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