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