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