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