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