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