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