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