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