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