Use sys::path and ARDOUR::user_config_directory in ARDOUR::read/write_recent_sessions
[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 () && !play_loop) || 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         /* XXX really atomic compare+swap here */
1159         if (g_atomic_int_get (&_record_status) == Recording) {
1160                 g_atomic_int_set (&_record_status, Enabled);
1161
1162                 if (Config->get_monitoring_model() == HardwareMonitoring) {
1163                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1164                         
1165                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1166                                 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1167                                         //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1168                                         (*i)->monitor_input (false);   
1169                                 }
1170                         }
1171                 }
1172         }
1173 }
1174
1175 void
1176 Session::maybe_enable_record ()
1177 {
1178         g_atomic_int_set (&_record_status, Enabled);
1179
1180         /* this function is currently called from somewhere other than an RT thread.
1181            this save_state() call therefore doesn't impact anything.
1182         */
1183
1184         save_state ("", true);
1185
1186         if (_transport_speed) {
1187                 if (!Config->get_punch_in()) {
1188                         enable_record ();
1189                 } 
1190         } else {
1191                 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1192                 RecordStateChanged (); /* EMIT SIGNAL */
1193         }
1194
1195         set_dirty();
1196 }
1197
1198 nframes_t
1199 Session::audible_frame () const
1200 {
1201         nframes_t ret;
1202         nframes_t offset;
1203         nframes_t tf;
1204
1205         /* the first of these two possible settings for "offset"
1206            mean that the audible frame is stationary until 
1207            audio emerges from the latency compensation
1208            "pseudo-pipeline".
1209
1210            the second means that the audible frame is stationary
1211            until audio would emerge from a physical port
1212            in the absence of any plugin latency compensation
1213         */
1214
1215         offset = _worst_output_latency;
1216
1217         if (offset > current_block_size) {
1218                 offset -= current_block_size;
1219         } else { 
1220                 /* XXX is this correct? if we have no external
1221                    physical connections and everything is internal
1222                    then surely this is zero? still, how
1223                    likely is that anyway?
1224                 */
1225                 offset = current_block_size;
1226         }
1227
1228         if (synced_to_jack()) {
1229                 tf = _engine.transport_frame();
1230         } else {
1231                 tf = _transport_frame;
1232         }
1233
1234         if (_transport_speed == 0) {
1235                 return tf;
1236         }
1237
1238         if (tf < offset) {
1239                 return 0;
1240         }
1241
1242         ret = tf;
1243
1244         if (!non_realtime_work_pending()) {
1245
1246                 /* MOVING */
1247
1248                 /* take latency into account */
1249                 
1250                 ret -= offset;
1251         }
1252
1253         return ret;
1254 }
1255
1256 void
1257 Session::set_frame_rate (nframes_t frames_per_second)
1258 {
1259         /** \fn void Session::set_frame_size(nframes_t)
1260                 the AudioEngine object that calls this guarantees 
1261                 that it will not be called while we are also in
1262                 ::process(). Its fine to do things that block
1263                 here.
1264         */
1265
1266         _base_frame_rate = frames_per_second;
1267
1268         sync_time_vars();
1269
1270         Route::set_automation_interval ((nframes_t) ceil ((double) frames_per_second * 0.25));
1271
1272         // XXX we need some equivalent to this, somehow
1273         // SndFileSource::setup_standard_crossfades (frames_per_second);
1274
1275         set_dirty();
1276
1277         /* XXX need to reset/reinstantiate all LADSPA plugins */
1278 }
1279
1280 void
1281 Session::set_block_size (nframes_t nframes)
1282 {
1283         /* the AudioEngine guarantees 
1284            that it will not be called while we are also in
1285            ::process(). It is therefore fine to do things that block
1286            here.
1287         */
1288
1289         { 
1290                         
1291                 current_block_size = nframes;
1292
1293                 ensure_buffers(_scratch_buffers->available());
1294
1295                 if (_gain_automation_buffer) {
1296                         delete [] _gain_automation_buffer;
1297                 }
1298                 _gain_automation_buffer = new gain_t[nframes];
1299
1300                 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1301
1302                 boost::shared_ptr<RouteList> r = routes.reader ();
1303
1304                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1305                         (*i)->set_block_size (nframes);
1306                 }
1307                 
1308                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1309                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1310                         (*i)->set_block_size (nframes);
1311                 }
1312
1313                 set_worst_io_latencies ();
1314         }
1315 }
1316
1317 void
1318 Session::set_default_fade (float steepness, float fade_msecs)
1319 {
1320 #if 0
1321         nframes_t fade_frames;
1322         
1323         /* Don't allow fade of less 1 frame */
1324         
1325         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1326
1327                 fade_msecs = 0;
1328                 fade_frames = 0;
1329
1330         } else {
1331                 
1332                 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1333                 
1334         }
1335
1336         default_fade_msecs = fade_msecs;
1337         default_fade_steepness = steepness;
1338
1339         {
1340                 // jlc, WTF is this!
1341                 Glib::RWLock::ReaderLock lm (route_lock);
1342                 AudioRegion::set_default_fade (steepness, fade_frames);
1343         }
1344
1345         set_dirty();
1346
1347         /* XXX have to do this at some point */
1348         /* foreach region using default fade, reset, then 
1349            refill_all_diskstream_buffers ();
1350         */
1351 #endif
1352 }
1353
1354 struct RouteSorter {
1355     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1356             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1357                     return false;
1358             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1359                     return true;
1360             } else {
1361                     if (r1->fed_by.empty()) {
1362                             if (r2->fed_by.empty()) {
1363                                     /* no ardour-based connections inbound to either route. just use signal order */
1364                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1365                             } else {
1366                                     /* r2 has connections, r1 does not; run r1 early */
1367                                     return true;
1368                             }
1369                     } else {
1370                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1371                     }
1372             }
1373     }
1374 };
1375
1376 static void
1377 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1378 {
1379         shared_ptr<Route> r2;
1380
1381         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1382                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1383                 return;
1384         } 
1385
1386         /* make a copy of the existing list of routes that feed r1 */
1387
1388         set<shared_ptr<Route> > existing = r1->fed_by;
1389
1390         /* for each route that feeds r1, recurse, marking it as feeding
1391            rbase as well.
1392         */
1393
1394         for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1395                 r2 =* i;
1396
1397                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1398                    base as being fed by r2
1399                 */
1400
1401                 rbase->fed_by.insert (r2);
1402
1403                 if (r2 != rbase) {
1404
1405                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1406                            stop here.
1407                          */
1408
1409                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1410                                 continue;
1411                         }
1412
1413                         /* now recurse, so that we can mark base as being fed by
1414                            all routes that feed r2
1415                         */
1416
1417                         trace_terminal (r2, rbase);
1418                 }
1419
1420         }
1421 }
1422
1423 void
1424 Session::resort_routes ()
1425 {
1426         /* don't do anything here with signals emitted
1427            by Routes while we are being destroyed.
1428         */
1429
1430         if (_state_of_the_state & Deletion) {
1431                 return;
1432         }
1433
1434
1435         {
1436
1437                 RCUWriter<RouteList> writer (routes);
1438                 shared_ptr<RouteList> r = writer.get_copy ();
1439                 resort_routes_using (r);
1440                 /* writer goes out of scope and forces update */
1441         }
1442
1443 }
1444 void
1445 Session::resort_routes_using (shared_ptr<RouteList> r)
1446 {
1447         RouteList::iterator i, j;
1448         
1449         for (i = r->begin(); i != r->end(); ++i) {
1450                 
1451                 (*i)->fed_by.clear ();
1452                 
1453                 for (j = r->begin(); j != r->end(); ++j) {
1454                         
1455                         /* although routes can feed themselves, it will
1456                            cause an endless recursive descent if we
1457                            detect it. so don't bother checking for
1458                            self-feeding.
1459                         */
1460                         
1461                         if (*j == *i) {
1462                                 continue;
1463                         }
1464                         
1465                         if ((*j)->feeds (*i)) {
1466                                 (*i)->fed_by.insert (*j);
1467                         } 
1468                 }
1469         }
1470         
1471         for (i = r->begin(); i != r->end(); ++i) {
1472                 trace_terminal (*i, *i);
1473         }
1474         
1475         RouteSorter cmp;
1476         r->sort (cmp);
1477         
1478 #if 0
1479         cerr << "finished route resort\n";
1480         
1481         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1482                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1483         }
1484         cerr << endl;
1485 #endif
1486         
1487 }
1488
1489 list<boost::shared_ptr<MidiTrack> >
1490 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1491 {
1492         char track_name[32];
1493         uint32_t track_id = 0;
1494         uint32_t n = 0;
1495         uint32_t channels_used = 0;
1496         string port;
1497         RouteList new_routes;
1498         list<boost::shared_ptr<MidiTrack> > ret;
1499
1500         /* count existing midi tracks */
1501
1502         {
1503                 shared_ptr<RouteList> r = routes.reader ();
1504
1505                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1506                         if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1507                                 if (!(*i)->hidden()) {
1508                                         n++;
1509                                         channels_used += (*i)->n_inputs().n_midi();
1510                                 }
1511                         }
1512                 }
1513         }
1514
1515         while (how_many) {
1516
1517                 /* check for duplicate route names, since we might have pre-existing
1518                    routes with this name (e.g. create Midi1, Midi2, delete Midi1,
1519                    save, close,restart,add new route - first named route is now
1520                    Midi2)
1521                 */
1522                 
1523
1524                 do {
1525                         ++track_id;
1526
1527                         snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1528
1529                         if (route_by_name (track_name) == 0) {
1530                                 break;
1531                         }
1532                         
1533                 } while (track_id < (UINT_MAX-1));
1534
1535                 try {
1536                         shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1537                         
1538                         if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::MIDI, 1), false, this)) {
1539                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1540                         }
1541                         
1542                         channels_used += track->n_inputs ().n_midi();
1543
1544                         track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1545                         track->set_remote_control_id (ntracks());
1546
1547                         new_routes.push_back (track);
1548                         ret.push_back (track);
1549                 }
1550
1551                 catch (failed_constructor &err) {
1552                         error << _("Session: could not create new midi track.") << endmsg;
1553                         // XXX should we delete the tracks already created? 
1554                         ret.clear ();
1555                         return ret;
1556                 }
1557                 
1558                 --how_many;
1559         }
1560
1561         if (!new_routes.empty()) {
1562                 add_routes (new_routes, false);
1563                 save_state (_current_snapshot_name);
1564         }
1565
1566         return ret;
1567 }
1568
1569 list<boost::shared_ptr<AudioTrack> >
1570 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1571 {
1572         char track_name[32];
1573         uint32_t track_id = 0;
1574         uint32_t n = 0;
1575         uint32_t channels_used = 0;
1576         string port;
1577         RouteList new_routes;
1578         list<boost::shared_ptr<AudioTrack> > ret;
1579         uint32_t control_id;
1580
1581         /* count existing audio tracks */
1582
1583         {
1584                 shared_ptr<RouteList> r = routes.reader ();
1585
1586                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1587                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1588                                 if (!(*i)->hidden()) {
1589                                         n++;
1590                                         channels_used += (*i)->n_inputs().n_audio();
1591                                 }
1592                         }
1593                 }
1594         }
1595
1596         vector<string> physinputs;
1597         vector<string> physoutputs;
1598         uint32_t nphysical_in;
1599         uint32_t nphysical_out;
1600
1601         _engine.get_physical_outputs (physoutputs);
1602         _engine.get_physical_inputs (physinputs);
1603         control_id = ntracks() + nbusses() + 1;
1604
1605         while (how_many) {
1606
1607                 /* check for duplicate route names, since we might have pre-existing
1608                    routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1609                    save, close,restart,add new route - first named route is now
1610                    Audio2)
1611                 */
1612                 
1613
1614                 do {
1615                         ++track_id;
1616
1617                         snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1618
1619                         if (route_by_name (track_name) == 0) {
1620                                 break;
1621                         }
1622                         
1623                 } while (track_id < (UINT_MAX-1));
1624
1625                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1626                         nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1627                 } else {
1628                         nphysical_in = 0;
1629                 }
1630                 
1631                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1632                         nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1633                 } else {
1634                         nphysical_out = 0;
1635                 }
1636
1637                 shared_ptr<AudioTrack> track;
1638                 
1639                 try {
1640                         track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1641                         
1642                         if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1643                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1644                                                          input_channels, output_channels)
1645                                       << endmsg;
1646                                 goto failed;
1647                         }
1648
1649                         if (nphysical_in) {
1650                                 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1651                                         
1652                                         port = "";
1653                                         
1654                                         if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1655                                                 port = physinputs[(channels_used+x)%nphysical_in];
1656                                         } 
1657                                         
1658                                         if (port.length() && track->connect_input (track->input (x), port, this)) {
1659                                                 break;
1660                                         }
1661                                 }
1662                         }
1663                         
1664                         for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1665                                 
1666                                 port = "";
1667                                 
1668                                 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1669                                         port = physoutputs[(channels_used+x)%nphysical_out];
1670                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1671                                         if (_master_out) {
1672                                                 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1673                                         }
1674                                 }
1675                                 
1676                                 if (port.length() && track->connect_output (track->output (x), port, this)) {
1677                                         break;
1678                                 }
1679                         }
1680                         
1681                         channels_used += track->n_inputs ().n_audio();
1682
1683                         track->audio_diskstream()->non_realtime_input_change();
1684                         
1685                         track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1686                         track->set_remote_control_id (control_id);
1687                         ++control_id;
1688
1689                         new_routes.push_back (track);
1690                         ret.push_back (track);
1691                 }
1692
1693                 catch (failed_constructor &err) {
1694                         error << _("Session: could not create new audio track.") << endmsg;
1695
1696                         if (track) {
1697                                 /* we need to get rid of this, since the track failed to be created */
1698                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1699
1700                                 { 
1701                                         RCUWriter<DiskstreamList> writer (diskstreams);
1702                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1703                                         ds->remove (track->audio_diskstream());
1704                                 }
1705                         }
1706
1707                         goto failed;
1708                 }
1709
1710                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1711
1712                         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;
1713
1714                         if (track) {
1715                                 /* we need to get rid of this, since the track failed to be created */
1716                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1717
1718                                 { 
1719                                         RCUWriter<DiskstreamList> writer (diskstreams);
1720                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1721                                         ds->remove (track->audio_diskstream());
1722                                 }
1723                         }
1724
1725                         goto failed;
1726                 }
1727
1728                 --how_many;
1729         }
1730
1731   failed:
1732         if (!new_routes.empty()) {
1733                 add_routes (new_routes, false);
1734                 save_state (_current_snapshot_name);
1735         }
1736
1737         return ret;
1738 }
1739
1740 void
1741 Session::set_remote_control_ids ()
1742 {
1743         RemoteModel m = Config->get_remote_model();
1744
1745         shared_ptr<RouteList> r = routes.reader ();
1746
1747         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1748                 if ( MixerOrdered == m) {                       
1749                         long order = (*i)->order_key(N_("signal"));
1750                         (*i)->set_remote_control_id( order+1 );
1751                 } else if ( EditorOrdered == m) {
1752                         long order = (*i)->order_key(N_("editor"));
1753                         (*i)->set_remote_control_id( order+1 );
1754                 } else if ( UserOrdered == m) {
1755                         //do nothing ... only changes to remote id's are initiated by user 
1756                 }
1757         }
1758 }
1759
1760
1761 Session::RouteList
1762 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1763 {
1764         char bus_name[32];
1765         uint32_t bus_id = 1;
1766         uint32_t n = 0;
1767         string port;
1768         RouteList ret;
1769         uint32_t control_id;
1770
1771         /* count existing audio busses */
1772
1773         {
1774                 shared_ptr<RouteList> r = routes.reader ();
1775
1776                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1777                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1778                                 if (!(*i)->hidden() && (*i)->name() != _("master")) {
1779                                         bus_id++;
1780                                 }
1781                         }
1782                 }
1783         }
1784
1785         vector<string> physinputs;
1786         vector<string> physoutputs;
1787
1788         _engine.get_physical_outputs (physoutputs);
1789         _engine.get_physical_inputs (physinputs);
1790         control_id = ntracks() + nbusses() + 1;
1791
1792         while (how_many) {
1793
1794                 do {
1795                         snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1796
1797                         bus_id++;
1798
1799                         if (route_by_name (bus_name) == 0) {
1800                                 break;
1801                         }
1802
1803                 } while (bus_id < (UINT_MAX-1));
1804
1805                 try {
1806                         shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1807                         
1808                         if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1809                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1810                                                          input_channels, output_channels)
1811                                       << endmsg;
1812                                 goto failure;
1813                         }
1814                         
1815                         for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1816                                 
1817                                 port = "";
1818
1819                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1820                                                 port = physinputs[((n+x)%n_physical_inputs)];
1821                                 } 
1822                                 
1823                                 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1824                                         break;
1825                                 }
1826                         }
1827                         
1828                         for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1829                                 
1830                                 port = "";
1831                                 
1832                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1833                                         port = physoutputs[((n+x)%n_physical_outputs)];
1834                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1835                                         if (_master_out) {
1836                                                 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1837                                         }
1838                                 }
1839                                 
1840                                 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1841                                         break;
1842                                 }
1843                         }
1844                         
1845                         bus->set_remote_control_id (control_id);
1846                         ++control_id;
1847
1848                         ret.push_back (bus);
1849                 }
1850         
1851
1852                 catch (failed_constructor &err) {
1853                         error << _("Session: could not create new audio route.") << endmsg;
1854                         goto failure;
1855                 }
1856
1857                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1858                         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;
1859                         goto failure;
1860                 }
1861
1862
1863                 --how_many;
1864         }
1865
1866   failure:
1867         if (!ret.empty()) {
1868                 add_routes (ret, false);
1869                 save_state (_current_snapshot_name);
1870         }
1871
1872         return ret;
1873
1874 }
1875
1876 void
1877 Session::add_routes (RouteList& new_routes, bool save)
1878 {
1879         { 
1880                 RCUWriter<RouteList> writer (routes);
1881                 shared_ptr<RouteList> r = writer.get_copy ();
1882                 r->insert (r->end(), new_routes.begin(), new_routes.end());
1883                 resort_routes_using (r);
1884         }
1885
1886         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1887                 
1888                 boost::weak_ptr<Route> wpr (*x);
1889
1890                 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1891                 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1892                 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1893                 (*x)->inserts_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1894                 
1895                 if ((*x)->master()) {
1896                         _master_out = (*x);
1897                 }
1898                 
1899                 if ((*x)->control()) {
1900                         _control_out = (*x);
1901                 } 
1902         }
1903
1904         if (_control_out && IO::connecting_legal) {
1905
1906                 vector<string> cports;
1907                 uint32_t ni = _control_out->n_inputs().n_audio();
1908
1909                 for (uint32_t n = 0; n < ni; ++n) {
1910                         cports.push_back (_control_out->input(n)->name());
1911                 }
1912
1913                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1914                         (*x)->set_control_outs (cports);
1915                 }
1916         } 
1917
1918         set_dirty();
1919
1920         if (save) {
1921                 save_state (_current_snapshot_name);
1922         }
1923
1924         RouteAdded (new_routes); /* EMIT SIGNAL */
1925 }
1926
1927 void
1928 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
1929 {
1930         /* need to do this in case we're rolling at the time, to prevent false underruns */
1931         dstream->do_refill_with_alloc ();
1932         
1933         dstream->set_block_size (current_block_size);
1934
1935         {
1936                 RCUWriter<DiskstreamList> writer (diskstreams);
1937                 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1938                 ds->push_back (dstream);
1939                 /* writer goes out of scope, copies ds back to main */
1940         } 
1941
1942         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1943         /* this will connect to future changes, and check the current length */
1944         diskstream_playlist_changed (dstream);
1945
1946         dstream->prepare ();
1947
1948 }
1949
1950 void
1951 Session::remove_route (shared_ptr<Route> route)
1952 {
1953         {       
1954                 RCUWriter<RouteList> writer (routes);
1955                 shared_ptr<RouteList> rs = writer.get_copy ();
1956                 
1957                 rs->remove (route);
1958
1959                 /* deleting the master out seems like a dumb
1960                    idea, but its more of a UI policy issue
1961                    than our concern.
1962                 */
1963
1964                 if (route == _master_out) {
1965                         _master_out = shared_ptr<Route> ();
1966                 }
1967
1968                 if (route == _control_out) {
1969                         _control_out = shared_ptr<Route> ();
1970
1971                         /* cancel control outs for all routes */
1972
1973                         vector<string> empty;
1974
1975                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
1976                                 (*r)->set_control_outs (empty);
1977                         }
1978                 }
1979
1980                 update_route_solo_state ();
1981                 
1982                 /* writer goes out of scope, forces route list update */
1983         }
1984
1985         Track* t;
1986         boost::shared_ptr<Diskstream> ds;
1987         
1988         if ((t = dynamic_cast<Track*>(route.get())) != 0) {
1989                 ds = t->diskstream();
1990         }
1991         
1992         if (ds) {
1993
1994                 {
1995                         RCUWriter<DiskstreamList> dsl (diskstreams);
1996                         boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
1997                         d->remove (ds);
1998                 }
1999         }
2000
2001         find_current_end ();
2002         
2003         update_latency_compensation (false, false);
2004         set_dirty();
2005
2006         // We need to disconnect the routes inputs and outputs 
2007         route->disconnect_inputs(NULL);
2008         route->disconnect_outputs(NULL);
2009         
2010         /* get rid of it from the dead wood collection in the route list manager */
2011
2012         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2013
2014         routes.flush ();
2015
2016         /* try to cause everyone to drop their references */
2017
2018         route->drop_references ();
2019
2020         /* save the new state of the world */
2021
2022         if (save_state (_current_snapshot_name)) {
2023                 save_history (_current_snapshot_name);
2024         }
2025 }       
2026
2027 void
2028 Session::route_mute_changed (void* src)
2029 {
2030         set_dirty ();
2031 }
2032
2033 void
2034 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2035 {      
2036         if (solo_update_disabled) {
2037                 // We know already
2038                 return;
2039         }
2040         
2041         bool is_track;
2042         boost::shared_ptr<Route> route = wpr.lock ();
2043
2044         if (!route) {
2045                 /* should not happen */
2046                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2047                 return;
2048         }
2049
2050         is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2051         
2052         shared_ptr<RouteList> r = routes.reader ();
2053
2054         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2055                 
2056                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2057                 
2058                 if (is_track) {
2059                         
2060                         /* don't mess with busses */
2061                         
2062                         if (dynamic_cast<Track*>((*i).get()) == 0) {
2063                                 continue;
2064                         }
2065                         
2066                 } else {
2067                         
2068                         /* don't mess with tracks */
2069                         
2070                         if (dynamic_cast<Track*>((*i).get()) != 0) {
2071                                 continue;
2072                         }
2073                 }
2074                 
2075                 if ((*i) != route &&
2076                     ((*i)->mix_group () == 0 ||
2077                      (*i)->mix_group () != route->mix_group () ||
2078                      !route->mix_group ()->is_active())) {
2079                         
2080                         if ((*i)->soloed()) {
2081                                 
2082                                 /* if its already soloed, and solo latching is enabled,
2083                                    then leave it as it is.
2084                                 */
2085                                 
2086                                 if (Config->get_solo_latched()) {
2087                                         continue;
2088                                 } 
2089                         }
2090                         
2091                         /* do it */
2092
2093                         solo_update_disabled = true;
2094                         (*i)->set_solo (false, src);
2095                         solo_update_disabled = false;
2096                 }
2097         }
2098         
2099         bool something_soloed = false;
2100         bool same_thing_soloed = false;
2101         bool signal = false;
2102
2103         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2104                 if ((*i)->soloed()) {
2105                         something_soloed = true;
2106                         if (dynamic_cast<Track*>((*i).get())) {
2107                                 if (is_track) {
2108                                         same_thing_soloed = true;
2109                                         break;
2110                                 }
2111                         } else {
2112                                 if (!is_track) {
2113                                         same_thing_soloed = true;
2114                                         break;
2115                                 }
2116                         }
2117                         break;
2118                 }
2119         }
2120         
2121         if (something_soloed != currently_soloing) {
2122                 signal = true;
2123                 currently_soloing = something_soloed;
2124         }
2125         
2126         modify_solo_mute (is_track, same_thing_soloed);
2127
2128         if (signal) {
2129                 SoloActive (currently_soloing); /* EMIT SIGNAL */
2130         }
2131
2132         SoloChanged (); /* EMIT SIGNAL */
2133
2134         set_dirty();
2135 }
2136
2137 void
2138 Session::update_route_solo_state ()
2139 {
2140         bool mute = false;
2141         bool is_track = false;
2142         bool signal = false;
2143
2144         /* caller must hold RouteLock */
2145
2146         /* this is where we actually implement solo by changing
2147            the solo mute setting of each track.
2148         */
2149         
2150         shared_ptr<RouteList> r = routes.reader ();
2151
2152         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2153                 if ((*i)->soloed()) {
2154                         mute = true;
2155                         if (dynamic_cast<Track*>((*i).get())) {
2156                                 is_track = true;
2157                         }
2158                         break;
2159                 }
2160         }
2161
2162         if (mute != currently_soloing) {
2163                 signal = true;
2164                 currently_soloing = mute;
2165         }
2166
2167         if (!is_track && !mute) {
2168
2169                 /* nothing is soloed */
2170
2171                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2172                         (*i)->set_solo_mute (false);
2173                 }
2174                 
2175                 if (signal) {
2176                         SoloActive (false);
2177                 }
2178
2179                 return;
2180         }
2181
2182         modify_solo_mute (is_track, mute);
2183
2184         if (signal) {
2185                 SoloActive (currently_soloing);
2186         }
2187 }
2188
2189 void
2190 Session::modify_solo_mute (bool is_track, bool mute)
2191 {
2192         shared_ptr<RouteList> r = routes.reader ();
2193
2194         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2195                 
2196                 if (is_track) {
2197                         
2198                         /* only alter track solo mute */
2199                         
2200                         if (dynamic_cast<Track*>((*i).get())) {
2201                                 if ((*i)->soloed()) {
2202                                         (*i)->set_solo_mute (!mute);
2203                                 } else {
2204                                         (*i)->set_solo_mute (mute);
2205                                 }
2206                         }
2207
2208                 } else {
2209
2210                         /* only alter bus solo mute */
2211
2212                         if (!dynamic_cast<Track*>((*i).get())) {
2213
2214                                 if ((*i)->soloed()) {
2215
2216                                         (*i)->set_solo_mute (false);
2217
2218                                 } else {
2219
2220                                         /* don't mute master or control outs
2221                                            in response to another bus solo
2222                                         */
2223                                         
2224                                         if ((*i) != _master_out &&
2225                                             (*i) != _control_out) {
2226                                                 (*i)->set_solo_mute (mute);
2227                                         }
2228                                 }
2229                         }
2230
2231                 }
2232         }
2233 }       
2234
2235
2236 void
2237 Session::catch_up_on_solo ()
2238 {
2239         /* this is called after set_state() to catch the full solo
2240            state, which can't be correctly determined on a per-route
2241            basis, but needs the global overview that only the session
2242            has.
2243         */
2244         update_route_solo_state();
2245 }       
2246                 
2247 shared_ptr<Route>
2248 Session::route_by_name (string name)
2249 {
2250         shared_ptr<RouteList> r = routes.reader ();
2251
2252         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2253                 if ((*i)->name() == name) {
2254                         return *i;
2255                 }
2256         }
2257
2258         return shared_ptr<Route> ((Route*) 0);
2259 }
2260
2261 shared_ptr<Route>
2262 Session::route_by_id (PBD::ID id)
2263 {
2264         shared_ptr<RouteList> r = routes.reader ();
2265
2266         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2267                 if ((*i)->id() == id) {
2268                         return *i;
2269                 }
2270         }
2271
2272         return shared_ptr<Route> ((Route*) 0);
2273 }
2274
2275 shared_ptr<Route>
2276 Session::route_by_remote_id (uint32_t id)
2277 {
2278         shared_ptr<RouteList> r = routes.reader ();
2279
2280         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2281                 if ((*i)->remote_control_id() == id) {
2282                         return *i;
2283                 }
2284         }
2285
2286         return shared_ptr<Route> ((Route*) 0);
2287 }
2288
2289 void
2290 Session::find_current_end ()
2291 {
2292         if (_state_of_the_state & Loading) {
2293                 return;
2294         }
2295
2296         nframes_t max = get_maximum_extent ();
2297
2298         if (max > end_location->end()) {
2299                 end_location->set_end (max);
2300                 set_dirty();
2301                 DurationChanged(); /* EMIT SIGNAL */
2302         }
2303 }
2304
2305 nframes_t
2306 Session::get_maximum_extent () const
2307 {
2308         nframes_t max = 0;
2309         nframes_t me; 
2310
2311         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2312
2313         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2314                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2315                 if ((me = pl->get_maximum_extent()) > max) {
2316                         max = me;
2317                 }
2318         }
2319
2320         return max;
2321 }
2322
2323 boost::shared_ptr<Diskstream>
2324 Session::diskstream_by_name (string name)
2325 {
2326         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2327
2328         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2329                 if ((*i)->name() == name) {
2330                         return *i;
2331                 }
2332         }
2333
2334         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2335 }
2336
2337 boost::shared_ptr<Diskstream>
2338 Session::diskstream_by_id (const PBD::ID& id)
2339 {
2340         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2341
2342         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2343                 if ((*i)->id() == id) {
2344                         return *i;
2345                 }
2346         }
2347
2348         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2349 }
2350
2351 /* Region management */
2352
2353 string
2354 Session::new_region_name (string old)
2355 {
2356         string::size_type last_period;
2357         uint32_t number;
2358         string::size_type len = old.length() + 64;
2359         char buf[len];
2360
2361         if ((last_period = old.find_last_of ('.')) == string::npos) {
2362                 
2363                 /* no period present - add one explicitly */
2364
2365                 old += '.';
2366                 last_period = old.length() - 1;
2367                 number = 0;
2368
2369         } else {
2370
2371                 number = atoi (old.substr (last_period+1).c_str());
2372
2373         }
2374
2375         while (number < (UINT_MAX-1)) {
2376
2377                 RegionList::const_iterator i;
2378                 string sbuf;
2379
2380                 number++;
2381
2382                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2383                 sbuf = buf;
2384
2385                 for (i = regions.begin(); i != regions.end(); ++i) {
2386                         if (i->second->name() == sbuf) {
2387                                 break;
2388                         }
2389                 }
2390                 
2391                 if (i == regions.end()) {
2392                         break;
2393                 }
2394         }
2395
2396         if (number != (UINT_MAX-1)) {
2397                 return buf;
2398         } 
2399
2400         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2401         return old;
2402 }
2403
2404 int
2405 Session::region_name (string& result, string base, bool newlevel) const
2406 {
2407         char buf[16];
2408         string subbase;
2409
2410         assert(base.find("/") == string::npos);
2411
2412         if (base == "") {
2413                 
2414                 Glib::Mutex::Lock lm (region_lock);
2415
2416                 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2417
2418                 
2419                 result = "region.";
2420                 result += buf;
2421
2422         } else {
2423
2424                 /* XXX this is going to be slow. optimize me later */
2425                 
2426                 if (newlevel) {
2427                         subbase = base;
2428                 } else {
2429                         string::size_type pos;
2430
2431                         pos = base.find_last_of ('.');
2432
2433                         /* pos may be npos, but then we just use entire base */
2434
2435                         subbase = base.substr (0, pos);
2436
2437                 }
2438
2439                 bool name_taken = true;
2440                 
2441                 {
2442                         Glib::Mutex::Lock lm (region_lock);
2443                         
2444                         for (int n = 1; n < 5000; ++n) {
2445                                 
2446                                 result = subbase;
2447                                 snprintf (buf, sizeof (buf), ".%d", n);
2448                                 result += buf;
2449                                 
2450                                 name_taken = false;
2451                                 
2452                                 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2453                                         if (i->second->name() == result) {
2454                                                 name_taken = true;
2455                                                 break;
2456                                         }
2457                                 }
2458                                 
2459                                 if (!name_taken) {
2460                                         break;
2461                                 }
2462                         }
2463                 }
2464                         
2465                 if (name_taken) {
2466                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2467                         /*NOTREACHED*/
2468                 }
2469         }
2470         return 0;
2471 }       
2472
2473 void
2474 Session::add_region (boost::shared_ptr<Region> region)
2475 {
2476         boost::shared_ptr<Region> other;
2477         bool added = false;
2478
2479         { 
2480                 Glib::Mutex::Lock lm (region_lock);
2481
2482                 RegionList::iterator x;
2483
2484                 for (x = regions.begin(); x != regions.end(); ++x) {
2485
2486                         other = x->second;
2487
2488                         if (region->region_list_equivalent (other)) {
2489                                 break;
2490                         }
2491                 }
2492
2493                 if (x == regions.end()) {
2494
2495                         pair<RegionList::key_type,RegionList::mapped_type> entry;
2496
2497                         entry.first = region->id();
2498                         entry.second = region;
2499
2500                         pair<RegionList::iterator,bool> x = regions.insert (entry);
2501
2502
2503                         if (!x.second) {
2504                                 return;
2505                         }
2506
2507                         added = true;
2508                 } 
2509
2510         }
2511
2512         /* mark dirty because something has changed even if we didn't
2513            add the region to the region list.
2514         */
2515         
2516         set_dirty();
2517         
2518         if (added) {
2519                 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2520                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2521                 RegionAdded (region); /* EMIT SIGNAL */
2522         }
2523 }
2524
2525 void
2526 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2527 {
2528         boost::shared_ptr<Region> region (weak_region.lock ());
2529
2530         if (!region) {
2531                 return;
2532         }
2533
2534         if (what_changed & Region::HiddenChanged) {
2535                 /* relay hidden changes */
2536                 RegionHiddenChange (region);
2537         }
2538 }
2539
2540 void
2541 Session::remove_region (boost::weak_ptr<Region> weak_region)
2542 {
2543         RegionList::iterator i;
2544         boost::shared_ptr<Region> region (weak_region.lock ());
2545
2546         if (!region) {
2547                 return;
2548         }
2549
2550         bool removed = false;
2551
2552         { 
2553                 Glib::Mutex::Lock lm (region_lock);
2554
2555                 if ((i = regions.find (region->id())) != regions.end()) {
2556                         regions.erase (i);
2557                         removed = true;
2558                 }
2559         }
2560
2561         /* mark dirty because something has changed even if we didn't
2562            remove the region from the region list.
2563         */
2564
2565         set_dirty();
2566
2567         if (removed) {
2568                  RegionRemoved(region); /* EMIT SIGNAL */
2569         }
2570 }
2571
2572 boost::shared_ptr<Region>
2573 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2574 {
2575         RegionList::iterator i;
2576         boost::shared_ptr<Region> region;
2577         
2578         Glib::Mutex::Lock lm (region_lock);
2579
2580         for (i = regions.begin(); i != regions.end(); ++i) {
2581
2582                 region = i->second;
2583
2584                 if (region->whole_file()) {
2585
2586                         if (child->source_equivalent (region)) {
2587                                 return region;
2588                         }
2589                 }
2590         } 
2591
2592         return boost::shared_ptr<Region> ();
2593 }       
2594
2595 void
2596 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2597 {
2598         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2599                 (*i)->get_region_list_equivalent_regions (region, result);
2600 }
2601
2602 int
2603 Session::destroy_region (boost::shared_ptr<Region> region)
2604 {
2605         vector<boost::shared_ptr<Source> > srcs;
2606                 
2607         {
2608                 boost::shared_ptr<AudioRegion> aregion;
2609                 
2610                 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2611                         return 0;
2612                 }
2613                 
2614                 if (aregion->playlist()) {
2615                         aregion->playlist()->destroy_region (region);
2616                 }
2617                 
2618                 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2619                         srcs.push_back (aregion->source (n));
2620                 }
2621         }
2622
2623         region->drop_references ();
2624
2625         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2626
2627                 if (!(*i)->used()) {
2628                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2629                         
2630                         if (afs) {
2631                                 (afs)->mark_for_remove ();
2632                         }
2633                         
2634                         (*i)->drop_references ();
2635                         
2636                         cerr << "source was not used by any playlist\n";
2637                 }
2638         }
2639
2640         return 0;
2641 }
2642
2643 int
2644 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2645 {
2646         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2647                 destroy_region (*i);
2648         }
2649         return 0;
2650 }
2651
2652 int
2653 Session::remove_last_capture ()
2654 {
2655         list<boost::shared_ptr<Region> > r;
2656         
2657         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2658         
2659         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2660                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2661                 
2662                 if (!l.empty()) {
2663                         r.insert (r.end(), l.begin(), l.end());
2664                         l.clear ();
2665                 }
2666         }
2667
2668         destroy_regions (r);
2669
2670         save_state (_current_snapshot_name);
2671
2672         return 0;
2673 }
2674
2675 int
2676 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2677 {
2678         remove_region (r);
2679         return 0;
2680 }
2681
2682 /* Source Management */
2683 void
2684 Session::add_source (boost::shared_ptr<Source> source)
2685 {
2686         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2687         pair<SourceMap::iterator,bool> result;
2688
2689         entry.first = source->id();
2690         entry.second = source;
2691         
2692         {
2693                 Glib::Mutex::Lock lm (source_lock);
2694                 result = sources.insert (entry);
2695         }
2696
2697         if (result.second) {
2698                 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2699                 set_dirty();
2700         }
2701 }
2702
2703 void
2704 Session::remove_source (boost::weak_ptr<Source> src)
2705 {
2706         SourceMap::iterator i;
2707         boost::shared_ptr<Source> source = src.lock();
2708
2709         if (!source) {
2710                 return;
2711         } 
2712
2713         { 
2714                 Glib::Mutex::Lock lm (source_lock);
2715                 
2716                 { 
2717                         Glib::Mutex::Lock lm (source_lock);
2718                         
2719                         if ((i = sources.find (source->id())) != sources.end()) {
2720                                 sources.erase (i);
2721                         } 
2722                 }
2723         }
2724         
2725         if (!_state_of_the_state & InCleanup) {
2726                 
2727                 /* save state so we don't end up with a session file
2728                    referring to non-existent sources.
2729                 */
2730                 
2731                 save_state (_current_snapshot_name);
2732         }
2733 }
2734
2735 boost::shared_ptr<Source>
2736 Session::source_by_id (const PBD::ID& id)
2737 {
2738         Glib::Mutex::Lock lm (source_lock);
2739         SourceMap::iterator i;
2740         boost::shared_ptr<Source> source;
2741
2742         if ((i = sources.find (id)) != sources.end()) {
2743                 source = i->second;
2744         }
2745
2746         /* XXX search MIDI or other searches here */
2747         
2748         return source;
2749 }
2750
2751
2752 boost::shared_ptr<Source>
2753 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2754 {
2755         Glib::Mutex::Lock lm (source_lock);
2756
2757         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2758                 cerr << "comparing " << path << " with " << i->second->name() << endl;
2759                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2760
2761                 if (afs && afs->path() == path && chn == afs->channel()) {
2762                         return afs;
2763                 } 
2764                        
2765         }
2766         return boost::shared_ptr<Source>();
2767 }
2768
2769 string
2770 Session::peak_path_from_audio_path (string audio_path) const
2771 {
2772         sys::path peakfile_path(_session_dir->peak_path());
2773
2774         peakfile_path /= basename_nosuffix (audio_path) + peakfile_suffix;
2775
2776         return peakfile_path.to_string();
2777 }
2778
2779 string
2780 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2781 {
2782         string look_for;
2783         string old_basename = PBD::basename_nosuffix (oldname);
2784         string new_legalized = legalize_for_path (newname);
2785
2786         /* note: we know (or assume) the old path is already valid */
2787
2788         if (destructive) {
2789                 
2790                 /* destructive file sources have a name of the form:
2791
2792                     /path/to/Tnnnn-NAME(%[LR])?.wav
2793                   
2794                     the task here is to replace NAME with the new name.
2795                 */
2796                 
2797                 /* find last slash */
2798
2799                 string dir;
2800                 string prefix;
2801                 string::size_type slash;
2802                 string::size_type dash;
2803
2804                 if ((slash = path.find_last_of ('/')) == string::npos) {
2805                         return "";
2806                 }
2807
2808                 dir = path.substr (0, slash+1);
2809
2810                 /* '-' is not a legal character for the NAME part of the path */
2811
2812                 if ((dash = path.find_last_of ('-')) == string::npos) {
2813                         return "";
2814                 }
2815
2816                 prefix = path.substr (slash+1, dash-(slash+1));
2817
2818                 path = dir;
2819                 path += prefix;
2820                 path += '-';
2821                 path += new_legalized;
2822                 path += ".wav";  /* XXX gag me with a spoon */
2823                 
2824         } else {
2825                 
2826                 /* non-destructive file sources have a name of the form:
2827
2828                     /path/to/NAME-nnnnn(%[LR])?.wav
2829                   
2830                     the task here is to replace NAME with the new name.
2831                 */
2832                 
2833                 string dir;
2834                 string suffix;
2835                 string::size_type slash;
2836                 string::size_type dash;
2837                 string::size_type postfix;
2838
2839                 /* find last slash */
2840
2841                 if ((slash = path.find_last_of ('/')) == string::npos) {
2842                         return "";
2843                 }
2844
2845                 dir = path.substr (0, slash+1);
2846
2847                 /* '-' is not a legal character for the NAME part of the path */
2848
2849                 if ((dash = path.find_last_of ('-')) == string::npos) {
2850                         return "";
2851                 }
2852
2853                 suffix = path.substr (dash+1);
2854                 
2855                 // Suffix is now everything after the dash. Now we need to eliminate
2856                 // the nnnnn part, which is done by either finding a '%' or a '.'
2857
2858                 postfix = suffix.find_last_of ("%");
2859                 if (postfix == string::npos) {
2860                         postfix = suffix.find_last_of ('.');
2861                 }
2862
2863                 if (postfix != string::npos) {
2864                         suffix = suffix.substr (postfix);
2865                 } else {
2866                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2867                         return "";
2868                 }
2869
2870                 const uint32_t limit = 10000;
2871                 char buf[PATH_MAX+1];
2872
2873                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2874
2875                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2876
2877                         if (access (buf, F_OK) != 0) {
2878                                 path = buf;
2879                                 break;
2880                         }
2881                         path = "";
2882                 }
2883
2884                 if (path == "") {
2885                         error << "FATAL ERROR! Could not find a " << endl;
2886                 }
2887
2888         }
2889
2890         return path;
2891 }
2892
2893 string
2894 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2895 {
2896         string spath;
2897         uint32_t cnt;
2898         char buf[PATH_MAX+1];
2899         const uint32_t limit = 10000;
2900         string legalized;
2901
2902         buf[0] = '\0';
2903         legalized = legalize_for_path (name);
2904
2905         /* find a "version" of the file name that doesn't exist in
2906            any of the possible directories.
2907         */
2908
2909         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2910
2911                 vector<space_and_path>::iterator i;
2912                 uint32_t existing = 0;
2913
2914                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2915
2916                         SessionDirectory sdir((*i).path);
2917
2918                         spath = sdir.sound_path().to_string();
2919
2920                         if (destructive) {
2921                                 if (nchan < 2) {
2922                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2923                                 } else if (nchan == 2) {
2924                                         if (chan == 0) {
2925                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2926                                         } else {
2927                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2928                                         }
2929                                 } else if (nchan < 26) {
2930                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2931                                 } else {
2932                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2933                                 }
2934
2935                         } else {
2936
2937                                 spath += '/';
2938                                 spath += legalized;
2939
2940                                 if (nchan < 2) {
2941                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2942                                 } else if (nchan == 2) {
2943                                         if (chan == 0) {
2944                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2945                                         } else {
2946                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2947                                         }
2948                                 } else if (nchan < 26) {
2949                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2950                                 } else {
2951                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2952                                 }
2953                         }
2954
2955                         if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
2956                                 existing++;
2957                         } 
2958
2959                 }
2960
2961                 if (existing == 0) {
2962                         break;
2963                 }
2964
2965                 if (cnt > limit) {
2966                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
2967                         destroy ();
2968                         throw failed_constructor();
2969                 }
2970         }
2971
2972         /* we now have a unique name for the file, but figure out where to
2973            actually put it.
2974         */
2975
2976         string foo = buf;
2977
2978         SessionDirectory sdir(get_best_session_directory_for_new_source ());
2979
2980         spath = sdir.sound_path().to_string();
2981         spath += '/';
2982
2983         string::size_type pos = foo.find_last_of ('/');
2984         
2985         if (pos == string::npos) {
2986                 spath += foo;
2987         } else {
2988                 spath += foo.substr (pos + 1);
2989         }
2990
2991         return spath;
2992 }
2993
2994 boost::shared_ptr<AudioFileSource>
2995 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2996 {
2997         string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
2998         return boost::dynamic_pointer_cast<AudioFileSource> (
2999                 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3000 }
3001
3002 // FIXME: _terrible_ code duplication
3003 string
3004 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3005 {
3006         string look_for;
3007         string old_basename = PBD::basename_nosuffix (oldname);
3008         string new_legalized = legalize_for_path (newname);
3009
3010         /* note: we know (or assume) the old path is already valid */
3011
3012         if (destructive) {
3013                 
3014                 /* destructive file sources have a name of the form:
3015
3016                     /path/to/Tnnnn-NAME(%[LR])?.wav
3017                   
3018                     the task here is to replace NAME with the new name.
3019                 */
3020                 
3021                 /* find last slash */
3022
3023                 string dir;
3024                 string prefix;
3025                 string::size_type slash;
3026                 string::size_type dash;
3027
3028                 if ((slash = path.find_last_of ('/')) == string::npos) {
3029                         return "";
3030                 }
3031
3032                 dir = path.substr (0, slash+1);
3033
3034                 /* '-' is not a legal character for the NAME part of the path */
3035
3036                 if ((dash = path.find_last_of ('-')) == string::npos) {
3037                         return "";
3038                 }
3039
3040                 prefix = path.substr (slash+1, dash-(slash+1));
3041
3042                 path = dir;
3043                 path += prefix;
3044                 path += '-';
3045                 path += new_legalized;
3046                 path += ".mid";  /* XXX gag me with a spoon */
3047                 
3048         } else {
3049                 
3050                 /* non-destructive file sources have a name of the form:
3051
3052                     /path/to/NAME-nnnnn(%[LR])?.wav
3053                   
3054                     the task here is to replace NAME with the new name.
3055                 */
3056                 
3057                 string dir;
3058                 string suffix;
3059                 string::size_type slash;
3060                 string::size_type dash;
3061                 string::size_type postfix;
3062
3063                 /* find last slash */
3064
3065                 if ((slash = path.find_last_of ('/')) == string::npos) {
3066                         return "";
3067                 }
3068
3069                 dir = path.substr (0, slash+1);
3070
3071                 /* '-' is not a legal character for the NAME part of the path */
3072
3073                 if ((dash = path.find_last_of ('-')) == string::npos) {
3074                         return "";
3075                 }
3076
3077                 suffix = path.substr (dash+1);
3078                 
3079                 // Suffix is now everything after the dash. Now we need to eliminate
3080                 // the nnnnn part, which is done by either finding a '%' or a '.'
3081
3082                 postfix = suffix.find_last_of ("%");
3083                 if (postfix == string::npos) {
3084                         postfix = suffix.find_last_of ('.');
3085                 }
3086
3087                 if (postfix != string::npos) {
3088                         suffix = suffix.substr (postfix);
3089                 } else {
3090                         error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3091                         return "";
3092                 }
3093
3094                 const uint32_t limit = 10000;
3095                 char buf[PATH_MAX+1];
3096
3097                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3098
3099                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3100
3101                         if (access (buf, F_OK) != 0) {
3102                                 path = buf;
3103                                 break;
3104                         }
3105                         path = "";
3106                 }
3107
3108                 if (path == "") {
3109                         error << "FATAL ERROR! Could not find a " << endl;
3110                 }
3111
3112         }
3113
3114         return path;
3115 }
3116
3117 string
3118 Session::midi_path_from_name (string name)
3119 {
3120         string spath;
3121         uint32_t cnt;
3122         char buf[PATH_MAX+1];
3123         const uint32_t limit = 10000;
3124         string legalized;
3125
3126         buf[0] = '\0';
3127         legalized = legalize_for_path (name);
3128
3129         /* find a "version" of the file name that doesn't exist in
3130            any of the possible directories.
3131         */
3132
3133         for (cnt = 1; cnt <= limit; ++cnt) {
3134
3135                 vector<space_and_path>::iterator i;
3136                 uint32_t existing = 0;
3137
3138                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3139
3140                         SessionDirectory sdir((*i).path);
3141                 
3142                         sys::path p = sdir.midi_path();
3143
3144                         p /= legalized;
3145
3146                         spath = p.to_string();
3147
3148                         snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3149
3150                         if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
3151                                 existing++;
3152                         } 
3153                 }
3154
3155                 if (existing == 0) {
3156                         break;
3157                 }
3158
3159                 if (cnt > limit) {
3160                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3161                         throw failed_constructor();
3162                 }
3163         }
3164
3165         /* we now have a unique name for the file, but figure out where to
3166            actually put it.
3167         */
3168
3169         string foo = buf;
3170
3171         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3172
3173         spath = sdir.midi_path().to_string();
3174         spath += '/';
3175
3176         string::size_type pos = foo.find_last_of ('/');
3177         
3178         if (pos == string::npos) {
3179                 spath += foo;
3180         } else {
3181                 spath += foo.substr (pos + 1);
3182         }
3183
3184         return spath;
3185 }
3186
3187 boost::shared_ptr<MidiSource>
3188 Session::create_midi_source_for_session (MidiDiskstream& ds)
3189 {
3190         string mpath = midi_path_from_name (ds.name());
3191         
3192         return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3193 }
3194
3195
3196 /* Playlist management */
3197
3198 boost::shared_ptr<Playlist>
3199 Session::playlist_by_name (string name)
3200 {
3201         Glib::Mutex::Lock lm (playlist_lock);
3202         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3203                 if ((*i)->name() == name) {
3204                         return* i;
3205                 }
3206         }
3207         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3208                 if ((*i)->name() == name) {
3209                         return* i;
3210                 }
3211         }
3212
3213         return boost::shared_ptr<Playlist>();
3214 }
3215
3216 void
3217 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3218 {
3219         if (playlist->hidden()) {
3220                 return;
3221         }
3222
3223         { 
3224                 Glib::Mutex::Lock lm (playlist_lock);
3225                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3226                         playlists.insert (playlists.begin(), playlist);
3227                         playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3228                         playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3229                 }
3230         }
3231
3232         set_dirty();
3233
3234         PlaylistAdded (playlist); /* EMIT SIGNAL */
3235 }
3236
3237 void
3238 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3239 {
3240         { 
3241                 Glib::Mutex::Lock lm (playlist_lock);
3242                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3243                         s.push_back (*i);
3244                 }
3245                 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3246                         s.push_back (*i);
3247                 }
3248         }
3249 }
3250
3251 void
3252 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3253 {
3254         boost::shared_ptr<Playlist> pl(wpl.lock());
3255
3256         if (!pl) {
3257                 return;
3258         }
3259
3260         PlaylistList::iterator x;
3261
3262         if (pl->hidden()) {
3263                 /* its not supposed to be visible */
3264                 return;
3265         }
3266
3267         { 
3268                 Glib::Mutex::Lock lm (playlist_lock);
3269
3270                 if (!inuse) {
3271
3272                         unused_playlists.insert (pl);
3273                         
3274                         if ((x = playlists.find (pl)) != playlists.end()) {
3275                                 playlists.erase (x);
3276                         }
3277
3278                         
3279                 } else {
3280
3281                         playlists.insert (pl);
3282                         
3283                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3284                                 unused_playlists.erase (x);
3285                         }
3286                 }
3287         }
3288 }
3289
3290 void
3291 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3292 {
3293         if (_state_of_the_state & Deletion) {
3294                 return;
3295         }
3296
3297         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3298
3299         if (!playlist) {
3300                 return;
3301         }
3302
3303         { 
3304                 Glib::Mutex::Lock lm (playlist_lock);
3305
3306                 PlaylistList::iterator i;
3307
3308                 i = find (playlists.begin(), playlists.end(), playlist);
3309                 if (i != playlists.end()) {
3310                         playlists.erase (i);
3311                 }
3312
3313                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3314                 if (i != unused_playlists.end()) {
3315                         unused_playlists.erase (i);
3316                 }
3317                 
3318         }
3319
3320         set_dirty();
3321
3322         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3323 }
3324
3325 void 
3326 Session::set_audition (boost::shared_ptr<Region> r)
3327 {
3328         pending_audition_region = r;
3329         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3330         schedule_butler_transport_work ();
3331 }
3332
3333 void
3334 Session::audition_playlist ()
3335 {
3336         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3337         ev->region.reset ();
3338         queue_event (ev);
3339 }
3340
3341 void
3342 Session::non_realtime_set_audition ()
3343 {
3344         if (!pending_audition_region) {
3345                 auditioner->audition_current_playlist ();
3346         } else {
3347                 auditioner->audition_region (pending_audition_region);
3348                 pending_audition_region.reset ();
3349         }
3350         AuditionActive (true); /* EMIT SIGNAL */
3351 }
3352
3353 void
3354 Session::audition_region (boost::shared_ptr<Region> r)
3355 {
3356         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3357         ev->region = r;
3358         queue_event (ev);
3359 }
3360
3361 void
3362 Session::cancel_audition ()
3363 {
3364         if (auditioner->active()) {
3365                 auditioner->cancel_audition ();
3366                 AuditionActive (false); /* EMIT SIGNAL */
3367         }
3368 }
3369
3370 bool
3371 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3372 {
3373         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3374 }
3375
3376 void
3377 Session::remove_empty_sounds ()
3378 {
3379         PathScanner scanner;
3380
3381         vector<string *>* possible_audiofiles = scanner (_session_dir->sound_path().to_string (),
3382                         Config->get_possible_audio_file_regexp (), false, true);
3383         
3384         Glib::Mutex::Lock lm (source_lock);
3385         
3386         regex_t compiled_tape_track_pattern;
3387         int err;
3388
3389         if ((err = regcomp (&compiled_tape_track_pattern, "/T[0-9][0-9][0-9][0-9]-", REG_EXTENDED|REG_NOSUB))) {
3390
3391                 char msg[256];
3392                 
3393                 regerror (err, &compiled_tape_track_pattern, msg, sizeof (msg));
3394                 
3395                 error << string_compose (_("Cannot compile tape track regexp for use (%1)"), msg) << endmsg;
3396                 return;
3397         }
3398
3399         for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
3400                 
3401                 /* never remove files that appear to be a tape track */
3402
3403                 if (regexec (&compiled_tape_track_pattern, (*i)->c_str(), 0, 0, 0) == 0) {
3404                         delete *i;
3405                         continue;
3406                 }
3407                         
3408                 if (AudioFileSource::is_empty (*this, *(*i))) {
3409
3410                         unlink ((*i)->c_str());
3411                         
3412                         string peak_path = peak_path_from_audio_path (**i);
3413                         unlink (peak_path.c_str());
3414                 }
3415
3416                 delete* i;
3417         }
3418
3419         delete possible_audiofiles;
3420 }
3421
3422 bool
3423 Session::is_auditioning () const
3424 {
3425         /* can be called before we have an auditioner object */
3426         if (auditioner) {
3427                 return auditioner->active();
3428         } else {
3429                 return false;
3430         }
3431 }
3432
3433 void
3434 Session::set_all_solo (bool yn)
3435 {
3436         shared_ptr<RouteList> r = routes.reader ();
3437         
3438         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3439                 if (!(*i)->hidden()) {
3440                         (*i)->set_solo (yn, this);
3441                 }
3442         }
3443
3444         set_dirty();
3445 }
3446                 
3447 void
3448 Session::set_all_mute (bool yn)
3449 {
3450         shared_ptr<RouteList> r = routes.reader ();
3451         
3452         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3453                 if (!(*i)->hidden()) {
3454                         (*i)->set_mute (yn, this);
3455                 }
3456         }
3457
3458         set_dirty();
3459 }
3460                 
3461 uint32_t
3462 Session::n_diskstreams () const
3463 {
3464         uint32_t n = 0;
3465
3466         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3467
3468         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3469                 if (!(*i)->hidden()) {
3470                         n++;
3471                 }
3472         }
3473         return n;
3474 }
3475
3476 void
3477 Session::graph_reordered ()
3478 {
3479         /* don't do this stuff if we are setting up connections
3480            from a set_state() call or creating new tracks.
3481         */
3482
3483         if (_state_of_the_state & InitialConnecting) {
3484                 return;
3485         }
3486         
3487         /* every track/bus asked for this to be handled but it was deferred because
3488            we were connecting. do it now.
3489         */
3490
3491         request_input_change_handling ();
3492
3493         resort_routes ();
3494
3495         /* force all diskstreams to update their capture offset values to 
3496            reflect any changes in latencies within the graph.
3497         */
3498         
3499         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3500
3501         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3502                 (*i)->set_capture_offset ();
3503         }
3504 }
3505
3506 void
3507 Session::record_disenable_all ()
3508 {
3509         record_enable_change_all (false);
3510 }
3511
3512 void
3513 Session::record_enable_all ()
3514 {
3515         record_enable_change_all (true);
3516 }
3517
3518 void
3519 Session::record_enable_change_all (bool yn)
3520 {
3521         shared_ptr<RouteList> r = routes.reader ();
3522         
3523         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3524                 Track* at;
3525
3526                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3527                         at->set_record_enable (yn, this);
3528                 }
3529         }
3530         
3531         /* since we don't keep rec-enable state, don't mark session dirty */
3532 }
3533
3534 void
3535 Session::add_insert (Insert* insert)
3536 {
3537         Send* send;
3538         PortInsert* port_insert;
3539         PluginInsert* plugin_insert;
3540
3541         if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3542                 _port_inserts.insert (_port_inserts.begin(), port_insert);
3543         } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3544                 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3545         } else if ((send = dynamic_cast<Send *> (insert)) != 0) {
3546                 _sends.insert (_sends.begin(), send);
3547         } else {
3548                 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3549                 /*NOTREACHED*/
3550         }
3551
3552         insert->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_insert), insert));
3553
3554         set_dirty();
3555 }
3556
3557 void
3558 Session::remove_insert (Insert* insert)
3559 {
3560         Send* send;
3561         PortInsert* port_insert;
3562         PluginInsert* plugin_insert;
3563         
3564         if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3565                 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3566                 if (x != _port_inserts.end()) {
3567                         insert_bitset[port_insert->bit_slot()] = false;
3568                         _port_inserts.erase (x);
3569                 }
3570         } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3571                 _plugin_inserts.remove (plugin_insert);
3572         } else if ((send = dynamic_cast<Send *> (insert)) != 0) {
3573                 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3574                 if (x != _sends.end()) {
3575                         send_bitset[send->bit_slot()] = false;
3576                         _sends.erase (x);
3577                 }
3578         } else {
3579                 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3580                 /*NOTREACHED*/
3581         }
3582
3583         set_dirty();
3584 }
3585
3586 nframes_t
3587 Session::available_capture_duration ()
3588 {
3589         float sample_bytes_on_disk = 4.0; // keep gcc happy
3590
3591         switch (Config->get_native_file_data_format()) {
3592         case FormatFloat:
3593                 sample_bytes_on_disk = 4.0;
3594                 break;
3595
3596         case FormatInt24:
3597                 sample_bytes_on_disk = 3.0;
3598                 break;
3599
3600         default: 
3601                 /* impossible, but keep some gcc versions happy */
3602                 fatal << string_compose (_("programming error: %1"),
3603                                          X_("illegal native file data format"))
3604                       << endmsg;
3605                 /*NOTREACHED*/
3606         }
3607
3608         double scale = 4096.0 / sample_bytes_on_disk;
3609
3610         if (_total_free_4k_blocks * scale > (double) max_frames) {
3611                 return max_frames;
3612         }
3613         
3614         return (nframes_t) floor (_total_free_4k_blocks * scale);
3615 }
3616
3617 void
3618 Session::add_bundle (ARDOUR::Bundle* bundle)
3619 {
3620         {
3621                 Glib::Mutex::Lock guard (bundle_lock);
3622                 _bundles.push_back (bundle);
3623         }
3624         
3625         BundleAdded (bundle); /* EMIT SIGNAL */
3626
3627         set_dirty();
3628 }
3629
3630 void
3631 Session::remove_bundle (ARDOUR::Bundle* bundle)
3632 {
3633         bool removed = false;
3634
3635         {
3636                 Glib::Mutex::Lock guard (bundle_lock);
3637                 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3638                 
3639                 if (i != _bundles.end()) {
3640                         _bundles.erase (i);
3641                         removed = true;
3642                 }
3643         }
3644
3645         if (removed) {
3646                  BundleRemoved (bundle); /* EMIT SIGNAL */
3647         }
3648
3649         set_dirty();
3650 }
3651
3652 ARDOUR::Bundle *
3653 Session::bundle_by_name (string name) const
3654 {
3655         Glib::Mutex::Lock lm (bundle_lock);
3656
3657         for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3658                 if ((*i)->name() == name) {
3659                         return* i;
3660                 }
3661         }
3662
3663         return 0;
3664 }
3665
3666 void
3667 Session::tempo_map_changed (Change ignored)
3668 {
3669         clear_clicks ();
3670         set_dirty ();
3671 }
3672
3673 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3674  * the given count with the current block size.
3675  */
3676 void
3677 Session::ensure_buffers (ChanCount howmany)
3678 {
3679         // FIXME: NASTY assumption (midi block size == audio block size)
3680         _scratch_buffers->ensure_buffers(howmany, current_block_size);
3681         _send_buffers->ensure_buffers(howmany, current_block_size);
3682         _silent_buffers->ensure_buffers(howmany, current_block_size);
3683         
3684         allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3685 }
3686
3687 uint32_t
3688 Session::next_insert_id ()
3689 {
3690         /* this doesn't really loop forever. just think about it */
3691
3692         while (true) {
3693                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3694                         if (!insert_bitset[n]) {
3695                                 insert_bitset[n] = true;
3696                                 return n;
3697                                 
3698                         }
3699                 }
3700                 
3701                 /* none available, so resize and try again */
3702
3703                 insert_bitset.resize (insert_bitset.size() + 16, false);
3704         }
3705 }
3706
3707 uint32_t
3708 Session::next_send_id ()
3709 {
3710         /* this doesn't really loop forever. just think about it */
3711
3712         while (true) {
3713                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3714                         if (!send_bitset[n]) {
3715                                 send_bitset[n] = true;
3716                                 return n;
3717                                 
3718                         }
3719                 }
3720                 
3721                 /* none available, so resize and try again */
3722
3723                 send_bitset.resize (send_bitset.size() + 16, false);
3724         }
3725 }
3726
3727 void
3728 Session::mark_send_id (uint32_t id)
3729 {
3730         if (id >= send_bitset.size()) {
3731                 send_bitset.resize (id+16, false);
3732         }
3733         if (send_bitset[id]) {
3734                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3735         }
3736         send_bitset[id] = true;
3737 }
3738
3739 void
3740 Session::mark_insert_id (uint32_t id)
3741 {
3742         if (id >= insert_bitset.size()) {
3743                 insert_bitset.resize (id+16, false);
3744         }
3745         if (insert_bitset[id]) {
3746                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3747         }
3748         insert_bitset[id] = true;
3749 }
3750
3751 /* Named Selection management */
3752
3753 NamedSelection *
3754 Session::named_selection_by_name (string name)
3755 {
3756         Glib::Mutex::Lock lm (named_selection_lock);
3757         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3758                 if ((*i)->name == name) {
3759                         return* i;
3760                 }
3761         }
3762         return 0;
3763 }
3764
3765 void
3766 Session::add_named_selection (NamedSelection* named_selection)
3767 {
3768         { 
3769                 Glib::Mutex::Lock lm (named_selection_lock);
3770                 named_selections.insert (named_selections.begin(), named_selection);
3771         }
3772
3773         for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3774                 add_playlist (*i);
3775         }
3776
3777         set_dirty();
3778
3779         NamedSelectionAdded (); /* EMIT SIGNAL */
3780 }
3781
3782 void
3783 Session::remove_named_selection (NamedSelection* named_selection)
3784 {
3785         bool removed = false;
3786
3787         { 
3788                 Glib::Mutex::Lock lm (named_selection_lock);
3789
3790                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3791
3792                 if (i != named_selections.end()) {
3793                         delete (*i);
3794                         named_selections.erase (i);
3795                         set_dirty();
3796                         removed = true;
3797                 }
3798         }
3799
3800         if (removed) {
3801                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3802         }
3803 }
3804
3805 void
3806 Session::reset_native_file_format ()
3807 {
3808         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3809
3810         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3811                 (*i)->reset_write_sources (false);
3812         }
3813 }
3814
3815 bool
3816 Session::route_name_unique (string n) const
3817 {
3818         shared_ptr<RouteList> r = routes.reader ();
3819         
3820         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3821                 if ((*i)->name() == n) {
3822                         return false;
3823                 }
3824         }
3825         
3826         return true;
3827 }
3828
3829 uint32_t
3830 Session::n_playlists () const
3831 {
3832         Glib::Mutex::Lock lm (playlist_lock);
3833         return playlists.size();
3834 }
3835
3836 void
3837 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3838 {
3839         if (!force && howmany <= _npan_buffers) {
3840                 return;
3841         }
3842
3843         if (_pan_automation_buffer) {
3844
3845                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3846                         delete [] _pan_automation_buffer[i];
3847                 }
3848
3849                 delete [] _pan_automation_buffer;
3850         }
3851
3852         _pan_automation_buffer = new pan_t*[howmany];
3853         
3854         for (uint32_t i = 0; i < howmany; ++i) {
3855                 _pan_automation_buffer[i] = new pan_t[nframes];
3856         }
3857
3858         _npan_buffers = howmany;
3859 }
3860
3861 int
3862 Session::freeze (InterThreadInfo& itt)
3863 {
3864         shared_ptr<RouteList> r = routes.reader ();
3865
3866         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3867
3868                 Track *at;
3869
3870                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3871                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3872                            of every track.
3873                         */
3874                         at->freeze (itt);
3875                 }
3876         }
3877
3878         return 0;
3879 }
3880
3881 int
3882 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,      
3883                                bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3884 {
3885         int ret = -1;
3886         boost::shared_ptr<Playlist> playlist;
3887         boost::shared_ptr<AudioFileSource> fsource;
3888         uint32_t x;
3889         char buf[PATH_MAX+1];
3890         ChanCount nchans(track.audio_diskstream()->n_channels());
3891         nframes_t position;
3892         nframes_t this_chunk;
3893         nframes_t to_do;
3894         BufferSet buffers;
3895         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3896         const string sound_dir = sdir.sound_path().to_string();
3897
3898         // any bigger than this seems to cause stack overflows in called functions
3899         const nframes_t chunk_size = (128 * 1024)/4;
3900
3901         g_atomic_int_set (&processing_prohibited, 1);
3902         
3903         /* call tree *MUST* hold route_lock */
3904         
3905         if ((playlist = track.diskstream()->playlist()) == 0) {
3906                 goto out;
3907         }
3908
3909         /* external redirects will be a problem */
3910
3911         if (track.has_external_redirects()) {
3912                 goto out;
3913         }
3914
3915         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3916
3917                 for (x = 0; x < 99999; ++x) {
3918                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3919                         if (access (buf, F_OK) != 0) {
3920                                 break;
3921                         }
3922                 }
3923                 
3924                 if (x == 99999) {
3925                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3926                         goto out;
3927                 }
3928                 
3929                 try {
3930                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3931                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3932                 }
3933                 
3934                 catch (failed_constructor& err) {
3935                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3936                         goto out;
3937                 }
3938
3939                 srcs.push_back (fsource);
3940         }
3941
3942         /* XXX need to flush all redirects */
3943         
3944         position = start;
3945         to_do = len;
3946
3947         /* create a set of reasonably-sized buffers */
3948         buffers.ensure_buffers(nchans, chunk_size);
3949         buffers.set_count(nchans);
3950
3951         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3952                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3953                 if (afs)
3954                         afs->prepare_for_peakfile_writes ();
3955         }
3956                         
3957         while (to_do && !itt.cancel) {
3958                 
3959                 this_chunk = min (to_do, chunk_size);
3960                 
3961                 if (track.export_stuff (buffers, start, this_chunk)) {
3962                         goto out;
3963                 }
3964
3965                 uint32_t n = 0;
3966                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3967                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3968                         
3969                         if (afs) {
3970                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3971                                         goto out;
3972                                 }
3973                         }
3974                 }
3975                 
3976                 start += this_chunk;
3977                 to_do -= this_chunk;
3978                 
3979                 itt.progress = (float) (1.0 - ((double) to_do / len));
3980
3981         }
3982
3983         if (!itt.cancel) {
3984                 
3985                 time_t now;
3986                 struct tm* xnow;
3987                 time (&now);
3988                 xnow = localtime (&now);
3989                 
3990                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3991                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3992                         
3993                         if (afs) {
3994                                 afs->update_header (position, *xnow, now);
3995                                 afs->flush_header ();
3996                         }
3997                 }
3998                 
3999                 /* construct a region to represent the bounced material */
4000
4001                 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
4002                                                                            region_name_from_path (srcs.front()->name(), true));
4003
4004                 ret = 0;
4005         }
4006                 
4007   out:
4008         if (ret) {
4009                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4010                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4011
4012                         if (afs) {
4013                                 afs->mark_for_remove ();
4014                         }
4015
4016                         (*src)->drop_references ();
4017                 }
4018
4019         } else {
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->done_with_peakfile_writes ();
4025                 }
4026         }
4027
4028         g_atomic_int_set (&processing_prohibited, 0);
4029
4030         return ret;
4031 }
4032
4033 BufferSet&
4034 Session::get_silent_buffers (ChanCount count)
4035 {
4036         assert(_silent_buffers->available() >= count);
4037         _silent_buffers->set_count(count);
4038
4039         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4040                 for (size_t i=0; i < count.get(*t); ++i) {
4041                         _silent_buffers->get(*t, i).clear();
4042                 }
4043         }
4044         
4045         return *_silent_buffers;
4046 }
4047
4048 BufferSet&
4049 Session::get_scratch_buffers (ChanCount count)
4050 {
4051         assert(_scratch_buffers->available() >= count);
4052         _scratch_buffers->set_count(count);
4053         return *_scratch_buffers;
4054 }
4055
4056 BufferSet&
4057 Session::get_send_buffers (ChanCount count)
4058 {
4059         assert(_send_buffers->available() >= count);
4060         _send_buffers->set_count(count);
4061         return *_send_buffers;
4062 }
4063
4064 uint32_t 
4065 Session::ntracks () const
4066 {
4067         uint32_t n = 0;
4068         shared_ptr<RouteList> r = routes.reader ();
4069
4070         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4071                 if (dynamic_cast<Track*> ((*i).get())) {
4072                         ++n;
4073                 }
4074         }
4075
4076         return n;
4077 }
4078
4079 uint32_t 
4080 Session::nbusses () const
4081 {
4082         uint32_t n = 0;
4083         shared_ptr<RouteList> r = routes.reader ();
4084
4085         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4086                 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4087                         ++n;
4088                 }
4089         }
4090
4091         return n;
4092 }
4093
4094 void
4095 Session::add_automation_list(AutomationList *al)
4096 {
4097         automation_lists[al->id()] = al;
4098 }
4099
4100 nframes_t
4101 Session::compute_initial_length ()
4102 {
4103         return _engine.frame_rate() * 60 * 5;
4104 }
4105