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