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