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