initial fixes to get build to work without new JACK MIDI, and to get it running with...
[ardour.git] / libs / ardour / session.cc
1 /*
2     Copyright (C) 1999-2004 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <algorithm>
21 #include <string>
22 #include <vector>
23 #include <sstream>
24 #include <fstream>
25 #include <cstdio> /* sprintf(3) ... grrr */
26 #include <cmath>
27 #include <cerrno>
28 #include <unistd.h>
29 #include <limits.h>
30
31 #include <sigc++/bind.h>
32 #include <sigc++/retype.h>
33
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
36
37 #include <pbd/error.h>
38 #include <glibmm/thread.h>
39 #include <pbd/pathscanner.h>
40 #include <pbd/stl_delete.h>
41 #include <pbd/basename.h>
42 #include <pbd/stacktrace.h>
43
44 #include <ardour/audioengine.h>
45 #include <ardour/configuration.h>
46 #include <ardour/session.h>
47 #include <ardour/utils.h>
48 #include <ardour/audio_diskstream.h>
49 #include <ardour/audioplaylist.h>
50 #include <ardour/audioregion.h>
51 #include <ardour/audiofilesource.h>
52 #include <ardour/midi_diskstream.h>
53 #include <ardour/midi_playlist.h>
54 #include <ardour/midi_region.h>
55 #include <ardour/smf_source.h>
56 #include <ardour/auditioner.h>
57 #include <ardour/recent_sessions.h>
58 #include <ardour/redirect.h>
59 #include <ardour/send.h>
60 #include <ardour/insert.h>
61 #include <ardour/connection.h>
62 #include <ardour/slave.h>
63 #include <ardour/tempo.h>
64 #include <ardour/audio_track.h>
65 #include <ardour/midi_track.h>
66 #include <ardour/cycle_timer.h>
67 #include <ardour/named_selection.h>
68 #include <ardour/crossfade.h>
69 #include <ardour/playlist.h>
70 #include <ardour/click.h>
71 #include <ardour/data_type.h>
72 #include <ardour/buffer_set.h>
73 #include <ardour/source_factory.h>
74 #include <ardour/region_factory.h>
75
76 #ifdef HAVE_LIBLO
77 #include <ardour/osc.h>
78 #endif
79
80 #include "i18n.h"
81
82 using namespace std;
83 using namespace ARDOUR;
84 using namespace PBD;
85 using boost::shared_ptr;
86
87 #ifdef __x86_64__
88 static const int CPU_CACHE_ALIGN = 64;
89 #else
90 static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
91 #endif
92
93 const char* Session::_template_suffix = X_(".template");
94 const char* Session::_statefile_suffix = X_(".ardour");
95 const char* Session::_pending_suffix = X_(".pending");
96 const char* Session::old_sound_dir_name = X_("sounds");
97 const char* Session::sound_dir_name = X_("audiofiles");
98 const char* Session::peak_dir_name = X_("peaks");
99 const char* Session::dead_sound_dir_name = X_("dead_sounds");
100 const char* Session::interchange_dir_name = X_("interchange");
101 const char* Session::export_dir_name = X_("export");
102
103 Session::compute_peak_t                 Session::compute_peak           = 0;
104 Session::find_peaks_t                   Session::find_peaks             = 0;
105 Session::apply_gain_to_buffer_t         Session::apply_gain_to_buffer   = 0;
106 Session::mix_buffers_with_gain_t        Session::mix_buffers_with_gain  = 0;
107 Session::mix_buffers_no_gain_t          Session::mix_buffers_no_gain    = 0;
108
109 sigc::signal<int> Session::AskAboutPendingState;
110 sigc::signal<void> Session::SendFeedback;
111
112 sigc::signal<void> Session::SMPTEOffsetChanged;
113 sigc::signal<void> Session::StartTimeChanged;
114 sigc::signal<void> Session::EndTimeChanged;
115
116 int
117 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
118 {
119         struct stat statbuf;
120         char buf[PATH_MAX+1];
121
122         isnew = false;
123
124         if (!realpath (str.c_str(), buf) && (errno != ENOENT && errno != ENOTDIR)) {
125                 error << string_compose (_("Could not resolve path: %1 (%2)"), buf, strerror(errno)) << endmsg;
126                 return -1;
127         }
128
129         str = buf;
130         
131         /* check to see if it exists, and what it is */
132
133         if (stat (str.c_str(), &statbuf)) {
134                 if (errno == ENOENT) {
135                         isnew = true;
136                 } else {
137                         error << string_compose (_("cannot check session path %1 (%2)"), str, strerror (errno))
138                               << endmsg;
139                         return -1;
140                 }
141         }
142
143         if (!isnew) {
144
145                 /* it exists, so it must either be the name
146                    of the directory, or the name of the statefile
147                    within it.
148                 */
149
150                 if (S_ISDIR (statbuf.st_mode)) {
151
152                         string::size_type slash = str.find_last_of ('/');
153                 
154                         if (slash == string::npos) {
155                                 
156                                 /* a subdirectory of cwd, so statefile should be ... */
157
158                                 string tmp;
159                                 tmp = str;
160                                 tmp += '/';
161                                 tmp += str;
162                                 tmp += _statefile_suffix;
163
164                                 /* is it there ? */
165                                 
166                                 if (stat (tmp.c_str(), &statbuf)) {
167                                         error << string_compose (_("cannot check statefile %1 (%2)"), tmp, strerror (errno))
168                                               << endmsg;
169                                         return -1;
170                                 }
171
172                                 path = str;
173                                 snapshot = str;
174
175                         } else {
176
177                                 /* some directory someplace in the filesystem.
178                                    the snapshot name is the directory name
179                                    itself.
180                                 */
181
182                                 path = str;
183                                 snapshot = str.substr (slash+1);
184                                         
185                         }
186
187                 } else if (S_ISREG (statbuf.st_mode)) {
188                         
189                         string::size_type slash = str.find_last_of ('/');
190                         string::size_type suffix;
191
192                         /* remove the suffix */
193                         
194                         if (slash != string::npos) {
195                                 snapshot = str.substr (slash+1);
196                         } else {
197                                 snapshot = str;
198                         }
199
200                         suffix = snapshot.find (_statefile_suffix);
201                         
202                         if (suffix == string::npos) {
203                                 error << string_compose (_("%1 is not an Ardour snapshot file"), str) << endmsg;
204                                 return -1;
205                         }
206
207                         /* remove suffix */
208
209                         snapshot = snapshot.substr (0, suffix);
210                         
211                         if (slash == string::npos) {
212                                 
213                                 /* we must be in the directory where the 
214                                    statefile lives. get it using cwd().
215                                 */
216
217                                 char cwd[PATH_MAX+1];
218
219                                 if (getcwd (cwd, sizeof (cwd)) == 0) {
220                                         error << string_compose (_("cannot determine current working directory (%1)"), strerror (errno))
221                                               << endmsg;
222                                         return -1;
223                                 }
224
225                                 path = cwd;
226
227                         } else {
228
229                                 /* full path to the statefile */
230
231                                 path = str.substr (0, slash);
232                         }
233                                 
234                 } else {
235
236                         /* what type of file is it? */
237                         error << string_compose (_("unknown file type for session %1"), str) << endmsg;
238                         return -1;
239                 }
240
241         } else {
242
243                 /* its the name of a new directory. get the name
244                    as "dirname" does.
245                 */
246
247                 string::size_type slash = str.find_last_of ('/');
248
249                 if (slash == string::npos) {
250                         
251                         /* no slash, just use the name, but clean it up */
252                         
253                         path = legalize_for_path (str);
254                         snapshot = path;
255                         
256                 } else {
257                         
258                         path = str;
259                         snapshot = str.substr (slash+1);
260                 }
261         }
262
263         return 0;
264 }
265
266 Session::Session (AudioEngine &eng,
267                   string fullpath,
268                   string snapshot_name,
269                   string* mix_template)
270
271         : _engine (eng),
272           _scratch_buffers(new BufferSet()),
273           _silent_buffers(new BufferSet()),
274           _send_buffers(new BufferSet()),
275           _mmc_port (default_mmc_port),
276           _mtc_port (default_mtc_port),
277           _midi_port (default_midi_port),
278           pending_events (2048),
279           //midi_requests (128), // the size of this should match the midi request pool size
280           _send_smpte_update (false),
281           diskstreams (new DiskstreamList),
282           routes (new RouteList),
283           auditioner ((Auditioner*) 0),
284           _click_io ((IO*) 0),
285           main_outs (0)
286 {
287         bool new_session;
288
289         if (!eng.connected()) {
290                 throw failed_constructor();
291         }
292
293         cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
294
295         n_physical_outputs = _engine.n_physical_outputs();
296         n_physical_inputs =  _engine.n_physical_inputs();
297
298         first_stage_init (fullpath, snapshot_name);
299         
300         new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
301         if (new_session) {
302                 if (create (new_session, mix_template, compute_initial_length())) {
303                         cerr << "create failed\n";
304                         destroy ();
305                         throw failed_constructor ();
306                 }
307         }
308         
309         if (second_stage_init (new_session)) {
310                 destroy ();
311                 throw failed_constructor ();
312         }
313         
314         store_recent_sessions(_name, _path);
315         
316         bool was_dirty = dirty();
317
318         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
319
320         Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
321
322         if (was_dirty) {
323                 DirtyChanged (); /* EMIT SIGNAL */
324         }
325 }
326
327 Session::Session (AudioEngine &eng,
328                   string fullpath,
329                   string snapshot_name,
330                   AutoConnectOption input_ac,
331                   AutoConnectOption output_ac,
332                   uint32_t control_out_channels,
333                   uint32_t master_out_channels,
334                   uint32_t requested_physical_in,
335                   uint32_t requested_physical_out,
336                   nframes_t initial_length)
337
338         : _engine (eng),
339           _scratch_buffers(new BufferSet()),
340           _silent_buffers(new BufferSet()),
341           _send_buffers(new BufferSet()),
342           _mmc_port (default_mmc_port),
343           _mtc_port (default_mtc_port),
344           _midi_port (default_midi_port),
345           pending_events (2048),
346           //midi_requests (16),
347           _send_smpte_update (false),
348           diskstreams (new DiskstreamList),
349           routes (new RouteList),
350           main_outs (0)
351
352 {
353         bool new_session;
354
355         if (!eng.connected()) {
356                 throw failed_constructor();
357         }
358
359         cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
360
361         n_physical_outputs = _engine.n_physical_outputs();
362         n_physical_inputs = _engine.n_physical_inputs();
363
364         if (n_physical_inputs) {
365                 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
366         }
367
368         if (n_physical_outputs) {
369                 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
370         }
371
372         first_stage_init (fullpath, snapshot_name);
373
374         new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
375
376         if (new_session) {
377                 if (create (new_session, 0, initial_length)) {
378                         destroy ();
379                         throw failed_constructor ();
380                 }
381         }
382
383         {
384                 /* set up Master Out and Control Out if necessary */
385                 
386                 RouteList rl;
387                 int control_id = 1;
388                 
389                 if (control_out_channels) {
390                         shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
391                         r->set_remote_control_id (control_id++);
392                         
393                         rl.push_back (r);
394                 }
395                 
396                 if (master_out_channels) {
397                         shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
398                         r->set_remote_control_id (control_id);
399                          
400                         rl.push_back (r);
401                 } else {
402                         /* prohibit auto-connect to master, because there isn't one */
403                         output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
404                 }
405                 
406                 if (!rl.empty()) {
407                         add_routes (rl);
408                 }
409                 
410         }
411
412         Config->set_input_auto_connect (input_ac);
413         Config->set_output_auto_connect (output_ac);
414
415         if (second_stage_init (new_session)) {
416                 destroy ();
417                 throw failed_constructor ();
418         }
419         
420         store_recent_sessions(_name, _path);
421         
422         bool was_dirty = dirty ();
423
424         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
425
426         Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
427
428         if (was_dirty) {
429                 DirtyChanged (); /* EMIT SIGNAL */
430         }
431 }
432
433 Session::~Session ()
434 {
435         destroy ();
436 }
437
438 void
439 Session::destroy ()
440 {
441         /* if we got to here, leaving pending capture state around
442            is a mistake.
443         */
444
445         remove_pending_capture_state ();
446
447         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
448         _engine.remove_session ();
449
450         GoingAway (); /* EMIT SIGNAL */
451         
452         /* do this */
453
454         notify_callbacks ();
455
456         /* clear history so that no references to objects are held any more */
457
458         _history.clear ();
459
460         /* clear state tree so that no references to objects are held any more */
461         
462         if (state_tree) {
463                 delete state_tree;
464         }
465
466         terminate_butler_thread ();
467         //terminate_midi_thread ();
468         
469         if (click_data && click_data != default_click) {
470                 delete [] click_data;
471         }
472
473         if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
474                 delete [] click_emphasis_data;
475         }
476
477         clear_clicks ();
478
479         delete _scratch_buffers;
480         delete _silent_buffers;
481         delete _send_buffers;
482
483         AudioDiskstream::free_working_buffers();
484         
485 #undef TRACK_DESTRUCTION
486 #ifdef TRACK_DESTRUCTION
487         cerr << "delete named selections\n";
488 #endif /* TRACK_DESTRUCTION */
489         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
490                 NamedSelectionList::iterator tmp;
491
492                 tmp = i;
493                 ++tmp;
494
495                 delete *i;
496                 i = tmp;
497         }
498
499 #ifdef TRACK_DESTRUCTION
500         cerr << "delete playlists\n";
501 #endif /* TRACK_DESTRUCTION */
502         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
503                 PlaylistList::iterator tmp;
504
505                 tmp = i;
506                 ++tmp;
507
508                 (*i)->drop_references ();
509                 
510                 i = tmp;
511         }
512         
513         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
514                 PlaylistList::iterator tmp;
515
516                 tmp = i;
517                 ++tmp;
518
519                 (*i)->drop_references ();
520                 
521                 i = tmp;
522         }
523         
524         playlists.clear ();
525         unused_playlists.clear ();
526
527 #ifdef TRACK_DESTRUCTION
528         cerr << "delete regions\n";
529 #endif /* TRACK_DESTRUCTION */
530         
531         for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
532                 RegionList::iterator tmp;
533
534                 tmp = i;
535                 ++tmp;
536
537                 i->second->drop_references ();
538
539                 i = tmp;
540         }
541
542         regions.clear ();
543
544 #ifdef TRACK_DESTRUCTION
545         cerr << "delete routes\n";
546 #endif /* TRACK_DESTRUCTION */
547         {
548                 RCUWriter<RouteList> writer (routes);
549                 boost::shared_ptr<RouteList> r = writer.get_copy ();
550                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
551                         (*i)->drop_references ();
552                 }
553                 r->clear ();
554                 /* writer goes out of scope and updates master */
555         }
556
557         routes.flush ();
558
559 #ifdef TRACK_DESTRUCTION
560         cerr << "delete diskstreams\n";
561 #endif /* TRACK_DESTRUCTION */
562        {
563                RCUWriter<DiskstreamList> dwriter (diskstreams);
564                boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
565                for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
566                        (*i)->drop_references ();
567                }
568                dsl->clear ();
569        }
570        diskstreams.flush ();
571
572 #ifdef TRACK_DESTRUCTION
573         cerr << "delete audio sources\n";
574 #endif /* TRACK_DESTRUCTION */
575         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
576                 SourceMap::iterator tmp;
577
578                 tmp = i;
579                 ++tmp;
580
581                 i->second->drop_references ();
582
583                 i = tmp;
584         }
585
586         sources.clear ();
587
588 #ifdef TRACK_DESTRUCTION
589         cerr << "delete mix groups\n";
590 #endif /* TRACK_DESTRUCTION */
591         for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
592                 list<RouteGroup*>::iterator tmp;
593
594                 tmp = i;
595                 ++tmp;
596
597                 delete *i;
598
599                 i = tmp;
600         }
601
602 #ifdef TRACK_DESTRUCTION
603         cerr << "delete edit groups\n";
604 #endif /* TRACK_DESTRUCTION */
605         for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
606                 list<RouteGroup*>::iterator tmp;
607                 
608                 tmp = i;
609                 ++tmp;
610
611                 delete *i;
612
613                 i = tmp;
614         }
615         
616 #ifdef TRACK_DESTRUCTION
617         cerr << "delete connections\n";
618 #endif /* TRACK_DESTRUCTION */
619         for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ) {
620                 ConnectionList::iterator tmp;
621
622                 tmp = i;
623                 ++tmp;
624
625                 delete *i;
626
627                 i = tmp;
628         }
629
630         if (butler_mixdown_buffer) {
631                 delete [] butler_mixdown_buffer;
632         }
633
634         if (butler_gain_buffer) {
635                 delete [] butler_gain_buffer;
636         }
637
638         Crossfade::set_buffer_size (0);
639
640         if (mmc) {
641                 delete mmc;
642         }
643 }
644
645 void
646 Session::set_worst_io_latencies ()
647 {
648         _worst_output_latency = 0;
649         _worst_input_latency = 0;
650
651         if (!_engine.connected()) {
652                 return;
653         }
654
655         boost::shared_ptr<RouteList> r = routes.reader ();
656         
657         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
658                 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
659                 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
660         }
661 }
662
663 void
664 Session::when_engine_running ()
665 {
666         string first_physical_output;
667
668         /* we don't want to run execute this again */
669
670         set_block_size (_engine.frames_per_cycle());
671         set_frame_rate (_engine.frame_rate());
672
673         Config->map_parameters (mem_fun (*this, &Session::config_changed));
674
675         /* every time we reconnect, recompute worst case output latencies */
676
677         _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
678
679         if (synced_to_jack()) {
680                 _engine.transport_stop ();
681         }
682
683         if (Config->get_jack_time_master()) {
684                 _engine.transport_locate (_transport_frame);
685         }
686
687         _clicking = false;
688
689         try {
690                 XMLNode* child = 0;
691                 
692                 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
693
694                 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
695
696                         /* existing state for Click */
697                         
698                         if (_click_io->set_state (*child->children().front()) == 0) {
699                                 
700                                 _clicking = Config->get_clicking ();
701
702                         } else {
703
704                                 error << _("could not setup Click I/O") << endmsg;
705                                 _clicking = false;
706                         }
707
708                 } else {
709                         
710                         /* default state for Click */
711
712                         first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
713
714                         if (first_physical_output.length()) {
715                                 if (_click_io->add_output_port (first_physical_output, this)) {
716                                         // relax, even though its an error
717                                 } else {
718                                         _clicking = Config->get_clicking ();
719                                 }
720                         }
721                 }
722         }
723
724         catch (failed_constructor& err) {
725                 error << _("cannot setup Click I/O") << endmsg;
726         }
727
728         set_worst_io_latencies ();
729
730         if (_clicking) {
731                 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
732         }
733
734         /* Create a set of Connection objects that map
735            to the physical outputs currently available
736         */
737
738         /* ONE: MONO */
739
740         for (uint32_t np = 0; np < n_physical_outputs; ++np) {
741                 char buf[32];
742                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
743
744                 Connection* c = new OutputConnection (buf, true);
745
746                 c->add_port ();
747                 c->add_connection (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
748
749                 add_connection (c);
750         }
751
752         for (uint32_t np = 0; np < n_physical_inputs; ++np) {
753                 char buf[32];
754                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
755
756                 Connection* c = new InputConnection (buf, true);
757
758                 c->add_port ();
759                 c->add_connection (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
760
761                 add_connection (c);
762         }
763
764         /* TWO: STEREO */
765
766         for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
767                 char buf[32];
768                 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
769
770                 Connection* c = new OutputConnection (buf, true);
771
772                 c->add_port ();
773                 c->add_port ();
774                 c->add_connection (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
775                 c->add_connection (1, _engine.get_nth_physical_output (DataType::AUDIO, np+1));
776
777                 add_connection (c);
778         }
779
780         for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
781                 char buf[32];
782                 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
783
784                 Connection* c = new InputConnection (buf, true);
785
786                 c->add_port ();
787                 c->add_port ();
788                 c->add_connection (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
789                 c->add_connection (1, _engine.get_nth_physical_input (DataType::AUDIO, np+1));
790
791                 add_connection (c);
792         }
793
794         /* THREE MASTER */
795
796         if (_master_out) {
797
798                 /* create master/control ports */
799                 
800                 if (_master_out) {
801                         uint32_t n;
802
803                         /* force the master to ignore any later call to this */
804                         
805                         if (_master_out->pending_state_node) {
806                                 _master_out->ports_became_legal();
807                         }
808
809                         /* no panner resets till we are through */
810                         
811                         _master_out->defer_pan_reset ();
812                         
813                         while (_master_out->n_inputs().get(DataType::AUDIO)
814                                         < _master_out->input_maximum().get(DataType::AUDIO)) {
815                                 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
816                                         error << _("cannot setup master inputs") 
817                                               << endmsg;
818                                         break;
819                                 }
820                         }
821                         n = 0;
822                         while (_master_out->n_outputs().get(DataType::AUDIO)
823                                         < _master_out->output_maximum().get(DataType::AUDIO)) {
824                                 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
825                                         error << _("cannot setup master outputs")
826                                               << endmsg;
827                                         break;
828                                 }
829                                 n++;
830                         }
831
832                         _master_out->allow_pan_reset ();
833                         
834                 }
835
836                 Connection* c = new OutputConnection (_("Master Out"), true);
837
838                 for (uint32_t n = 0; n < _master_out->n_inputs ().get_total(); ++n) {
839                         c->add_port ();
840                         c->add_connection ((int) n, _master_out->input(n)->name());
841                 }
842                 add_connection (c);
843         } 
844
845         hookup_io ();
846
847         /* catch up on send+insert cnts */
848
849         insert_cnt = 0;
850         
851         for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
852                 uint32_t id;
853
854                 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
855                         if (id > insert_cnt) {
856                                 insert_cnt = id;
857                         }
858                 }
859         }
860
861         send_cnt = 0;
862
863         for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
864                 uint32_t id;
865                 
866                 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
867                         if (id > send_cnt) {
868                                 send_cnt = id;
869                         }
870                 }
871         }
872
873         
874         _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
875
876         /* hook us up to the engine */
877
878         _engine.set_session (this);
879
880 #ifdef HAVE_LIBLO
881         /* and to OSC */
882
883         osc->set_session (*this);
884 #endif
885
886         _state_of_the_state = Clean;
887
888         DirtyChanged (); /* EMIT SIGNAL */
889 }
890
891 void
892 Session::hookup_io ()
893 {
894         /* stop graph reordering notifications from
895            causing resorts, etc.
896         */
897
898         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
899
900         if (auditioner == 0) {
901                 
902                 /* we delay creating the auditioner till now because
903                    it makes its own connections to ports.
904                    the engine has to be running for this to work.
905                 */
906                 
907                 try {
908                         auditioner.reset (new Auditioner (*this));
909                 }
910                 
911                 catch (failed_constructor& err) {
912                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
913                 }
914         }
915
916         /* Tell all IO objects to create their ports */
917
918         IO::enable_ports ();
919
920         if (_control_out) {
921                 uint32_t n;
922
923                 while (_control_out->n_inputs().get(DataType::AUDIO) < _control_out->input_maximum().get(DataType::AUDIO)) {
924                         if (_control_out->add_input_port ("", this)) {
925                                 error << _("cannot setup control inputs")
926                                       << endmsg;
927                                 break;
928                         }
929                 }
930                 n = 0;
931                 while (_control_out->n_outputs().get(DataType::AUDIO) < _control_out->output_maximum().get(DataType::AUDIO)) {
932                         if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
933                                 error << _("cannot set up master outputs")
934                                       << endmsg;
935                                 break;
936                         }
937                         n++;
938                 }
939         }
940
941         /* Tell all IO objects to connect themselves together */
942
943         IO::enable_connecting ();
944
945         /* Now reset all panners */
946
947         IO::reset_panners ();
948
949         /* Anyone who cares about input state, wake up and do something */
950
951         IOConnectionsComplete (); /* EMIT SIGNAL */
952
953         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
954
955         /* now handle the whole enchilada as if it was one
956            graph reorder event.
957         */
958
959         graph_reordered ();
960
961         /* update mixer solo state */
962
963         catch_up_on_solo();
964 }
965
966 void
967 Session::playlist_length_changed ()
968 {
969         /* we can't just increase end_location->end() if pl->get_maximum_extent() 
970            if larger. if the playlist used to be the longest playlist,
971            and its now shorter, we have to decrease end_location->end(). hence,
972            we have to iterate over all diskstreams and check the 
973            playlists currently in use.
974         */
975         find_current_end ();
976 }
977
978 void
979 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
980 {
981         boost::shared_ptr<Playlist> playlist;
982
983         if ((playlist = dstream->playlist()) != 0) {
984                 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
985         }
986         
987         /* see comment in playlist_length_changed () */
988         find_current_end ();
989 }
990
991 bool
992 Session::record_enabling_legal () const
993 {
994         /* this used to be in here, but survey says.... we don't need to restrict it */
995         // if (record_status() == Recording) {
996         //      return false;
997         // }
998
999         if (Config->get_all_safe()) {
1000                 return false;
1001         }
1002         return true;
1003 }
1004
1005 void
1006 Session::reset_input_monitor_state ()
1007 {
1008         if (transport_rolling()) {
1009
1010                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1011
1012                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1013                         if ((*i)->record_enabled ()) {
1014                                 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1015                                 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
1016                         }
1017                 }
1018         } else {
1019                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1020
1021                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1022                         if ((*i)->record_enabled ()) {
1023                                 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
1024                                 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
1025                         }
1026                 }
1027         }
1028 }
1029
1030 void
1031 Session::auto_punch_start_changed (Location* location)
1032 {
1033         replace_event (Event::PunchIn, location->start());
1034
1035         if (get_record_enabled() && Config->get_punch_in()) {
1036                 /* capture start has been changed, so save new pending state */
1037                 save_state ("", true);
1038         }
1039 }       
1040
1041 void
1042 Session::auto_punch_end_changed (Location* location)
1043 {
1044         nframes_t when_to_stop = location->end();
1045         // when_to_stop += _worst_output_latency + _worst_input_latency;
1046         replace_event (Event::PunchOut, when_to_stop);
1047 }       
1048
1049 void
1050 Session::auto_punch_changed (Location* location)
1051 {
1052         nframes_t when_to_stop = location->end();
1053
1054         replace_event (Event::PunchIn, location->start());
1055         //when_to_stop += _worst_output_latency + _worst_input_latency;
1056         replace_event (Event::PunchOut, when_to_stop);
1057 }       
1058
1059 void
1060 Session::auto_loop_changed (Location* location)
1061 {
1062         replace_event (Event::AutoLoop, location->end(), location->start());
1063
1064         if (transport_rolling() && play_loop) {
1065
1066                 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
1067
1068                 if (_transport_frame > location->end()) {
1069                         // relocate to beginning of loop
1070                         clear_events (Event::LocateRoll);
1071                         
1072                         request_locate (location->start(), true);
1073
1074                 }
1075                 else if (Config->get_seamless_loop() && !loop_changing) {
1076                         
1077                         // schedule a locate-roll to refill the diskstreams at the
1078                         // previous loop end
1079                         loop_changing = true;
1080
1081                         if (location->end() > last_loopend) {
1082                                 clear_events (Event::LocateRoll);
1083                                 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1084                                 queue_event (ev);
1085                         }
1086
1087                 }
1088         }       
1089
1090         last_loopend = location->end();
1091         
1092 }
1093
1094 void
1095 Session::set_auto_punch_location (Location* location)
1096 {
1097         Location* existing;
1098
1099         if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1100                 auto_punch_start_changed_connection.disconnect();
1101                 auto_punch_end_changed_connection.disconnect();
1102                 auto_punch_changed_connection.disconnect();
1103                 existing->set_auto_punch (false, this);
1104                 remove_event (existing->start(), Event::PunchIn);
1105                 clear_events (Event::PunchOut);
1106                 auto_punch_location_changed (0);
1107         }
1108
1109         set_dirty();
1110
1111         if (location == 0) {
1112                 return;
1113         }
1114         
1115         if (location->end() <= location->start()) {
1116                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1117                 return;
1118         }
1119
1120         auto_punch_start_changed_connection.disconnect();
1121         auto_punch_end_changed_connection.disconnect();
1122         auto_punch_changed_connection.disconnect();
1123                 
1124         auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1125         auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1126         auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1127
1128         location->set_auto_punch (true, this);
1129         auto_punch_location_changed (location);
1130 }
1131
1132 void
1133 Session::set_auto_loop_location (Location* location)
1134 {
1135         Location* existing;
1136
1137         if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1138                 auto_loop_start_changed_connection.disconnect();
1139                 auto_loop_end_changed_connection.disconnect();
1140                 auto_loop_changed_connection.disconnect();
1141                 existing->set_auto_loop (false, this);
1142                 remove_event (existing->end(), Event::AutoLoop);
1143                 auto_loop_location_changed (0);
1144         }
1145         
1146         set_dirty();
1147
1148         if (location == 0) {
1149                 return;
1150         }
1151
1152         if (location->end() <= location->start()) {
1153                 error << _("Session: you can't use a mark for auto loop") << endmsg;
1154                 return;
1155         }
1156
1157         last_loopend = location->end();
1158         
1159         auto_loop_start_changed_connection.disconnect();
1160         auto_loop_end_changed_connection.disconnect();
1161         auto_loop_changed_connection.disconnect();
1162         
1163         auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1164         auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1165         auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1166
1167         location->set_auto_loop (true, this);
1168         auto_loop_location_changed (location);
1169 }
1170
1171 void
1172 Session::locations_added (Location* ignored)
1173 {
1174         set_dirty ();
1175 }
1176
1177 void
1178 Session::locations_changed ()
1179 {
1180         _locations.apply (*this, &Session::handle_locations_changed);
1181 }
1182
1183 void
1184 Session::handle_locations_changed (Locations::LocationList& locations)
1185 {
1186         Locations::LocationList::iterator i;
1187         Location* location;
1188         bool set_loop = false;
1189         bool set_punch = false;
1190
1191         for (i = locations.begin(); i != locations.end(); ++i) {
1192
1193                 location =* i;
1194
1195                 if (location->is_auto_punch()) {
1196                         set_auto_punch_location (location);
1197                         set_punch = true;
1198                 }
1199                 if (location->is_auto_loop()) {
1200                         set_auto_loop_location (location);
1201                         set_loop = true;
1202                 }
1203                 
1204         }
1205
1206         if (!set_loop) {
1207                 set_auto_loop_location (0);
1208         }
1209         if (!set_punch) {
1210                 set_auto_punch_location (0);
1211         }
1212
1213         set_dirty();
1214 }                                                    
1215
1216 void
1217 Session::enable_record ()
1218 {
1219         /* XXX really atomic compare+swap here */
1220         if (g_atomic_int_get (&_record_status) != Recording) {
1221                 g_atomic_int_set (&_record_status, Recording);
1222                 _last_record_location = _transport_frame;
1223                 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1224
1225                 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1226                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1227                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1228                                 if ((*i)->record_enabled ()) {
1229                                         (*i)->monitor_input (true);   
1230                                 }
1231                         }
1232                 }
1233
1234                 RecordStateChanged ();
1235         }
1236 }
1237
1238 void
1239 Session::disable_record (bool rt_context, bool force)
1240 {
1241         RecordState rs;
1242
1243         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1244
1245                 if (!Config->get_latched_record_enable () || force) {
1246                         g_atomic_int_set (&_record_status, Disabled);
1247                 } else {
1248                         if (rs == Recording) {
1249                                 g_atomic_int_set (&_record_status, Enabled);
1250                         }
1251                 }
1252
1253                 // FIXME: timestamp correct? [DR]
1254                 // FIXME FIXME FIXME: rt_context?  this must be called in the process thread.
1255                 // does this /need/ to be sent in all cases?
1256                 if (rt_context)
1257                         deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1258
1259                 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1260                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1261                         
1262                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1263                                 if ((*i)->record_enabled ()) {
1264                                         (*i)->monitor_input (false);   
1265                                 }
1266                         }
1267                 }
1268                 
1269                 RecordStateChanged (); /* emit signal */
1270
1271                 if (!rt_context) {
1272                         remove_pending_capture_state ();
1273                 }
1274         }
1275 }
1276
1277 void
1278 Session::step_back_from_record ()
1279 {
1280         g_atomic_int_set (&_record_status, Enabled);
1281
1282         if (Config->get_monitoring_model() == HardwareMonitoring) {
1283                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1284                 
1285                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1286                         if (Config->get_auto_input() && (*i)->record_enabled ()) {
1287                                 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1288                                 (*i)->monitor_input (false);   
1289                         }
1290                 }
1291         }
1292 }
1293
1294 void
1295 Session::maybe_enable_record ()
1296 {
1297         g_atomic_int_set (&_record_status, Enabled);
1298
1299         /* this function is currently called from somewhere other than an RT thread.
1300            this save_state() call therefore doesn't impact anything.
1301         */
1302
1303         save_state ("", true);
1304
1305         if (_transport_speed) {
1306                 if (!Config->get_punch_in()) {
1307                         enable_record ();
1308                 } 
1309         } else {
1310                 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1311                 RecordStateChanged (); /* EMIT SIGNAL */
1312         }
1313
1314         set_dirty();
1315 }
1316
1317 nframes_t
1318 Session::audible_frame () const
1319 {
1320         nframes_t ret;
1321         nframes_t offset;
1322         nframes_t tf;
1323
1324         /* the first of these two possible settings for "offset"
1325            mean that the audible frame is stationary until 
1326            audio emerges from the latency compensation
1327            "pseudo-pipeline".
1328
1329            the second means that the audible frame is stationary
1330            until audio would emerge from a physical port
1331            in the absence of any plugin latency compensation
1332         */
1333
1334         offset = _worst_output_latency;
1335
1336         if (offset > current_block_size) {
1337                 offset -= current_block_size;
1338         } else { 
1339                 /* XXX is this correct? if we have no external
1340                    physical connections and everything is internal
1341                    then surely this is zero? still, how
1342                    likely is that anyway?
1343                 */
1344                 offset = current_block_size;
1345         }
1346
1347         if (synced_to_jack()) {
1348                 tf = _engine.transport_frame();
1349         } else {
1350                 tf = _transport_frame;
1351         }
1352
1353         if (_transport_speed == 0) {
1354                 return tf;
1355         }
1356
1357         if (tf < offset) {
1358                 return 0;
1359         }
1360
1361         ret = tf;
1362
1363         if (!non_realtime_work_pending()) {
1364
1365                 /* MOVING */
1366
1367                 /* take latency into account */
1368                 
1369                 ret -= offset;
1370         }
1371
1372         return ret;
1373 }
1374
1375 void
1376 Session::set_frame_rate (nframes_t frames_per_second)
1377 {
1378         /** \fn void Session::set_frame_size(nframes_t)
1379                 the AudioEngine object that calls this guarantees 
1380                 that it will not be called while we are also in
1381                 ::process(). Its fine to do things that block
1382                 here.
1383         */
1384
1385         _base_frame_rate = frames_per_second;
1386
1387         sync_time_vars();
1388
1389         Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
1390
1391         // XXX we need some equivalent to this, somehow
1392         // SndFileSource::setup_standard_crossfades (frames_per_second);
1393
1394         set_dirty();
1395
1396         /* XXX need to reset/reinstantiate all LADSPA plugins */
1397 }
1398
1399 void
1400 Session::set_block_size (nframes_t nframes)
1401 {
1402         /* the AudioEngine guarantees 
1403            that it will not be called while we are also in
1404            ::process(). It is therefore fine to do things that block
1405            here.
1406         */
1407
1408         { 
1409                         
1410                 current_block_size = nframes;
1411
1412                 ensure_buffers(_scratch_buffers->available());
1413
1414                 if (_gain_automation_buffer) {
1415                         delete [] _gain_automation_buffer;
1416                 }
1417                 _gain_automation_buffer = new gain_t[nframes];
1418
1419                 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1420
1421                 boost::shared_ptr<RouteList> r = routes.reader ();
1422
1423                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1424                         (*i)->set_block_size (nframes);
1425                 }
1426                 
1427                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1428                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1429                         (*i)->set_block_size (nframes);
1430                 }
1431
1432                 set_worst_io_latencies ();
1433         }
1434 }
1435
1436 void
1437 Session::set_default_fade (float steepness, float fade_msecs)
1438 {
1439 #if 0
1440         nframes_t fade_frames;
1441         
1442         /* Don't allow fade of less 1 frame */
1443         
1444         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1445
1446                 fade_msecs = 0;
1447                 fade_frames = 0;
1448
1449         } else {
1450                 
1451                 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1452                 
1453         }
1454
1455         default_fade_msecs = fade_msecs;
1456         default_fade_steepness = steepness;
1457
1458         {
1459                 // jlc, WTF is this!
1460                 Glib::RWLock::ReaderLock lm (route_lock);
1461                 AudioRegion::set_default_fade (steepness, fade_frames);
1462         }
1463
1464         set_dirty();
1465
1466         /* XXX have to do this at some point */
1467         /* foreach region using default fade, reset, then 
1468            refill_all_diskstream_buffers ();
1469         */
1470 #endif
1471 }
1472
1473 struct RouteSorter {
1474     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1475             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1476                     return false;
1477             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1478                     return true;
1479             } else {
1480                     if (r1->fed_by.empty()) {
1481                             if (r2->fed_by.empty()) {
1482                                     /* no ardour-based connections inbound to either route. just use signal order */
1483                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1484                             } else {
1485                                     /* r2 has connections, r1 does not; run r1 early */
1486                                     return true;
1487                             }
1488                     } else {
1489                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1490                     }
1491             }
1492     }
1493 };
1494
1495 static void
1496 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1497 {
1498         shared_ptr<Route> r2;
1499
1500         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1501                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1502                 return;
1503         } 
1504
1505         /* make a copy of the existing list of routes that feed r1 */
1506
1507         set<shared_ptr<Route> > existing = r1->fed_by;
1508
1509         /* for each route that feeds r1, recurse, marking it as feeding
1510            rbase as well.
1511         */
1512
1513         for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1514                 r2 =* i;
1515
1516                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1517                    base as being fed by r2
1518                 */
1519
1520                 rbase->fed_by.insert (r2);
1521
1522                 if (r2 != rbase) {
1523
1524                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1525                            stop here.
1526                          */
1527
1528                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1529                                 continue;
1530                         }
1531
1532                         /* now recurse, so that we can mark base as being fed by
1533                            all routes that feed r2
1534                         */
1535
1536                         trace_terminal (r2, rbase);
1537                 }
1538
1539         }
1540 }
1541
1542 void
1543 Session::resort_routes ()
1544 {
1545         /* don't do anything here with signals emitted
1546            by Routes while we are being destroyed.
1547         */
1548
1549         if (_state_of_the_state & Deletion) {
1550                 return;
1551         }
1552
1553
1554         {
1555
1556                 RCUWriter<RouteList> writer (routes);
1557                 shared_ptr<RouteList> r = writer.get_copy ();
1558                 resort_routes_using (r);
1559                 /* writer goes out of scope and forces update */
1560         }
1561
1562 }
1563 void
1564 Session::resort_routes_using (shared_ptr<RouteList> r)
1565 {
1566         RouteList::iterator i, j;
1567         
1568         for (i = r->begin(); i != r->end(); ++i) {
1569                 
1570                 (*i)->fed_by.clear ();
1571                 
1572                 for (j = r->begin(); j != r->end(); ++j) {
1573                         
1574                         /* although routes can feed themselves, it will
1575                            cause an endless recursive descent if we
1576                            detect it. so don't bother checking for
1577                            self-feeding.
1578                         */
1579                         
1580                         if (*j == *i) {
1581                                 continue;
1582                         }
1583                         
1584                         if ((*j)->feeds (*i)) {
1585                                 (*i)->fed_by.insert (*j);
1586                         } 
1587                 }
1588         }
1589         
1590         for (i = r->begin(); i != r->end(); ++i) {
1591                 trace_terminal (*i, *i);
1592         }
1593         
1594         RouteSorter cmp;
1595         r->sort (cmp);
1596         
1597 #if 0
1598         cerr << "finished route resort\n";
1599         
1600         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1601                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1602         }
1603         cerr << endl;
1604 #endif
1605         
1606 }
1607
1608 list<boost::shared_ptr<MidiTrack> >
1609 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1610 {
1611         char track_name[32];
1612         uint32_t track_id = 0;
1613         uint32_t n = 0;
1614         uint32_t channels_used = 0;
1615         string port;
1616         RouteList new_routes;
1617         list<boost::shared_ptr<MidiTrack> > ret;
1618
1619         /* count existing midi tracks */
1620
1621         {
1622                 shared_ptr<RouteList> r = routes.reader ();
1623
1624                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1625                         if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1626                                 if (!(*i)->hidden()) {
1627                                         n++;
1628                                         channels_used += (*i)->n_inputs().get(DataType::MIDI);
1629                                 }
1630                         }
1631                 }
1632         }
1633
1634         while (how_many) {
1635
1636                 /* check for duplicate route names, since we might have pre-existing
1637                    routes with this name (e.g. create Midi1, Midi2, delete Midi1,
1638                    save, close,restart,add new route - first named route is now
1639                    Midi2)
1640                 */
1641                 
1642
1643                 do {
1644                         ++track_id;
1645
1646                         snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1647
1648                         if (route_by_name (track_name) == 0) {
1649                                 break;
1650                         }
1651                         
1652                 } while (track_id < (UINT_MAX-1));
1653
1654                 try {
1655                         shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1656                         
1657                         if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::MIDI, 1), false, this)) {
1658                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1659                         }
1660                         
1661                         channels_used += track->n_inputs ().get(DataType::MIDI);
1662
1663                         track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1664                         track->set_remote_control_id (ntracks());
1665
1666                         new_routes.push_back (track);
1667                         ret.push_back (track);
1668                 }
1669
1670                 catch (failed_constructor &err) {
1671                         error << _("Session: could not create new midi track.") << endmsg;
1672                         // XXX should we delete the tracks already created? 
1673                         ret.clear ();
1674                         return ret;
1675                 }
1676                 
1677                 --how_many;
1678         }
1679
1680         if (!new_routes.empty()) {
1681                 add_routes (new_routes, false);
1682                 save_state (_current_snapshot_name);
1683         }
1684
1685         return ret;
1686 }
1687
1688 list<boost::shared_ptr<AudioTrack> >
1689 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1690 {
1691         char track_name[32];
1692         uint32_t track_id = 0;
1693         uint32_t n = 0;
1694         uint32_t channels_used = 0;
1695         string port;
1696         RouteList new_routes;
1697         list<boost::shared_ptr<AudioTrack> > ret;
1698         uint32_t control_id;
1699
1700         /* count existing audio tracks */
1701
1702         {
1703                 shared_ptr<RouteList> r = routes.reader ();
1704
1705                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1706                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1707                                 if (!(*i)->hidden()) {
1708                                         n++;
1709                                         channels_used += (*i)->n_inputs().get(DataType::AUDIO);
1710                                 }
1711                         }
1712                 }
1713         }
1714
1715         vector<string> physinputs;
1716         vector<string> physoutputs;
1717         uint32_t nphysical_in;
1718         uint32_t nphysical_out;
1719
1720         _engine.get_physical_outputs (physoutputs);
1721         _engine.get_physical_inputs (physinputs);
1722         control_id = ntracks() + nbusses() + 1;
1723
1724         while (how_many) {
1725
1726                 /* check for duplicate route names, since we might have pre-existing
1727                    routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1728                    save, close,restart,add new route - first named route is now
1729                    Audio2)
1730                 */
1731                 
1732
1733                 do {
1734                         ++track_id;
1735
1736                         snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1737
1738                         if (route_by_name (track_name) == 0) {
1739                                 break;
1740                         }
1741                         
1742                 } while (track_id < (UINT_MAX-1));
1743
1744                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1745                         nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1746                 } else {
1747                         nphysical_in = 0;
1748                 }
1749                 
1750                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1751                         nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1752                 } else {
1753                         nphysical_out = 0;
1754                 }
1755
1756                 shared_ptr<AudioTrack> track;
1757                 
1758                 try {
1759                         track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1760                         
1761                         if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1762                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1763                                                          input_channels, output_channels)
1764                                       << endmsg;
1765                                 goto failed;
1766                         }
1767
1768                         if (nphysical_in) {
1769                                 for (uint32_t x = 0; x < track->n_inputs().get(DataType::AUDIO) && x < nphysical_in; ++x) {
1770                                         
1771                                         port = "";
1772                                         
1773                                         if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1774                                                 port = physinputs[(channels_used+x)%nphysical_in];
1775                                         } 
1776                                         
1777                                         if (port.length() && track->connect_input (track->input (x), port, this)) {
1778                                                 break;
1779                                         }
1780                                 }
1781                         }
1782                         
1783                         for (uint32_t x = 0; x < track->n_outputs().get(DataType::MIDI); ++x) {
1784                                 
1785                                 port = "";
1786                                 
1787                                 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1788                                         port = physoutputs[(channels_used+x)%nphysical_out];
1789                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1790                                         if (_master_out) {
1791                                                 port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
1792                                         }
1793                                 }
1794                                 
1795                                 if (port.length() && track->connect_output (track->output (x), port, this)) {
1796                                         break;
1797                                 }
1798                         }
1799                         
1800                         channels_used += track->n_inputs ().get(DataType::AUDIO);
1801
1802                         if (_control_out) {
1803                                 vector<string> cports;
1804                                 uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
1805                                 
1806                                 for (n = 0; n < ni; ++n) {
1807                                         cports.push_back (_control_out->input(n)->name());
1808                                 }
1809                                 
1810                                 track->set_control_outs (cports);
1811                         }
1812
1813                         // assert (current_thread != RT_thread)
1814                         
1815                         track->audio_diskstream()->non_realtime_input_change();
1816                         
1817                         track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1818                         track->set_remote_control_id (control_id);
1819                         ++control_id;
1820
1821                         new_routes.push_back (track);
1822                         ret.push_back (track);
1823                 }
1824
1825                 catch (failed_constructor &err) {
1826                         error << _("Session: could not create new audio track.") << endmsg;
1827
1828                         if (track) {
1829                                 /* we need to get rid of this, since the track failed to be created */
1830                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1831
1832                                 { 
1833                                         RCUWriter<DiskstreamList> writer (diskstreams);
1834                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1835                                         ds->remove (track->audio_diskstream());
1836                                 }
1837                         }
1838
1839                         goto failed;
1840                 }
1841
1842                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1843
1844                         error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1845
1846                         if (track) {
1847                                 /* we need to get rid of this, since the track failed to be created */
1848                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1849
1850                                 { 
1851                                         RCUWriter<DiskstreamList> writer (diskstreams);
1852                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1853                                         ds->remove (track->audio_diskstream());
1854                                 }
1855                         }
1856
1857                         goto failed;
1858                 }
1859
1860                 --how_many;
1861         }
1862
1863   failed:
1864         if (!new_routes.empty()) {
1865                 add_routes (new_routes, false);
1866                 save_state (_current_snapshot_name);
1867         }
1868
1869         return ret;
1870 }
1871
1872 void
1873 Session::set_remote_control_ids ()
1874 {
1875         RemoteModel m = Config->get_remote_model();
1876
1877         shared_ptr<RouteList> r = routes.reader ();
1878
1879         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1880                 if ( MixerOrdered == m) {                       
1881                         long order = (*i)->order_key(N_("signal"));
1882                         (*i)->set_remote_control_id( order+1 );
1883                 } else if ( EditorOrdered == m) {
1884                         long order = (*i)->order_key(N_("editor"));
1885                         (*i)->set_remote_control_id( order+1 );
1886                 } else if ( UserOrdered == m) {
1887                         //do nothing ... only changes to remote id's are initiated by user 
1888                 }
1889         }
1890 }
1891
1892
1893 Session::RouteList
1894 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1895 {
1896         char bus_name[32];
1897         uint32_t bus_id = 1;
1898         uint32_t n = 0;
1899         string port;
1900         RouteList ret;
1901         uint32_t control_id;
1902
1903         /* count existing audio busses */
1904
1905         {
1906                 shared_ptr<RouteList> r = routes.reader ();
1907
1908                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1909                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1910                                 if (!(*i)->hidden() && (*i)->name() != _("master")) {
1911                                         bus_id++;
1912                                 }
1913                         }
1914                 }
1915         }
1916
1917         vector<string> physinputs;
1918         vector<string> physoutputs;
1919
1920         _engine.get_physical_outputs (physoutputs);
1921         _engine.get_physical_inputs (physinputs);
1922         control_id = ntracks() + nbusses() + 1;
1923
1924         while (how_many) {
1925
1926                 do {
1927                         snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1928
1929                         if (route_by_name (bus_name) == 0) {
1930                                 break;
1931                         }
1932
1933                 } while (++bus_id < (UINT_MAX-1));
1934
1935                 try {
1936                         shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1937                         
1938                         if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1939                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1940                                                          input_channels, output_channels)
1941                                       << endmsg;
1942                                 goto failure;
1943                         }
1944                         
1945                         for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().get(DataType::AUDIO); ++x) {
1946                                 
1947                                 port = "";
1948
1949                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1950                                                 port = physinputs[((n+x)%n_physical_inputs)];
1951                                 } 
1952                                 
1953                                 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1954                                         break;
1955                                 }
1956                         }
1957                         
1958                         for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().get(DataType::AUDIO); ++x) {
1959                                 
1960                                 port = "";
1961                                 
1962                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1963                                         port = physoutputs[((n+x)%n_physical_outputs)];
1964                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1965                                         if (_master_out) {
1966                                                 port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
1967                                         }
1968                                 }
1969                                 
1970                                 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1971                                         break;
1972                                 }
1973                         }
1974                         
1975                         if (_control_out) {
1976                                 vector<string> cports;
1977                                 uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
1978                                 
1979                                 for (uint32_t n = 0; n < ni; ++n) {
1980                                         cports.push_back (_control_out->input(n)->name());
1981                                 }
1982                                 bus->set_control_outs (cports);
1983                         }
1984
1985                         bus->set_remote_control_id (control_id);
1986                         ++control_id;
1987
1988                         ret.push_back (bus);
1989                 }
1990         
1991
1992                 catch (failed_constructor &err) {
1993                         error << _("Session: could not create new audio route.") << endmsg;
1994                         goto failure;
1995                 }
1996
1997                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1998                         error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1999                         goto failure;
2000                 }
2001
2002
2003                 --how_many;
2004         }
2005
2006   failure:
2007         if (!ret.empty()) {
2008                 add_routes (ret, false);
2009                 save_state (_current_snapshot_name);
2010         }
2011
2012         return ret;
2013
2014 }
2015
2016 void
2017 Session::add_routes (RouteList& new_routes, bool save)
2018 {
2019         { 
2020                 RCUWriter<RouteList> writer (routes);
2021                 shared_ptr<RouteList> r = writer.get_copy ();
2022                 r->insert (r->end(), new_routes.begin(), new_routes.end());
2023                 resort_routes_using (r);
2024         }
2025
2026         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2027                 
2028                 boost::weak_ptr<Route> wpr (*x);
2029
2030                 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
2031                 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
2032                 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
2033                 (*x)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
2034                 
2035                 if ((*x)->master()) {
2036                         _master_out = (*x);
2037                 }
2038                 
2039                 if ((*x)->control()) {
2040                         _control_out = (*x);
2041                 }
2042         }
2043
2044         set_dirty();
2045
2046         if (save) {
2047                 save_state (_current_snapshot_name);
2048         }
2049
2050         RouteAdded (new_routes); /* EMIT SIGNAL */
2051 }
2052
2053 void
2054 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2055 {
2056         /* need to do this in case we're rolling at the time, to prevent false underruns */
2057         dstream->do_refill_with_alloc ();
2058         
2059         dstream->set_block_size (current_block_size);
2060
2061         {
2062                 RCUWriter<DiskstreamList> writer (diskstreams);
2063                 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2064                 ds->push_back (dstream);
2065                 /* writer goes out of scope, copies ds back to main */
2066         } 
2067
2068         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2069         /* this will connect to future changes, and check the current length */
2070         diskstream_playlist_changed (dstream);
2071
2072         dstream->prepare ();
2073
2074 }
2075
2076 void
2077 Session::remove_route (shared_ptr<Route> route)
2078 {
2079         {       
2080                 RCUWriter<RouteList> writer (routes);
2081                 shared_ptr<RouteList> rs = writer.get_copy ();
2082                 
2083                 rs->remove (route);
2084
2085                 /* deleting the master out seems like a dumb
2086                    idea, but its more of a UI policy issue
2087                    than our concern.
2088                 */
2089
2090                 if (route == _master_out) {
2091                         _master_out = shared_ptr<Route> ();
2092                 }
2093
2094                 if (route == _control_out) {
2095                         _control_out = shared_ptr<Route> ();
2096
2097                         /* cancel control outs for all routes */
2098
2099                         vector<string> empty;
2100
2101                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2102                                 (*r)->set_control_outs (empty);
2103                         }
2104                 }
2105
2106                 update_route_solo_state ();
2107                 
2108                 /* writer goes out of scope, forces route list update */
2109         }
2110
2111         Track* t;
2112         boost::shared_ptr<Diskstream> ds;
2113         
2114         if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2115                 ds = t->diskstream();
2116         }
2117         
2118         if (ds) {
2119
2120                 {
2121                         RCUWriter<DiskstreamList> dsl (diskstreams);
2122                         boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2123                         d->remove (ds);
2124                 }
2125         }
2126
2127         find_current_end ();
2128         
2129         update_latency_compensation (false, false);
2130         set_dirty();
2131
2132         // We need to disconnect the routes inputs and outputs 
2133         route->disconnect_inputs(NULL);
2134         route->disconnect_outputs(NULL);
2135         
2136         /* get rid of it from the dead wood collection in the route list manager */
2137
2138         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2139
2140         routes.flush ();
2141
2142         /* try to cause everyone to drop their references */
2143
2144         route->drop_references ();
2145
2146         /* save the new state of the world */
2147
2148         if (save_state (_current_snapshot_name)) {
2149                 save_history (_current_snapshot_name);
2150         }
2151 }       
2152
2153 void
2154 Session::route_mute_changed (void* src)
2155 {
2156         set_dirty ();
2157 }
2158
2159 void
2160 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2161 {      
2162         if (solo_update_disabled) {
2163                 // We know already
2164                 return;
2165         }
2166         
2167         bool is_track;
2168         boost::shared_ptr<Route> route = wpr.lock ();
2169
2170         if (!route) {
2171                 /* should not happen */
2172                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2173                 return;
2174         }
2175
2176         is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2177         
2178         shared_ptr<RouteList> r = routes.reader ();
2179
2180         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2181                 
2182                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2183                 
2184                 if (is_track) {
2185                         
2186                         /* don't mess with busses */
2187                         
2188                         if (dynamic_cast<Track*>((*i).get()) == 0) {
2189                                 continue;
2190                         }
2191                         
2192                 } else {
2193                         
2194                         /* don't mess with tracks */
2195                         
2196                         if (dynamic_cast<Track*>((*i).get()) != 0) {
2197                                 continue;
2198                         }
2199                 }
2200                 
2201                 if ((*i) != route &&
2202                     ((*i)->mix_group () == 0 ||
2203                      (*i)->mix_group () != route->mix_group () ||
2204                      !route->mix_group ()->is_active())) {
2205                         
2206                         if ((*i)->soloed()) {
2207                                 
2208                                 /* if its already soloed, and solo latching is enabled,
2209                                    then leave it as it is.
2210                                 */
2211                                 
2212                                 if (Config->get_solo_latched()) {
2213                                         continue;
2214                                 } 
2215                         }
2216                         
2217                         /* do it */
2218
2219                         solo_update_disabled = true;
2220                         (*i)->set_solo (false, src);
2221                         solo_update_disabled = false;
2222                 }
2223         }
2224         
2225         bool something_soloed = false;
2226         bool same_thing_soloed = false;
2227         bool signal = false;
2228
2229         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2230                 if ((*i)->soloed()) {
2231                         something_soloed = true;
2232                         if (dynamic_cast<Track*>((*i).get())) {
2233                                 if (is_track) {
2234                                         same_thing_soloed = true;
2235                                         break;
2236                                 }
2237                         } else {
2238                                 if (!is_track) {
2239                                         same_thing_soloed = true;
2240                                         break;
2241                                 }
2242                         }
2243                         break;
2244                 }
2245         }
2246         
2247         if (something_soloed != currently_soloing) {
2248                 signal = true;
2249                 currently_soloing = something_soloed;
2250         }
2251         
2252         modify_solo_mute (is_track, same_thing_soloed);
2253
2254         if (signal) {
2255                 SoloActive (currently_soloing); /* EMIT SIGNAL */
2256         }
2257
2258         SoloChanged (); /* EMIT SIGNAL */
2259
2260         set_dirty();
2261 }
2262
2263 void
2264 Session::update_route_solo_state ()
2265 {
2266         bool mute = false;
2267         bool is_track = false;
2268         bool signal = false;
2269
2270         /* caller must hold RouteLock */
2271
2272         /* this is where we actually implement solo by changing
2273            the solo mute setting of each track.
2274         */
2275         
2276         shared_ptr<RouteList> r = routes.reader ();
2277
2278         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2279                 if ((*i)->soloed()) {
2280                         mute = true;
2281                         if (dynamic_cast<Track*>((*i).get())) {
2282                                 is_track = true;
2283                         }
2284                         break;
2285                 }
2286         }
2287
2288         if (mute != currently_soloing) {
2289                 signal = true;
2290                 currently_soloing = mute;
2291         }
2292
2293         if (!is_track && !mute) {
2294
2295                 /* nothing is soloed */
2296
2297                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2298                         (*i)->set_solo_mute (false);
2299                 }
2300                 
2301                 if (signal) {
2302                         SoloActive (false);
2303                 }
2304
2305                 return;
2306         }
2307
2308         modify_solo_mute (is_track, mute);
2309
2310         if (signal) {
2311                 SoloActive (currently_soloing);
2312         }
2313 }
2314
2315 void
2316 Session::modify_solo_mute (bool is_track, bool mute)
2317 {
2318         shared_ptr<RouteList> r = routes.reader ();
2319
2320         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2321                 
2322                 if (is_track) {
2323                         
2324                         /* only alter track solo mute */
2325                         
2326                         if (dynamic_cast<Track*>((*i).get())) {
2327                                 if ((*i)->soloed()) {
2328                                         (*i)->set_solo_mute (!mute);
2329                                 } else {
2330                                         (*i)->set_solo_mute (mute);
2331                                 }
2332                         }
2333
2334                 } else {
2335
2336                         /* only alter bus solo mute */
2337
2338                         if (!dynamic_cast<Track*>((*i).get())) {
2339
2340                                 if ((*i)->soloed()) {
2341
2342                                         (*i)->set_solo_mute (false);
2343
2344                                 } else {
2345
2346                                         /* don't mute master or control outs
2347                                            in response to another bus solo
2348                                         */
2349                                         
2350                                         if ((*i) != _master_out &&
2351                                             (*i) != _control_out) {
2352                                                 (*i)->set_solo_mute (mute);
2353                                         }
2354                                 }
2355                         }
2356
2357                 }
2358         }
2359 }       
2360
2361
2362 void
2363 Session::catch_up_on_solo ()
2364 {
2365         /* this is called after set_state() to catch the full solo
2366            state, which can't be correctly determined on a per-route
2367            basis, but needs the global overview that only the session
2368            has.
2369         */
2370         update_route_solo_state();
2371 }       
2372                 
2373 shared_ptr<Route>
2374 Session::route_by_name (string name)
2375 {
2376         shared_ptr<RouteList> r = routes.reader ();
2377
2378         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2379                 if ((*i)->name() == name) {
2380                         return *i;
2381                 }
2382         }
2383
2384         return shared_ptr<Route> ((Route*) 0);
2385 }
2386
2387 shared_ptr<Route>
2388 Session::route_by_id (PBD::ID id)
2389 {
2390         shared_ptr<RouteList> r = routes.reader ();
2391
2392         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2393                 if ((*i)->id() == id) {
2394                         return *i;
2395                 }
2396         }
2397
2398         return shared_ptr<Route> ((Route*) 0);
2399 }
2400
2401 shared_ptr<Route>
2402 Session::route_by_remote_id (uint32_t id)
2403 {
2404         shared_ptr<RouteList> r = routes.reader ();
2405
2406         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2407                 if ((*i)->remote_control_id() == id) {
2408                         return *i;
2409                 }
2410         }
2411
2412         return shared_ptr<Route> ((Route*) 0);
2413 }
2414
2415 void
2416 Session::find_current_end ()
2417 {
2418         if (_state_of_the_state & Loading) {
2419                 return;
2420         }
2421
2422         nframes_t max = get_maximum_extent ();
2423
2424         if (max > end_location->end()) {
2425                 end_location->set_end (max);
2426                 set_dirty();
2427                 DurationChanged(); /* EMIT SIGNAL */
2428         }
2429 }
2430
2431 nframes_t
2432 Session::get_maximum_extent () const
2433 {
2434         nframes_t max = 0;
2435         nframes_t me; 
2436
2437         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2438
2439         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2440                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2441                 if ((me = pl->get_maximum_extent()) > max) {
2442                         max = me;
2443                 }
2444         }
2445
2446         return max;
2447 }
2448
2449 boost::shared_ptr<Diskstream>
2450 Session::diskstream_by_name (string name)
2451 {
2452         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2453
2454         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2455                 if ((*i)->name() == name) {
2456                         return *i;
2457                 }
2458         }
2459
2460         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2461 }
2462
2463 boost::shared_ptr<Diskstream>
2464 Session::diskstream_by_id (const PBD::ID& id)
2465 {
2466         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2467
2468         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2469                 if ((*i)->id() == id) {
2470                         return *i;
2471                 }
2472         }
2473
2474         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2475 }
2476
2477 /* Region management */
2478
2479 string
2480 Session::new_region_name (string old)
2481 {
2482         string::size_type last_period;
2483         uint32_t number;
2484         string::size_type len = old.length() + 64;
2485         char buf[len];
2486
2487         if ((last_period = old.find_last_of ('.')) == string::npos) {
2488                 
2489                 /* no period present - add one explicitly */
2490
2491                 old += '.';
2492                 last_period = old.length() - 1;
2493                 number = 0;
2494
2495         } else {
2496
2497                 number = atoi (old.substr (last_period+1).c_str());
2498
2499         }
2500
2501         while (number < (UINT_MAX-1)) {
2502
2503                 RegionList::const_iterator i;
2504                 string sbuf;
2505
2506                 number++;
2507
2508                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2509                 sbuf = buf;
2510
2511                 for (i = regions.begin(); i != regions.end(); ++i) {
2512                         if (i->second->name() == sbuf) {
2513                                 break;
2514                         }
2515                 }
2516                 
2517                 if (i == regions.end()) {
2518                         break;
2519                 }
2520         }
2521
2522         if (number != (UINT_MAX-1)) {
2523                 return buf;
2524         } 
2525
2526         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2527         return old;
2528 }
2529
2530 int
2531 Session::region_name (string& result, string base, bool newlevel) const
2532 {
2533         char buf[16];
2534         string subbase;
2535
2536         assert(base.find("/") == string::npos);
2537
2538         if (base == "") {
2539                 
2540                 Glib::Mutex::Lock lm (region_lock);
2541
2542                 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2543
2544                 
2545                 result = "region.";
2546                 result += buf;
2547
2548         } else {
2549
2550                 /* XXX this is going to be slow. optimize me later */
2551                 
2552                 if (newlevel) {
2553                         subbase = base;
2554                 } else {
2555                         string::size_type pos;
2556
2557                         pos = base.find_last_of ('.');
2558
2559                         /* pos may be npos, but then we just use entire base */
2560
2561                         subbase = base.substr (0, pos);
2562
2563                 }
2564
2565                 bool name_taken = true;
2566                 
2567                 {
2568                         Glib::Mutex::Lock lm (region_lock);
2569                         
2570                         for (int n = 1; n < 5000; ++n) {
2571                                 
2572                                 result = subbase;
2573                                 snprintf (buf, sizeof (buf), ".%d", n);
2574                                 result += buf;
2575                                 
2576                                 name_taken = false;
2577                                 
2578                                 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2579                                         if (i->second->name() == result) {
2580                                                 name_taken = true;
2581                                                 break;
2582                                         }
2583                                 }
2584                                 
2585                                 if (!name_taken) {
2586                                         break;
2587                                 }
2588                         }
2589                 }
2590                         
2591                 if (name_taken) {
2592                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2593                         /*NOTREACHED*/
2594                 }
2595         }
2596         return 0;
2597 }       
2598
2599 void
2600 Session::add_region (boost::shared_ptr<Region> region)
2601 {
2602         boost::shared_ptr<Region> other;
2603         bool added = false;
2604
2605         { 
2606                 Glib::Mutex::Lock lm (region_lock);
2607
2608                 RegionList::iterator x;
2609
2610                 for (x = regions.begin(); x != regions.end(); ++x) {
2611
2612                         other = x->second;
2613
2614                         if (region->region_list_equivalent (other)) {
2615                                 break;
2616                         }
2617                 }
2618
2619                 if (x == regions.end()) {
2620
2621                         pair<RegionList::key_type,RegionList::mapped_type> entry;
2622
2623                         entry.first = region->id();
2624                         entry.second = region;
2625
2626                         pair<RegionList::iterator,bool> x = regions.insert (entry);
2627
2628
2629                         if (!x.second) {
2630                                 return;
2631                         }
2632
2633                         added = true;
2634                 } 
2635
2636         }
2637
2638         /* mark dirty because something has changed even if we didn't
2639            add the region to the region list.
2640         */
2641         
2642         set_dirty();
2643         
2644         if (added) {
2645                 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2646                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2647                 RegionAdded (region); /* EMIT SIGNAL */
2648         }
2649 }
2650
2651 void
2652 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2653 {
2654         boost::shared_ptr<Region> region (weak_region.lock ());
2655
2656         if (!region) {
2657                 return;
2658         }
2659
2660         if (what_changed & Region::HiddenChanged) {
2661                 /* relay hidden changes */
2662                 RegionHiddenChange (region);
2663         }
2664 }
2665
2666 void
2667 Session::remove_region (boost::weak_ptr<Region> weak_region)
2668 {
2669         RegionList::iterator i;
2670         boost::shared_ptr<Region> region (weak_region.lock ());
2671
2672         if (!region) {
2673                 return;
2674         }
2675
2676         bool removed = false;
2677
2678         { 
2679                 Glib::Mutex::Lock lm (region_lock);
2680
2681                 if ((i = regions.find (region->id())) != regions.end()) {
2682                         regions.erase (i);
2683                         removed = true;
2684                 }
2685         }
2686
2687         /* mark dirty because something has changed even if we didn't
2688            remove the region from the region list.
2689         */
2690
2691         set_dirty();
2692
2693         if (removed) {
2694                  RegionRemoved(region); /* EMIT SIGNAL */
2695         }
2696 }
2697
2698 boost::shared_ptr<Region>
2699 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2700 {
2701         RegionList::iterator i;
2702         boost::shared_ptr<Region> region;
2703         
2704         Glib::Mutex::Lock lm (region_lock);
2705
2706         for (i = regions.begin(); i != regions.end(); ++i) {
2707
2708                 region = i->second;
2709
2710                 if (region->whole_file()) {
2711
2712                         if (child->source_equivalent (region)) {
2713                                 return region;
2714                         }
2715                 }
2716         } 
2717
2718         return boost::shared_ptr<Region> ();
2719 }       
2720
2721 void
2722 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2723 {
2724         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2725                 (*i)->get_region_list_equivalent_regions (region, result);
2726 }
2727
2728 int
2729 Session::destroy_region (boost::shared_ptr<Region> region)
2730 {
2731         vector<boost::shared_ptr<Source> > srcs;
2732                 
2733         {
2734                 boost::shared_ptr<AudioRegion> aregion;
2735                 
2736                 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2737                         return 0;
2738                 }
2739                 
2740                 if (aregion->playlist()) {
2741                         aregion->playlist()->destroy_region (region);
2742                 }
2743                 
2744                 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2745                         srcs.push_back (aregion->source (n));
2746                 }
2747         }
2748
2749         region->drop_references ();
2750
2751         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2752
2753                 if (!(*i)->used()) {
2754                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2755                         
2756                         if (afs) {
2757                                 (afs)->mark_for_remove ();
2758                         }
2759                         
2760                         (*i)->drop_references ();
2761                         
2762                         cerr << "source was not used by any playlist\n";
2763                 }
2764         }
2765
2766         return 0;
2767 }
2768
2769 int
2770 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2771 {
2772         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2773                 destroy_region (*i);
2774         }
2775         return 0;
2776 }
2777
2778 int
2779 Session::remove_last_capture ()
2780 {
2781         list<boost::shared_ptr<Region> > r;
2782         
2783         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2784         
2785         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2786                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2787                 
2788                 if (!l.empty()) {
2789                         r.insert (r.end(), l.begin(), l.end());
2790                         l.clear ();
2791                 }
2792         }
2793
2794         destroy_regions (r);
2795
2796         save_state (_current_snapshot_name);
2797
2798         return 0;
2799 }
2800
2801 int
2802 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2803 {
2804         remove_region (r);
2805         return 0;
2806 }
2807
2808 /* Source Management */
2809 void
2810 Session::add_source (boost::shared_ptr<Source> source)
2811 {
2812         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2813         pair<SourceMap::iterator,bool> result;
2814
2815         entry.first = source->id();
2816         entry.second = source;
2817         
2818         {
2819                 Glib::Mutex::Lock lm (source_lock);
2820                 result = sources.insert (entry);
2821         }
2822
2823         if (result.second) {
2824                 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2825                 set_dirty();
2826         }
2827 }
2828
2829 void
2830 Session::remove_source (boost::weak_ptr<Source> src)
2831 {
2832         SourceMap::iterator i;
2833         boost::shared_ptr<Source> source = src.lock();
2834
2835         if (!source) {
2836                 return;
2837         } 
2838
2839         { 
2840                 Glib::Mutex::Lock lm (source_lock);
2841                 
2842                 { 
2843                         Glib::Mutex::Lock lm (source_lock);
2844                         
2845                         if ((i = sources.find (source->id())) != sources.end()) {
2846                                 sources.erase (i);
2847                         } 
2848                 }
2849         }
2850         
2851         if (!_state_of_the_state & InCleanup) {
2852                 
2853                 /* save state so we don't end up with a session file
2854                    referring to non-existent sources.
2855                 */
2856                 
2857                 save_state (_current_snapshot_name);
2858         }
2859 }
2860
2861 boost::shared_ptr<Source>
2862 Session::source_by_id (const PBD::ID& id)
2863 {
2864         Glib::Mutex::Lock lm (source_lock);
2865         SourceMap::iterator i;
2866         boost::shared_ptr<Source> source;
2867
2868         if ((i = sources.find (id)) != sources.end()) {
2869                 source = i->second;
2870         }
2871
2872         /* XXX search MIDI or other searches here */
2873         
2874         return source;
2875 }
2876
2877
2878 boost::shared_ptr<Source>
2879 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2880 {
2881         Glib::Mutex::Lock lm (source_lock);
2882
2883         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2884                 cerr << "comparing " << path << " with " << i->second->name() << endl;
2885                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2886
2887                 if (afs && afs->path() == path && chn == afs->channel()) {
2888                         return afs;
2889                 } 
2890                        
2891         }
2892         return boost::shared_ptr<Source>();
2893 }
2894
2895 string
2896 Session::peak_path_from_audio_path (string audio_path) const
2897 {
2898         string res;
2899
2900         res = peak_dir ();
2901         res += PBD::basename_nosuffix (audio_path);
2902         res += ".peak";
2903
2904         return res;
2905 }
2906
2907 string
2908 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2909 {
2910         string look_for;
2911         string old_basename = PBD::basename_nosuffix (oldname);
2912         string new_legalized = legalize_for_path (newname);
2913
2914         /* note: we know (or assume) the old path is already valid */
2915
2916         if (destructive) {
2917                 
2918                 /* destructive file sources have a name of the form:
2919
2920                     /path/to/Tnnnn-NAME(%[LR])?.wav
2921                   
2922                     the task here is to replace NAME with the new name.
2923                 */
2924                 
2925                 /* find last slash */
2926
2927                 string dir;
2928                 string prefix;
2929                 string::size_type slash;
2930                 string::size_type dash;
2931
2932                 if ((slash = path.find_last_of ('/')) == string::npos) {
2933                         return "";
2934                 }
2935
2936                 dir = path.substr (0, slash+1);
2937
2938                 /* '-' is not a legal character for the NAME part of the path */
2939
2940                 if ((dash = path.find_last_of ('-')) == string::npos) {
2941                         return "";
2942                 }
2943
2944                 prefix = path.substr (slash+1, dash-(slash+1));
2945
2946                 path = dir;
2947                 path += prefix;
2948                 path += '-';
2949                 path += new_legalized;
2950                 path += ".wav";  /* XXX gag me with a spoon */
2951                 
2952         } else {
2953                 
2954                 /* non-destructive file sources have a name of the form:
2955
2956                     /path/to/NAME-nnnnn(%[LR])?.wav
2957                   
2958                     the task here is to replace NAME with the new name.
2959                 */
2960                 
2961                 string dir;
2962                 string suffix;
2963                 string::size_type slash;
2964                 string::size_type dash;
2965                 string::size_type postfix;
2966
2967                 /* find last slash */
2968
2969                 if ((slash = path.find_last_of ('/')) == string::npos) {
2970                         return "";
2971                 }
2972
2973                 dir = path.substr (0, slash+1);
2974
2975                 /* '-' is not a legal character for the NAME part of the path */
2976
2977                 if ((dash = path.find_last_of ('-')) == string::npos) {
2978                         return "";
2979                 }
2980
2981                 suffix = path.substr (dash+1);
2982                 
2983                 // Suffix is now everything after the dash. Now we need to eliminate
2984                 // the nnnnn part, which is done by either finding a '%' or a '.'
2985
2986                 postfix = suffix.find_last_of ("%");
2987                 if (postfix == string::npos) {
2988                         postfix = suffix.find_last_of ('.');
2989                 }
2990
2991                 if (postfix != string::npos) {
2992                         suffix = suffix.substr (postfix);
2993                 } else {
2994                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2995                         return "";
2996                 }
2997
2998                 const uint32_t limit = 10000;
2999                 char buf[PATH_MAX+1];
3000
3001                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3002
3003                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3004
3005                         if (access (buf, F_OK) != 0) {
3006                                 path = buf;
3007                                 break;
3008                         }
3009                         path = "";
3010                 }
3011
3012                 if (path == "") {
3013                         error << "FATAL ERROR! Could not find a " << endl;
3014                 }
3015
3016         }
3017
3018         return path;
3019 }
3020
3021 string
3022 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
3023 {
3024         string spath;
3025         uint32_t cnt;
3026         char buf[PATH_MAX+1];
3027         const uint32_t limit = 10000;
3028         string legalized;
3029
3030         buf[0] = '\0';
3031         legalized = legalize_for_path (name);
3032
3033         /* find a "version" of the file name that doesn't exist in
3034            any of the possible directories.
3035         */
3036
3037         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3038
3039                 vector<space_and_path>::iterator i;
3040                 uint32_t existing = 0;
3041
3042                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3043
3044                         spath = (*i).path;
3045
3046                         spath += sound_dir (false);
3047
3048                         if (destructive) {
3049                                 if (nchan < 2) {
3050                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3051                                 } else if (nchan == 2) {
3052                                         if (chan == 0) {
3053                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3054                                         } else {
3055                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3056                                         }
3057                                 } else if (nchan < 26) {
3058                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3059                                 } else {
3060                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3061                                 }
3062
3063                         } else {
3064
3065                                 spath += '/';
3066                                 spath += legalized;
3067
3068                                 if (nchan < 2) {
3069                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3070                                 } else if (nchan == 2) {
3071                                         if (chan == 0) {
3072                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3073                                         } else {
3074                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3075                                         }
3076                                 } else if (nchan < 26) {
3077                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3078                                 } else {
3079                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3080                                 }
3081                         }
3082
3083                         if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
3084                                 existing++;
3085                         } 
3086
3087                 }
3088
3089                 if (existing == 0) {
3090                         break;
3091                 }
3092
3093                 if (cnt > limit) {
3094                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3095                         destroy ();
3096                         throw failed_constructor();
3097                 }
3098         }
3099
3100         /* we now have a unique name for the file, but figure out where to
3101            actually put it.
3102         */
3103
3104         string foo = buf;
3105
3106         spath = discover_best_sound_dir ();
3107         spath += '/';
3108
3109         string::size_type pos = foo.find_last_of ('/');
3110         
3111         if (pos == string::npos) {
3112                 spath += foo;
3113         } else {
3114                 spath += foo.substr (pos + 1);
3115         }
3116
3117         return spath;
3118 }
3119
3120 boost::shared_ptr<AudioFileSource>
3121 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3122 {
3123         string spath = audio_path_from_name (ds.name(), ds.n_channels().get(DataType::AUDIO), chan, destructive);
3124         return boost::dynamic_pointer_cast<AudioFileSource> (
3125                 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3126 }
3127
3128 // FIXME: _terrible_ code duplication
3129 string
3130 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3131 {
3132         string look_for;
3133         string old_basename = PBD::basename_nosuffix (oldname);
3134         string new_legalized = legalize_for_path (newname);
3135
3136         /* note: we know (or assume) the old path is already valid */
3137
3138         if (destructive) {
3139                 
3140                 /* destructive file sources have a name of the form:
3141
3142                     /path/to/Tnnnn-NAME(%[LR])?.wav
3143                   
3144                     the task here is to replace NAME with the new name.
3145                 */
3146                 
3147                 /* find last slash */
3148
3149                 string dir;
3150                 string prefix;
3151                 string::size_type slash;
3152                 string::size_type dash;
3153
3154                 if ((slash = path.find_last_of ('/')) == string::npos) {
3155                         return "";
3156                 }
3157
3158                 dir = path.substr (0, slash+1);
3159
3160                 /* '-' is not a legal character for the NAME part of the path */
3161
3162                 if ((dash = path.find_last_of ('-')) == string::npos) {
3163                         return "";
3164                 }
3165
3166                 prefix = path.substr (slash+1, dash-(slash+1));
3167
3168                 path = dir;
3169                 path += prefix;
3170                 path += '-';
3171                 path += new_legalized;
3172                 path += ".mid";  /* XXX gag me with a spoon */
3173                 
3174         } else {
3175                 
3176                 /* non-destructive file sources have a name of the form:
3177
3178                     /path/to/NAME-nnnnn(%[LR])?.wav
3179                   
3180                     the task here is to replace NAME with the new name.
3181                 */
3182                 
3183                 string dir;
3184                 string suffix;
3185                 string::size_type slash;
3186                 string::size_type dash;
3187                 string::size_type postfix;
3188
3189                 /* find last slash */
3190
3191                 if ((slash = path.find_last_of ('/')) == string::npos) {
3192                         return "";
3193                 }
3194
3195                 dir = path.substr (0, slash+1);
3196
3197                 /* '-' is not a legal character for the NAME part of the path */
3198
3199                 if ((dash = path.find_last_of ('-')) == string::npos) {
3200                         return "";
3201                 }
3202
3203                 suffix = path.substr (dash+1);
3204                 
3205                 // Suffix is now everything after the dash. Now we need to eliminate
3206                 // the nnnnn part, which is done by either finding a '%' or a '.'
3207
3208                 postfix = suffix.find_last_of ("%");
3209                 if (postfix == string::npos) {
3210                         postfix = suffix.find_last_of ('.');
3211                 }
3212
3213                 if (postfix != string::npos) {
3214                         suffix = suffix.substr (postfix);
3215                 } else {
3216                         error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3217                         return "";
3218                 }
3219
3220                 const uint32_t limit = 10000;
3221                 char buf[PATH_MAX+1];
3222
3223                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3224
3225                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3226
3227                         if (access (buf, F_OK) != 0) {
3228                                 path = buf;
3229                                 break;
3230                         }
3231                         path = "";
3232                 }
3233
3234                 if (path == "") {
3235                         error << "FATAL ERROR! Could not find a " << endl;
3236                 }
3237
3238         }
3239
3240         return path;
3241 }
3242
3243 string
3244 Session::midi_path_from_name (string name)
3245 {
3246         string spath;
3247         uint32_t cnt;
3248         char buf[PATH_MAX+1];
3249         const uint32_t limit = 10000;
3250         string legalized;
3251
3252         buf[0] = '\0';
3253         legalized = legalize_for_path (name);
3254
3255         /* find a "version" of the file name that doesn't exist in
3256            any of the possible directories.
3257         */
3258
3259         for (cnt = 1; cnt <= limit; ++cnt) {
3260
3261                 vector<space_and_path>::iterator i;
3262                 uint32_t existing = 0;
3263
3264                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3265
3266                         spath = (*i).path;
3267
3268                         // FIXME: different directory from audio?
3269                         spath += sound_dir(false) + "/" + legalized;
3270
3271                         snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3272
3273                         if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
3274                                 existing++;
3275                         } 
3276                 }
3277
3278                 if (existing == 0) {
3279                         break;
3280                 }
3281
3282                 if (cnt > limit) {
3283                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3284                         throw failed_constructor();
3285                 }
3286         }
3287
3288         /* we now have a unique name for the file, but figure out where to
3289            actually put it.
3290         */
3291
3292         string foo = buf;
3293
3294         // FIXME: different directory than audio?
3295         spath = discover_best_sound_dir ();
3296         spath += '/';
3297
3298         string::size_type pos = foo.find_last_of ('/');
3299         
3300         if (pos == string::npos) {
3301                 spath += foo;
3302         } else {
3303                 spath += foo.substr (pos + 1);
3304         }
3305
3306         return spath;
3307 }
3308
3309 boost::shared_ptr<MidiSource>
3310 Session::create_midi_source_for_session (MidiDiskstream& ds)
3311 {
3312         string spath = midi_path_from_name (ds.name());
3313         
3314         return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, spath, false, frame_rate()));
3315 }
3316
3317
3318 /* Playlist management */
3319
3320 boost::shared_ptr<Playlist>
3321 Session::playlist_by_name (string name)
3322 {
3323         Glib::Mutex::Lock lm (playlist_lock);
3324         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3325                 if ((*i)->name() == name) {
3326                         return* i;
3327                 }
3328         }
3329         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3330                 if ((*i)->name() == name) {
3331                         return* i;
3332                 }
3333         }
3334
3335         return boost::shared_ptr<Playlist>();
3336 }
3337
3338 void
3339 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3340 {
3341         if (playlist->hidden()) {
3342                 return;
3343         }
3344
3345         { 
3346                 Glib::Mutex::Lock lm (playlist_lock);
3347                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3348                         playlists.insert (playlists.begin(), playlist);
3349                         playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3350                         playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3351                 }
3352         }
3353
3354         set_dirty();
3355
3356         PlaylistAdded (playlist); /* EMIT SIGNAL */
3357 }
3358
3359 void
3360 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3361 {
3362         { 
3363                 Glib::Mutex::Lock lm (playlist_lock);
3364                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3365                         s.push_back (*i);
3366                 }
3367                 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3368                         s.push_back (*i);
3369                 }
3370         }
3371 }
3372
3373 void
3374 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3375 {
3376         boost::shared_ptr<Playlist> pl(wpl.lock());
3377
3378         if (!pl) {
3379                 return;
3380         }
3381
3382         PlaylistList::iterator x;
3383
3384         if (pl->hidden()) {
3385                 /* its not supposed to be visible */
3386                 return;
3387         }
3388
3389         { 
3390                 Glib::Mutex::Lock lm (playlist_lock);
3391
3392                 if (!inuse) {
3393
3394                         unused_playlists.insert (pl);
3395                         
3396                         if ((x = playlists.find (pl)) != playlists.end()) {
3397                                 playlists.erase (x);
3398                         }
3399
3400                         
3401                 } else {
3402
3403                         playlists.insert (pl);
3404                         
3405                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3406                                 unused_playlists.erase (x);
3407                         }
3408                 }
3409         }
3410 }
3411
3412 void
3413 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3414 {
3415         if (_state_of_the_state & Deletion) {
3416                 return;
3417         }
3418
3419         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3420
3421         if (!playlist) {
3422                 return;
3423         }
3424
3425         { 
3426                 Glib::Mutex::Lock lm (playlist_lock);
3427
3428                 PlaylistList::iterator i;
3429
3430                 i = find (playlists.begin(), playlists.end(), playlist);
3431                 if (i != playlists.end()) {
3432                         playlists.erase (i);
3433                 }
3434
3435                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3436                 if (i != unused_playlists.end()) {
3437                         unused_playlists.erase (i);
3438                 }
3439                 
3440         }
3441
3442         set_dirty();
3443
3444         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3445 }
3446
3447 void 
3448 Session::set_audition (boost::shared_ptr<Region> r)
3449 {
3450         pending_audition_region = r;
3451         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3452         schedule_butler_transport_work ();
3453 }
3454
3455 void
3456 Session::audition_playlist ()
3457 {
3458         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3459         ev->region.reset ();
3460         queue_event (ev);
3461 }
3462
3463 void
3464 Session::non_realtime_set_audition ()
3465 {
3466         if (!pending_audition_region) {
3467                 auditioner->audition_current_playlist ();
3468         } else {
3469                 auditioner->audition_region (pending_audition_region);
3470                 pending_audition_region.reset ();
3471         }
3472         AuditionActive (true); /* EMIT SIGNAL */
3473 }
3474
3475 void
3476 Session::audition_region (boost::shared_ptr<Region> r)
3477 {
3478         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3479         ev->region = r;
3480         queue_event (ev);
3481 }
3482
3483 void
3484 Session::cancel_audition ()
3485 {
3486         if (auditioner->active()) {
3487                 auditioner->cancel_audition ();
3488                 AuditionActive (false); /* EMIT SIGNAL */
3489         }
3490 }
3491
3492 bool
3493 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3494 {
3495         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3496 }
3497
3498 void
3499 Session::remove_empty_sounds ()
3500 {
3501         PathScanner scanner;
3502
3503         vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64)$", false, true);
3504         
3505         Glib::Mutex::Lock lm (source_lock);
3506         
3507         regex_t compiled_tape_track_pattern;
3508         int err;
3509
3510         if ((err = regcomp (&compiled_tape_track_pattern, "/T[0-9][0-9][0-9][0-9]-", REG_EXTENDED|REG_NOSUB))) {
3511
3512                 char msg[256];
3513                 
3514                 regerror (err, &compiled_tape_track_pattern, msg, sizeof (msg));
3515                 
3516                 error << string_compose (_("Cannot compile tape track regexp for use (%1)"), msg) << endmsg;
3517                 return;
3518         }
3519
3520         for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
3521                 
3522                 /* never remove files that appear to be a tape track */
3523
3524                 if (regexec (&compiled_tape_track_pattern, (*i)->c_str(), 0, 0, 0) == 0) {
3525                         delete *i;
3526                         continue;
3527                 }
3528                         
3529                 if (AudioFileSource::is_empty (*this, *(*i))) {
3530
3531                         unlink ((*i)->c_str());
3532                         
3533                         string peak_path = peak_path_from_audio_path (**i);
3534                         unlink (peak_path.c_str());
3535                 }
3536
3537                 delete* i;
3538         }
3539
3540         delete possible_audiofiles;
3541 }
3542
3543 bool
3544 Session::is_auditioning () const
3545 {
3546         /* can be called before we have an auditioner object */
3547         if (auditioner) {
3548                 return auditioner->active();
3549         } else {
3550                 return false;
3551         }
3552 }
3553
3554 void
3555 Session::set_all_solo (bool yn)
3556 {
3557         shared_ptr<RouteList> r = routes.reader ();
3558         
3559         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3560                 if (!(*i)->hidden()) {
3561                         (*i)->set_solo (yn, this);
3562                 }
3563         }
3564
3565         set_dirty();
3566 }
3567                 
3568 void
3569 Session::set_all_mute (bool yn)
3570 {
3571         shared_ptr<RouteList> r = routes.reader ();
3572         
3573         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3574                 if (!(*i)->hidden()) {
3575                         (*i)->set_mute (yn, this);
3576                 }
3577         }
3578
3579         set_dirty();
3580 }
3581                 
3582 uint32_t
3583 Session::n_diskstreams () const
3584 {
3585         uint32_t n = 0;
3586
3587         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3588
3589         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3590                 if (!(*i)->hidden()) {
3591                         n++;
3592                 }
3593         }
3594         return n;
3595 }
3596
3597 void
3598 Session::graph_reordered ()
3599 {
3600         /* don't do this stuff if we are setting up connections
3601            from a set_state() call or creating new tracks.
3602         */
3603
3604         if (_state_of_the_state & InitialConnecting) {
3605                 return;
3606         }
3607         
3608         /* every track/bus asked for this to be handled but it was deferred because
3609            we were connecting. do it now.
3610         */
3611
3612         request_input_change_handling ();
3613
3614         resort_routes ();
3615
3616         /* force all diskstreams to update their capture offset values to 
3617            reflect any changes in latencies within the graph.
3618         */
3619         
3620         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3621
3622         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3623                 (*i)->set_capture_offset ();
3624         }
3625 }
3626
3627 void
3628 Session::record_disenable_all ()
3629 {
3630         record_enable_change_all (false);
3631 }
3632
3633 void
3634 Session::record_enable_all ()
3635 {
3636         record_enable_change_all (true);
3637 }
3638
3639 void
3640 Session::record_enable_change_all (bool yn)
3641 {
3642         shared_ptr<RouteList> r = routes.reader ();
3643         
3644         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3645                 Track* at;
3646
3647                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3648                         at->set_record_enable (yn, this);
3649                 }
3650         }
3651         
3652         /* since we don't keep rec-enable state, don't mark session dirty */
3653 }
3654
3655 void
3656 Session::add_redirect (Redirect* redirect)
3657 {
3658         Send* send;
3659         Insert* insert;
3660         PortInsert* port_insert;
3661         PluginInsert* plugin_insert;
3662
3663         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3664                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3665                         _port_inserts.insert (_port_inserts.begin(), port_insert);
3666                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3667                         _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3668                 } else {
3669                         fatal << _("programming error: unknown type of Insert created!") << endmsg;
3670                         /*NOTREACHED*/
3671                 }
3672         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3673                 _sends.insert (_sends.begin(), send);
3674         } else {
3675                 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
3676                 /*NOTREACHED*/
3677         }
3678
3679         redirect->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_redirect), redirect));
3680
3681         set_dirty();
3682 }
3683
3684 void
3685 Session::remove_redirect (Redirect* redirect)
3686 {
3687         Send* send;
3688         Insert* insert;
3689         PortInsert* port_insert;
3690         PluginInsert* plugin_insert;
3691         
3692         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3693                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3694                         list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3695                         if (x != _port_inserts.end()) {
3696                                 insert_bitset[port_insert->bit_slot()] = false;
3697                                 _port_inserts.erase (x);
3698                         }
3699                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3700                         _plugin_inserts.remove (plugin_insert);
3701                 } else {
3702                         fatal << string_compose (_("programming error: %1"),
3703                                                  X_("unknown type of Insert deleted!")) 
3704                               << endmsg;
3705                         /*NOTREACHED*/
3706                 }
3707         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3708                 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3709                 if (x != _sends.end()) {
3710                         send_bitset[send->bit_slot()] = false;
3711                         _sends.erase (x);
3712                 }
3713         } else {
3714                 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
3715                 /*NOTREACHED*/
3716         }
3717
3718         set_dirty();
3719 }
3720
3721 nframes_t
3722 Session::available_capture_duration ()
3723 {
3724         float sample_bytes_on_disk = 4.0; // keep gcc happy
3725
3726         switch (Config->get_native_file_data_format()) {
3727         case FormatFloat:
3728                 sample_bytes_on_disk = 4.0;
3729                 break;
3730
3731         case FormatInt24:
3732                 sample_bytes_on_disk = 3.0;
3733                 break;
3734
3735         default: 
3736                 /* impossible, but keep some gcc versions happy */
3737                 fatal << string_compose (_("programming error: %1"),
3738                                          X_("illegal native file data format"))
3739                       << endmsg;
3740                 /*NOTREACHED*/
3741         }
3742
3743         double scale = 4096.0 / sample_bytes_on_disk;
3744
3745         if (_total_free_4k_blocks * scale > (double) max_frames) {
3746                 return max_frames;
3747         }
3748         
3749         return (nframes_t) floor (_total_free_4k_blocks * scale);
3750 }
3751
3752 void
3753 Session::add_connection (ARDOUR::Connection* connection)
3754 {
3755         {
3756                 Glib::Mutex::Lock guard (connection_lock);
3757                 _connections.push_back (connection);
3758         }
3759         
3760         ConnectionAdded (connection); /* EMIT SIGNAL */
3761
3762         set_dirty();
3763 }
3764
3765 void
3766 Session::remove_connection (ARDOUR::Connection* connection)
3767 {
3768         bool removed = false;
3769
3770         {
3771                 Glib::Mutex::Lock guard (connection_lock);
3772                 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3773                 
3774                 if (i != _connections.end()) {
3775                         _connections.erase (i);
3776                         removed = true;
3777                 }
3778         }
3779
3780         if (removed) {
3781                  ConnectionRemoved (connection); /* EMIT SIGNAL */
3782         }
3783
3784         set_dirty();
3785 }
3786
3787 ARDOUR::Connection *
3788 Session::connection_by_name (string name) const
3789 {
3790         Glib::Mutex::Lock lm (connection_lock);
3791
3792         for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3793                 if ((*i)->name() == name) {
3794                         return* i;
3795                 }
3796         }
3797
3798         return 0;
3799 }
3800
3801 void
3802 Session::tempo_map_changed (Change ignored)
3803 {
3804         clear_clicks ();
3805         set_dirty ();
3806 }
3807
3808 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3809  * the given count with the current block size.
3810  */
3811 void
3812 Session::ensure_buffers (ChanCount howmany)
3813 {
3814         // FIXME: NASTY assumption (midi block size == audio block size)
3815         _scratch_buffers->ensure_buffers(howmany, current_block_size);
3816         _send_buffers->ensure_buffers(howmany, current_block_size);
3817         _silent_buffers->ensure_buffers(howmany, current_block_size);
3818         
3819         allocate_pan_automation_buffers (current_block_size, howmany.get(DataType::AUDIO), false);
3820 }
3821
3822 uint32_t
3823 Session::next_insert_id ()
3824 {
3825         /* this doesn't really loop forever. just think about it */
3826
3827         while (true) {
3828                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3829                         if (!insert_bitset[n]) {
3830                                 insert_bitset[n] = true;
3831                                 return n;
3832                                 
3833                         }
3834                 }
3835                 
3836                 /* none available, so resize and try again */
3837
3838                 insert_bitset.resize (insert_bitset.size() + 16, false);
3839         }
3840 }
3841
3842 uint32_t
3843 Session::next_send_id ()
3844 {
3845         /* this doesn't really loop forever. just think about it */
3846
3847         while (true) {
3848                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3849                         if (!send_bitset[n]) {
3850                                 send_bitset[n] = true;
3851                                 return n;
3852                                 
3853                         }
3854                 }
3855                 
3856                 /* none available, so resize and try again */
3857
3858                 send_bitset.resize (send_bitset.size() + 16, false);
3859         }
3860 }
3861
3862 void
3863 Session::mark_send_id (uint32_t id)
3864 {
3865         if (id >= send_bitset.size()) {
3866                 send_bitset.resize (id+16, false);
3867         }
3868         if (send_bitset[id]) {
3869                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3870         }
3871         send_bitset[id] = true;
3872 }
3873
3874 void
3875 Session::mark_insert_id (uint32_t id)
3876 {
3877         if (id >= insert_bitset.size()) {
3878                 insert_bitset.resize (id+16, false);
3879         }
3880         if (insert_bitset[id]) {
3881                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3882         }
3883         insert_bitset[id] = true;
3884 }
3885
3886 /* Named Selection management */
3887
3888 NamedSelection *
3889 Session::named_selection_by_name (string name)
3890 {
3891         Glib::Mutex::Lock lm (named_selection_lock);
3892         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3893                 if ((*i)->name == name) {
3894                         return* i;
3895                 }
3896         }
3897         return 0;
3898 }
3899
3900 void
3901 Session::add_named_selection (NamedSelection* named_selection)
3902 {
3903         { 
3904                 Glib::Mutex::Lock lm (named_selection_lock);
3905                 named_selections.insert (named_selections.begin(), named_selection);
3906         }
3907
3908         for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3909                 add_playlist (*i);
3910         }
3911
3912         set_dirty();
3913
3914         NamedSelectionAdded (); /* EMIT SIGNAL */
3915 }
3916
3917 void
3918 Session::remove_named_selection (NamedSelection* named_selection)
3919 {
3920         bool removed = false;
3921
3922         { 
3923                 Glib::Mutex::Lock lm (named_selection_lock);
3924
3925                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3926
3927                 if (i != named_selections.end()) {
3928                         delete (*i);
3929                         named_selections.erase (i);
3930                         set_dirty();
3931                         removed = true;
3932                 }
3933         }
3934
3935         if (removed) {
3936                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3937         }
3938 }
3939
3940 void
3941 Session::reset_native_file_format ()
3942 {
3943         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3944
3945         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3946                 (*i)->reset_write_sources (false);
3947         }
3948 }
3949
3950 bool
3951 Session::route_name_unique (string n) const
3952 {
3953         shared_ptr<RouteList> r = routes.reader ();
3954         
3955         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3956                 if ((*i)->name() == n) {
3957                         return false;
3958                 }
3959         }
3960         
3961         return true;
3962 }
3963
3964 uint32_t
3965 Session::n_playlists () const
3966 {
3967         Glib::Mutex::Lock lm (playlist_lock);
3968         return playlists.size();
3969 }
3970
3971 void
3972 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3973 {
3974         if (!force && howmany <= _npan_buffers) {
3975                 return;
3976         }
3977
3978         if (_pan_automation_buffer) {
3979
3980                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3981                         delete [] _pan_automation_buffer[i];
3982                 }
3983
3984                 delete [] _pan_automation_buffer;
3985         }
3986
3987         _pan_automation_buffer = new pan_t*[howmany];
3988         
3989         for (uint32_t i = 0; i < howmany; ++i) {
3990                 _pan_automation_buffer[i] = new pan_t[nframes];
3991         }
3992
3993         _npan_buffers = howmany;
3994 }
3995
3996 int
3997 Session::freeze (InterThreadInfo& itt)
3998 {
3999         shared_ptr<RouteList> r = routes.reader ();
4000
4001         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4002
4003                 Track *at;
4004
4005                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
4006                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
4007                            of every track.
4008                         */
4009                         at->freeze (itt);
4010                 }
4011         }
4012
4013         return 0;
4014 }
4015
4016 int
4017 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,      
4018                                bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
4019 {
4020         int ret = -1;
4021         boost::shared_ptr<Playlist> playlist;
4022         boost::shared_ptr<AudioFileSource> fsource;
4023         uint32_t x;
4024         char buf[PATH_MAX+1];
4025         string dir;
4026         ChanCount nchans(track.audio_diskstream()->n_channels());
4027         nframes_t position;
4028         nframes_t this_chunk;
4029         nframes_t to_do;
4030         BufferSet buffers;
4031
4032         // any bigger than this seems to cause stack overflows in called functions
4033         const nframes_t chunk_size = (128 * 1024)/4;
4034
4035         g_atomic_int_set (&processing_prohibited, 1);
4036         
4037         /* call tree *MUST* hold route_lock */
4038         
4039         if ((playlist = track.diskstream()->playlist()) == 0) {
4040                 goto out;
4041         }
4042
4043         /* external redirects will be a problem */
4044
4045         if (track.has_external_redirects()) {
4046                 goto out;
4047         }
4048         
4049         dir = discover_best_sound_dir ();
4050
4051         for (uint32_t chan_n=0; chan_n < nchans.get(DataType::AUDIO); ++chan_n) {
4052
4053                 for (x = 0; x < 99999; ++x) {
4054                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4055                         if (access (buf, F_OK) != 0) {
4056                                 break;
4057                         }
4058                 }
4059                 
4060                 if (x == 99999) {
4061                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4062                         goto out;
4063                 }
4064                 
4065                 try {
4066                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4067                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4068                 }
4069                 
4070                 catch (failed_constructor& err) {
4071                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4072                         goto out;
4073                 }
4074
4075                 srcs.push_back (fsource);
4076         }
4077
4078         /* XXX need to flush all redirects */
4079         
4080         position = start;
4081         to_do = len;
4082
4083         /* create a set of reasonably-sized buffers */
4084         buffers.ensure_buffers(nchans, chunk_size);
4085         buffers.set_count(nchans);
4086
4087         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4088                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4089                 if (afs)
4090                         afs->prepare_for_peakfile_writes ();
4091         }
4092                         
4093         while (to_do && !itt.cancel) {
4094                 
4095                 this_chunk = min (to_do, chunk_size);
4096                 
4097                 if (track.export_stuff (buffers, start, this_chunk)) {
4098                         goto out;
4099                 }
4100
4101                 uint32_t n = 0;
4102                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4103                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4104                         
4105                         if (afs) {
4106                                 if (afs->write (buffers.get_audio(n).data(this_chunk), this_chunk) != this_chunk) {
4107                                         goto out;
4108                                 }
4109                         }
4110                 }
4111                 
4112                 start += this_chunk;
4113                 to_do -= this_chunk;
4114                 
4115                 itt.progress = (float) (1.0 - ((double) to_do / len));
4116
4117         }
4118
4119         if (!itt.cancel) {
4120                 
4121                 time_t now;
4122                 struct tm* xnow;
4123                 time (&now);
4124                 xnow = localtime (&now);
4125                 
4126                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4127                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4128                         
4129                         if (afs) {
4130                                 afs->update_header (position, *xnow, now);
4131                                 afs->flush_header ();
4132                         }
4133                 }
4134                 
4135                 /* construct a region to represent the bounced material */
4136
4137                 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
4138                                                                            region_name_from_path (srcs.front()->name(), true));
4139
4140                 ret = 0;
4141         }
4142                 
4143   out:
4144         if (ret) {
4145                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4146                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4147
4148                         if (afs) {
4149                                 afs->mark_for_remove ();
4150                         }
4151
4152                         (*src)->drop_references ();
4153                 }
4154
4155         } else {
4156                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4157                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4158                         
4159                         if (afs)
4160                                 afs->done_with_peakfile_writes ();
4161                 }
4162         }
4163
4164         g_atomic_int_set (&processing_prohibited, 0);
4165
4166         itt.done = true;
4167
4168         return ret;
4169 }
4170
4171 BufferSet&
4172 Session::get_silent_buffers (ChanCount count)
4173 {
4174         assert(_silent_buffers->available() >= count);
4175         _silent_buffers->set_count(count);
4176
4177         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4178                 for (size_t i=0; i < count.get(*t); ++i) {
4179                         _silent_buffers->get(*t, i).clear();
4180                 }
4181         }
4182         
4183         return *_silent_buffers;
4184 }
4185
4186 BufferSet&
4187 Session::get_scratch_buffers (ChanCount count)
4188 {
4189         assert(_scratch_buffers->available() >= count);
4190         _scratch_buffers->set_count(count);
4191         return *_scratch_buffers;
4192 }
4193
4194 BufferSet&
4195 Session::get_send_buffers (ChanCount count)
4196 {
4197         assert(_send_buffers->available() >= count);
4198         _send_buffers->set_count(count);
4199         return *_send_buffers;
4200 }
4201
4202 uint32_t 
4203 Session::ntracks () const
4204 {
4205         uint32_t n = 0;
4206         shared_ptr<RouteList> r = routes.reader ();
4207
4208         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4209                 if (dynamic_cast<Track*> ((*i).get())) {
4210                         ++n;
4211                 }
4212         }
4213
4214         return n;
4215 }
4216
4217 uint32_t 
4218 Session::nbusses () const
4219 {
4220         uint32_t n = 0;
4221         shared_ptr<RouteList> r = routes.reader ();
4222
4223         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4224                 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4225                         ++n;
4226                 }
4227         }
4228
4229         return n;
4230 }
4231
4232 void
4233 Session::add_automation_list(AutomationList *al)
4234 {
4235         automation_lists[al->id()] = al;
4236 }
4237
4238 nframes_t
4239 Session::compute_initial_length ()
4240 {
4241         return _engine.frame_rate() * 60 * 5;
4242 }
4243