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