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