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