e2deb716397b53a2ab64725213b0f19a1946206f
[ardour.git] / libs / ardour / session.cc
1 /*
2     Copyright (C) 1999-2010 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 <stdint.h>
21
22 #include <algorithm>
23 #include <string>
24 #include <vector>
25 #include <sstream>
26 #include <fstream>
27 #include <cstdio> /* sprintf(3) ... grrr */
28 #include <cmath>
29 #include <cerrno>
30 #include <unistd.h>
31 #include <limits.h>
32
33 #include <glibmm/threads.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
36
37 #include <boost/algorithm/string/erase.hpp>
38
39 #include "pbd/error.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/strsplit.h"
48 #include "pbd/unwind.h"
49
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/midi_ui.h"
73 #include "ardour/operations.h"
74 #include "ardour/playlist.h"
75 #include "ardour/plugin.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/rc_configuration.h"
79 #include "ardour/recent_sessions.h"
80 #include "ardour/region.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/route_graph.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_playlists.h"
88 #include "ardour/smf_source.h"
89 #include "ardour/source_factory.h"
90 #include "ardour/speakers.h"
91 #include "ardour/utils.h"
92
93 #include "midi++/port.h"
94 #include "midi++/mmc.h"
95
96 #include "i18n.h"
97
98 namespace ARDOUR {
99 class MidiSource;
100 class Processor;
101 class Speakers;
102 }
103
104 using namespace std;
105 using namespace ARDOUR;
106 using namespace PBD;
107
108 bool Session::_disable_all_loaded_plugins = false;
109
110 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
111 PBD::Signal1<void,std::string> Session::Dialog;
112 PBD::Signal0<int> Session::AskAboutPendingState;
113 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
114 PBD::Signal0<void> Session::SendFeedback;
115 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
116
117 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
118 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
119 PBD::Signal2<void,std::string, std::string> Session::Exported;
120 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
121 PBD::Signal0<void> Session::Quit;
122 PBD::Signal0<void> Session::FeedbackDetected;
123 PBD::Signal0<void> Session::SuccessfulGraphSort;
124 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
125
126 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
127 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
128
129 /** @param snapshot_name Snapshot name, without .ardour suffix */
130 Session::Session (AudioEngine &eng,
131                   const string& fullpath,
132                   const string& snapshot_name,
133                   BusProfile* bus_profile,
134                   string mix_template)
135         : playlists (new SessionPlaylists)
136         , _engine (eng)
137         , process_function (&Session::process_with_events)
138         , waiting_for_sync_offset (false)
139         , _base_frame_rate (0)
140         , _current_frame_rate (0)
141         , _nominal_frame_rate (0)
142         , transport_sub_state (0)
143         , _record_status (Disabled)
144         , _transport_frame (0)
145         , _session_range_location (0)
146         , _slave (0)
147         , _silent (false)
148         , _transport_speed (0)
149         , _default_transport_speed (1.0)
150         , _last_transport_speed (0)
151         , _target_transport_speed (0.0)
152         , auto_play_legal (false)
153         , _last_slave_transport_frame (0)
154         , maximum_output_latency (0)
155         , _requested_return_frame (-1)
156         , current_block_size (0)
157         , _worst_output_latency (0)
158         , _worst_input_latency (0)
159         , _worst_track_latency (0)
160         , _have_captured (false)
161         , _meter_hold (0)
162         , _meter_falloff (0)
163         , _non_soloed_outs_muted (false)
164         , _listen_cnt (0)
165         , _solo_isolated_cnt (0)
166         , _writable (false)
167         , _was_seamless (Config->get_seamless_loop ())
168         , _under_nsm_control (false)
169         , delta_accumulator_cnt (0)
170         , average_slave_delta (1800) // !!! why 1800 ???
171         , average_dir (0)
172         , have_first_delta_accumulator (false)
173         , _slave_state (Stopped)
174         , post_export_sync (false)
175         , post_export_position (0)
176         , _exporting (false)
177         , _export_started (false)
178         , _export_rolling (false)
179         , _pre_export_mmc_enabled (false)
180         , _name (snapshot_name)
181         , _is_new (true)
182         , _send_qf_mtc (false)
183         , _pframes_since_last_mtc (0)
184         , session_midi_feedback (0)
185         , play_loop (false)
186         , loop_changing (false)
187         , last_loopend (0)
188         , _session_dir (new SessionDirectory (fullpath))
189         , _current_snapshot_name (snapshot_name)          
190         , state_tree (0)
191         , state_was_pending (false)
192         , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
193         , _last_roll_location (0)
194         , _last_roll_or_reversal_location (0)
195         , _last_record_location (0)
196         , pending_locate_roll (false)
197         , pending_locate_frame (0)
198         , pending_locate_flush (false)
199         , pending_abort (false)
200         , pending_auto_loop (false)
201         , _butler (new Butler (*this))
202         , _post_transport_work (0)
203         ,  cumulative_rf_motion (0)
204         , rf_scale (1.0)
205         , _locations (new Locations (*this))
206         , step_speed (0)
207         , outbound_mtc_timecode_frame (0)
208         , next_quarter_frame_to_send (-1)
209         , _frames_per_timecode_frame (0)
210         , _frames_per_hour (0)
211         , _timecode_frames_per_hour (0)
212         , last_timecode_valid (false)
213         , last_timecode_when (0)
214         , _send_timecode_update (false)
215         , ltc_encoder (0)
216         , ltc_enc_buf(0)
217         , ltc_buf_off (0)
218         , ltc_buf_len (0)
219         , ltc_speed (0)
220         , ltc_enc_byte (0)
221         , ltc_enc_pos (0)
222         , ltc_enc_cnt (0)
223         , ltc_enc_off (0)
224         , restarting (false)
225         , ltc_prev_cycle (0)
226         , ltc_timecode_offset (0)
227         , ltc_timecode_negative_offset (false)
228         , midi_control_ui (0)
229         , _tempo_map (0)
230         , _all_route_group (new RouteGroup (*this, "all"))
231         , routes (new RouteList)
232         , _adding_routes_in_progress (false)
233         , destructive_index (0)
234         , solo_update_disabled (false)
235         , default_fade_steepness (0)
236         , default_fade_msecs (0)
237         , _total_free_4k_blocks (0)
238         , _total_free_4k_blocks_uncertain (false)
239         , no_questions_about_missing_files (false)
240         , _playback_load (0)
241         , _capture_load (0)
242         , _bundles (new BundleList)
243         , _bundle_xml_node (0)
244         , _current_trans (0)
245         , _clicking (false)
246         , click_data (0)
247         , click_emphasis_data (0)
248         , click_length (0)
249         , click_emphasis_length (0)
250         , _clicks_cleared (0)
251         , _play_range (false)
252         , main_outs (0)
253         , first_file_data_format_reset (true)
254         , first_file_header_format_reset (true)
255         , have_looped (false)
256         , _have_rec_enabled_track (false)
257         , _step_editors (0)
258         , _suspend_timecode_transmission (0)
259         ,  _speakers (new Speakers)
260         , ignore_route_processor_changes (false)
261 {
262         uint32_t sr = 0;
263
264         pre_engine_init (fullpath);
265         
266         if (_is_new) {
267                 if (ensure_engine (sr)) {
268                         destroy ();
269                         throw failed_constructor ();
270                 }
271
272                 if (create (mix_template, bus_profile)) {
273                         destroy ();
274                         throw failed_constructor ();
275                 }
276
277         } else {
278
279                 if (load_state (_current_snapshot_name)) {
280                         throw failed_constructor ();
281                 }
282         
283                 /* try to get sample rate from XML state so that we
284                  * can influence the SR if we set up the audio
285                  * engine.
286                  */
287
288                 if (state_tree) {
289                         const XMLProperty* prop;
290                         if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {           
291                                 sr = atoi (prop->value());
292                         }
293                 }
294
295                 if (ensure_engine (sr)) {
296                         destroy ();
297                         throw failed_constructor ();
298                 }
299         }
300
301         if (post_engine_init ()) {
302                 destroy ();
303                 throw failed_constructor ();
304         }
305
306         store_recent_sessions (_name, _path);
307
308         bool was_dirty = dirty();
309
310         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
311
312         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
313         config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
314
315         if (was_dirty) {
316                 DirtyChanged (); /* EMIT SIGNAL */
317         }
318
319         StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
320         EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
321
322         _is_new = false;
323
324         /* hook us up to the engine since we are now completely constructed */
325
326         BootMessage (_("Connect to engine"));
327
328         _engine.set_session (this);
329         _engine.reset_timebase ();
330
331         BootMessage (_("Session loading complete"));
332
333 }
334
335 Session::~Session ()
336 {
337 #ifdef PT_TIMING        
338         ST.dump ("ST.dump");
339 #endif  
340         destroy ();
341 }
342
343 int
344 Session::ensure_engine (uint32_t desired_sample_rate)
345 {
346         if (_engine.current_backend() == 0) {
347                 /* backend is unknown ... */
348                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
349                 if (r.get_value_or (-1) != 0) {
350                         return -1;
351                 }
352         } else if (_engine.setup_required()) {
353                 /* backend is known, but setup is needed */
354                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
355                 if (r.get_value_or (-1) != 0) {
356                         return -1;
357                 }
358         } else if (!_engine.running()) {
359                 if (_engine.start()) {
360                         return -1;
361                 }
362         }
363
364         /* at this point the engine should be running
365         */
366
367         if (!_engine.running()) {
368                 return -1;
369         }
370
371         /* the graph is just about as basic to everything else as the engine
372            so we create it here. this results in it coming into being at just
373            the right time for both new and existing sessions.
374
375            XXX some cleanup in the new/existing path is still waiting to be
376            done
377         */
378
379         if (how_many_dsp_threads () > 1) {
380                 /* For now, only create the graph if we are using >1 DSP threads, as
381                    it is a bit slower than the old code with 1 thread.
382                 */
383                 _process_graph.reset (new Graph (*this));
384         }
385
386         return 0;
387 }
388
389 void
390 Session::destroy ()
391 {
392         vector<void*> debug_pointers;
393
394         /* if we got to here, leaving pending capture state around
395            is a mistake.
396         */
397
398         remove_pending_capture_state ();
399
400         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
401
402         /* disconnect from any and all signals that we are connected to */
403
404         drop_connections ();
405
406         _engine.remove_session ();
407
408         /* deregister all ports - there will be no process or any other
409          * callbacks from the engine any more.
410          */
411
412         Port::PortDrop (); /* EMIT SIGNAL */
413
414         ltc_tx_cleanup();
415
416         /* clear history so that no references to objects are held any more */
417
418         _history.clear ();
419
420         /* clear state tree so that no references to objects are held any more */
421
422         delete state_tree;
423
424         /* reset dynamic state version back to default */
425
426         Stateful::loading_state_version = 0;
427
428         _butler->drop_references ();
429         delete _butler;
430         _butler = 0;
431         
432         delete midi_control_ui;
433         delete _all_route_group;
434
435         if (click_data != default_click) {
436                 delete [] click_data;
437         }
438
439         if (click_emphasis_data != default_click_emphasis) {
440                 delete [] click_emphasis_data;
441         }
442
443         clear_clicks ();
444
445         /* clear out any pending dead wood from RCU managed objects */
446
447         routes.flush ();
448         _bundles.flush ();
449
450         AudioDiskstream::free_working_buffers();
451
452         /* tell everyone who is still standing that we're about to die */
453         drop_references ();
454
455         /* tell everyone to drop references and delete objects as we go */
456
457         DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
458         RegionFactory::delete_all_regions ();
459
460         DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
461
462         /* reset these three references to special routes before we do the usual route delete thing */
463
464         auditioner.reset ();
465         _master_out.reset ();
466         _monitor_out.reset ();
467
468         {
469                 RCUWriter<RouteList> writer (routes);
470                 boost::shared_ptr<RouteList> r = writer.get_copy ();
471
472                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
473                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
474                         (*i)->drop_references ();
475                 }
476
477                 r->clear ();
478                 /* writer goes out of scope and updates master */
479         }
480         routes.flush ();
481
482         DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
483         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
484                 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
485                 i->second->drop_references ();
486         }
487
488         sources.clear ();
489
490         DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
491         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
492
493                 delete *i;
494         }
495
496         /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
497         playlists.reset ();
498
499         delete _mmc;
500         delete _midi_ports;
501         delete _locations;
502
503         DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
504
505 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
506         boost_debug_list_ptrs ();
507 #endif
508 }
509
510 void
511 Session::setup_ltc ()
512 {
513         XMLNode* child = 0;
514         
515         _ltc_input.reset (new IO (*this, _("LTC In"), IO::Input));
516         _ltc_output.reset (new IO (*this, _("LTC Out"), IO::Output));
517         
518         if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-In")) != 0) {
519                 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
520         } else {
521                 {
522                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
523                         _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
524                 }
525                 reconnect_ltc_input ();
526         }
527         
528         if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-Out")) != 0) {
529                 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
530         } else {
531                 {
532                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
533                         _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
534                 }
535                 reconnect_ltc_output ();
536         }
537         
538         /* fix up names of LTC ports because we don't want the normal
539          * IO style of NAME/TYPE-{in,out}N
540          */
541         
542         _ltc_input->nth (0)->set_name (_("LTC-in"));
543         _ltc_output->nth (0)->set_name (_("LTC-out"));
544 }
545
546 void
547 Session::setup_click ()
548 {
549         XMLNode* child = 0;
550
551         _clicking = false;
552         _click_io.reset (new ClickIO (*this, "click"));
553         _click_gain.reset (new Amp (*this));
554         _click_gain->activate ();
555         
556         if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
557                 
558                 /* existing state for Click */
559                 int c = 0;
560
561                 if (Stateful::loading_state_version < 3000) {
562                         c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
563                 } else {
564                         const XMLNodeList& children (child->children());
565                         XMLNodeList::const_iterator i = children.begin();
566                         if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
567                                 ++i;
568                                 if (i != children.end()) {
569                                         c = _click_gain->set_state (**i, Stateful::loading_state_version);
570                                 }
571                         }
572                 }
573                         
574                 if (c == 0) {
575                         _clicking = Config->get_clicking ();
576
577                 } else {
578
579                         error << _("could not setup Click I/O") << endmsg;
580                         _clicking = false;
581                 }
582
583
584         } else {
585
586                 /* default state for Click: dual-mono to first 2 physical outputs */
587
588                 vector<string> outs;
589                 _engine.get_physical_outputs (DataType::AUDIO, outs);
590
591                 for (uint32_t physport = 0; physport < 2; ++physport) {
592                         if (outs.size() > physport) {
593                                 if (_click_io->add_port (outs[physport], this)) {
594                                         // relax, even though its an error
595                                 }
596                         }
597                 }
598
599                 if (_click_io->n_ports () > ChanCount::ZERO) {
600                         _clicking = Config->get_clicking ();
601                 }
602         }
603 }
604
605 void
606 Session::setup_bundles ()
607 {
608         vector<string> inputs[DataType::num_types];
609         vector<string> outputs[DataType::num_types];
610         for (uint32_t i = 0; i < DataType::num_types; ++i) {
611                 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
612                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
613         }
614
615         /* Create a set of Bundle objects that map
616            to the physical I/O currently available.  We create both
617            mono and stereo bundles, so that the common cases of mono
618            and stereo tracks get bundles to put in their mixer strip
619            in / out menus.  There may be a nicer way of achieving that;
620            it doesn't really scale that well to higher channel counts
621         */
622
623         /* mono output bundles */
624
625         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
626                 char buf[32];
627                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
628
629                 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
630                 c->add_channel (_("mono"), DataType::AUDIO);
631                 c->set_port (0, outputs[DataType::AUDIO][np]);
632
633                 add_bundle (c);
634         }
635
636         /* stereo output bundles */
637
638         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
639                 if (np + 1 < outputs[DataType::AUDIO].size()) {
640                         char buf[32];
641                         snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
642                         boost::shared_ptr<Bundle> c (new Bundle (buf, true));
643                         c->add_channel (_("L"), DataType::AUDIO);
644                         c->set_port (0, outputs[DataType::AUDIO][np]);
645                         c->add_channel (_("R"), DataType::AUDIO);
646                         c->set_port (1, outputs[DataType::AUDIO][np + 1]);
647
648                         add_bundle (c);
649                 }
650         }
651
652         /* mono input bundles */
653
654         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
655                 char buf[32];
656                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
657
658                 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
659                 c->add_channel (_("mono"), DataType::AUDIO);
660                 c->set_port (0, inputs[DataType::AUDIO][np]);
661
662                 add_bundle (c);
663         }
664
665         /* stereo input bundles */
666
667         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
668                 if (np + 1 < inputs[DataType::AUDIO].size()) {
669                         char buf[32];
670                         snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
671
672                         boost::shared_ptr<Bundle> c (new Bundle (buf, false));
673                         c->add_channel (_("L"), DataType::AUDIO);
674                         c->set_port (0, inputs[DataType::AUDIO][np]);
675                         c->add_channel (_("R"), DataType::AUDIO);
676                         c->set_port (1, inputs[DataType::AUDIO][np + 1]);
677
678                         add_bundle (c);
679                 }
680         }
681
682         /* MIDI input bundles */
683
684         for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
685                 string n = inputs[DataType::MIDI][np];
686                 boost::erase_first (n, X_("alsa_pcm:"));
687
688                 boost::shared_ptr<Bundle> c (new Bundle (n, false));
689                 c->add_channel ("", DataType::MIDI);
690                 c->set_port (0, inputs[DataType::MIDI][np]);
691                 add_bundle (c);
692         }
693
694         /* MIDI output bundles */
695
696         for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
697                 string n = outputs[DataType::MIDI][np];
698                 boost::erase_first (n, X_("alsa_pcm:"));
699
700                 boost::shared_ptr<Bundle> c (new Bundle (n, true));
701                 c->add_channel ("", DataType::MIDI);
702                 c->set_port (0, outputs[DataType::MIDI][np]);
703                 add_bundle (c);
704         }
705
706 }
707
708 int
709 Session::when_engine_running ()
710 {
711         /* every time we reconnect, recompute worst case output latencies */
712
713         _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
714
715         if (synced_to_jack()) {
716                 _engine.transport_stop ();
717         }
718
719         if (config.get_jack_time_master()) {
720                 _engine.transport_locate (_transport_frame);
721         }
722
723
724         try {
725                 BootMessage (_("Set up LTC"));
726                 setup_ltc ();
727                 BootMessage (_("Set up Click"));
728                 setup_click ();
729                 BootMessage (_("Set up standard connections"));
730                 setup_bundles ();
731         }
732
733         catch (failed_constructor& err) {
734                 return -1;
735         }
736
737         BootMessage (_("Setup signal flow and plugins"));
738
739         /* Reset all panners */
740
741         Delivery::reset_panners ();
742
743         /* this will cause the CPM to instantiate any protocols that are in use
744          * (or mandatory), which will pass it this Session, and then call
745          * set_state() on each instantiated protocol to match stored state.
746          */
747
748         ControlProtocolManager::instance().set_session (this);
749
750         /* This must be done after the ControlProtocolManager set_session above,
751            as it will set states for ports which the ControlProtocolManager creates.
752         */
753
754         // XXX set state of MIDI::Port's
755         // MidiPortManager::instance()->set_port_states (Config->midi_port_states ());
756
757         /* And this must be done after the MIDI::Manager::set_port_states as
758          * it will try to make connections whose details are loaded by set_port_states.
759          */
760
761         hookup_io ();
762
763         /* Let control protocols know that we are now all connected, so they
764          * could start talking to surfaces if they want to.
765          */
766
767         ControlProtocolManager::instance().midi_connectivity_established ();
768
769         if (_is_new && !no_auto_connect()) {
770                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
771                 auto_connect_master_bus ();
772         }
773
774         _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
775
776         /* update latencies */
777
778         initialize_latencies ();
779
780         return 0;
781 }
782
783 void
784 Session::auto_connect_master_bus ()
785 {
786         if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
787                 return;
788         }
789                 
790         /* if requested auto-connect the outputs to the first N physical ports.
791          */
792         
793         uint32_t limit = _master_out->n_outputs().n_total();
794         vector<string> outputs[DataType::num_types];
795         
796         for (uint32_t i = 0; i < DataType::num_types; ++i) {
797                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
798         }
799         
800         for (uint32_t n = 0; n < limit; ++n) {
801                 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
802                 string connect_to;
803                 if (outputs[p->type()].size() > n) {
804                         connect_to = outputs[p->type()][n];
805                 }
806                 
807                 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
808                         if (_master_out->output()->connect (p, connect_to, this)) {
809                                 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
810                                       << endmsg;
811                                 break;
812                         }
813                 }
814         }
815 }
816
817 void
818 Session::remove_monitor_section ()
819 {
820         if (!_monitor_out) {
821                 return;
822         }
823
824         /* force reversion to Solo-In-Place */
825         Config->set_solo_control_is_listen_control (false);
826
827         {
828                 /* Hold process lock while doing this so that we don't hear bits and
829                  * pieces of audio as we work on each route.
830                  */
831                 
832                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
833                 
834                 /* Connect tracks to monitor section. Note that in an
835                    existing session, the internal sends will already exist, but we want the
836                    routes to notice that they connect to the control out specifically.
837                 */
838                 
839                 
840                 boost::shared_ptr<RouteList> r = routes.reader ();
841                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
842                 
843                 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
844                         
845                         if ((*x)->is_monitor()) {
846                                 /* relax */
847                         } else if ((*x)->is_master()) {
848                                 /* relax */
849                         } else {
850                                 (*x)->remove_aux_or_listen (_monitor_out);
851                         }
852                 }
853         }
854
855         remove_route (_monitor_out);
856         auto_connect_master_bus ();
857 }
858
859 void
860 Session::add_monitor_section ()
861 {
862         RouteList rl;
863
864         if (_monitor_out || !_master_out) {
865                 return;
866         }
867
868         boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
869
870         if (r->init ()) {
871                 return;
872         }
873
874 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
875         // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
876 #endif
877         {
878                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
879                 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
880                 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
881         }
882
883         rl.push_back (r);
884         add_routes (rl, false, false, false);
885         
886         assert (_monitor_out);
887
888         /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
889            are undefined, at best.
890         */
891         
892         uint32_t limit = _monitor_out->n_inputs().n_audio();
893         
894         if (_master_out) {
895                 
896                 /* connect the inputs to the master bus outputs. this
897                  * represents a separate data feed from the internal sends from
898                  * each route. as of jan 2011, it allows the monitor section to
899                  * conditionally ignore either the internal sends or the normal
900                  * input feed, but we should really find a better way to do
901                  * this, i think.
902                  */
903
904                 _master_out->output()->disconnect (this);
905
906                 for (uint32_t n = 0; n < limit; ++n) {
907                         boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
908                         boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
909                         
910                         if (o) {
911                                 string connect_to = o->name();
912                                 if (_monitor_out->input()->connect (p, connect_to, this)) {
913                                         error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
914                                               << endmsg;
915                                         break;
916                                 }
917                         }
918                 }
919         }
920         
921         /* if monitor section is not connected, connect it to physical outs
922          */
923         
924         if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
925                 
926                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
927                         
928                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
929                         
930                         if (b) {
931                                 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
932                         } else {
933                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
934                                                            Config->get_monitor_bus_preferred_bundle())
935                                         << endmsg;
936                         }
937                         
938                 } else {
939                         
940                         /* Monitor bus is audio only */
941
942                         uint32_t mod = n_physical_outputs.get (DataType::AUDIO);
943                         uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
944                         vector<string> outputs[DataType::num_types];
945
946                         for (uint32_t i = 0; i < DataType::num_types; ++i) {
947                                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
948                         }
949                         
950                         
951                         if (mod != 0) {
952                                 
953                                 for (uint32_t n = 0; n < limit; ++n) {
954                                         
955                                         boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
956                                         string connect_to;
957                                         if (outputs[DataType::AUDIO].size() > (n % mod)) {
958                                                 connect_to = outputs[DataType::AUDIO][n % mod];
959                                         }
960                                         
961                                         if (!connect_to.empty()) {
962                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
963                                                         error << string_compose (
964                                                                 _("cannot connect control output %1 to %2"),
965                                                                 n, connect_to)
966                                                               << endmsg;
967                                                         break;
968                                                 }
969                                         }
970                                 }
971                         }
972                 }
973         }
974
975         /* Hold process lock while doing this so that we don't hear bits and
976          * pieces of audio as we work on each route.
977          */
978          
979         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
980
981         /* Connect tracks to monitor section. Note that in an
982            existing session, the internal sends will already exist, but we want the
983            routes to notice that they connect to the control out specifically.
984         */
985
986
987         boost::shared_ptr<RouteList> rls = routes.reader ();
988
989         PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
990
991         for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
992                 
993                 if ((*x)->is_monitor()) {
994                         /* relax */
995                 } else if ((*x)->is_master()) {
996                         /* relax */
997                 } else {
998                         (*x)->enable_monitor_send ();
999                 }
1000         }
1001 }
1002
1003 void
1004 Session::hookup_io ()
1005 {
1006         /* stop graph reordering notifications from
1007            causing resorts, etc.
1008         */
1009
1010         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1011
1012         if (!auditioner) {
1013
1014                 /* we delay creating the auditioner till now because
1015                    it makes its own connections to ports.
1016                 */
1017
1018                 try {
1019                         boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1020                         if (a->init()) {
1021                                 throw failed_constructor ();
1022                         }
1023                         a->use_new_diskstream ();
1024                         auditioner = a;
1025                 }
1026
1027                 catch (failed_constructor& err) {
1028                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1029                 }
1030         }
1031
1032         /* load bundles, which we may have postponed earlier on */
1033         if (_bundle_xml_node) {
1034                 load_bundles (*_bundle_xml_node);
1035                 delete _bundle_xml_node;
1036         }
1037
1038         /* Tell all IO objects to connect themselves together */
1039
1040         IO::enable_connecting ();
1041
1042         /* Now tell all "floating" ports to connect to whatever
1043            they should be connected to.
1044         */
1045
1046         AudioEngine::instance()->reconnect_ports ();
1047
1048         /* Anyone who cares about input state, wake up and do something */
1049
1050         IOConnectionsComplete (); /* EMIT SIGNAL */
1051
1052         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1053
1054         /* now handle the whole enchilada as if it was one
1055            graph reorder event.
1056         */
1057
1058         graph_reordered ();
1059
1060         /* update the full solo state, which can't be
1061            correctly determined on a per-route basis, but
1062            needs the global overview that only the session
1063            has.
1064         */
1065
1066         update_route_solo_state ();
1067 }
1068
1069 void
1070 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1071 {
1072         boost::shared_ptr<Track> track = wp.lock ();
1073         if (!track) {
1074                 return;
1075         }
1076
1077         boost::shared_ptr<Playlist> playlist;
1078
1079         if ((playlist = track->playlist()) != 0) {
1080                 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1081                 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1082                 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1083         }
1084 }
1085
1086 bool
1087 Session::record_enabling_legal () const
1088 {
1089         /* this used to be in here, but survey says.... we don't need to restrict it */
1090         // if (record_status() == Recording) {
1091         //      return false;
1092         // }
1093
1094         if (Config->get_all_safe()) {
1095                 return false;
1096         }
1097         return true;
1098 }
1099
1100 void
1101 Session::set_track_monitor_input_status (bool yn)
1102 {
1103         boost::shared_ptr<RouteList> rl = routes.reader ();
1104         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1105                 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1106                 if (tr && tr->record_enabled ()) {
1107                         //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1108                         tr->request_input_monitoring (yn);
1109                 }
1110         }
1111 }
1112
1113 void
1114 Session::auto_punch_start_changed (Location* location)
1115 {
1116         replace_event (SessionEvent::PunchIn, location->start());
1117
1118         if (get_record_enabled() && config.get_punch_in()) {
1119                 /* capture start has been changed, so save new pending state */
1120                 save_state ("", true);
1121         }
1122 }
1123
1124 void
1125 Session::auto_punch_end_changed (Location* location)
1126 {
1127         framepos_t when_to_stop = location->end();
1128         // when_to_stop += _worst_output_latency + _worst_input_latency;
1129         replace_event (SessionEvent::PunchOut, when_to_stop);
1130 }
1131
1132 void
1133 Session::auto_punch_changed (Location* location)
1134 {
1135         framepos_t when_to_stop = location->end();
1136
1137         replace_event (SessionEvent::PunchIn, location->start());
1138         //when_to_stop += _worst_output_latency + _worst_input_latency;
1139         replace_event (SessionEvent::PunchOut, when_to_stop);
1140 }
1141
1142 /** @param loc A loop location.
1143  *  @param pos Filled in with the start time of the required fade-out (in session frames).
1144  *  @param length Filled in with the length of the required fade-out.
1145  */
1146 void
1147 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1148 {
1149         pos = max (loc->start(), loc->end() - 64);
1150         length = loc->end() - pos;
1151 }
1152
1153 void
1154 Session::auto_loop_changed (Location* location)
1155 {
1156         replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1157         framepos_t dcp;
1158         framecnt_t dcl;
1159         auto_loop_declick_range (location, dcp, dcl);
1160         replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1161
1162         if (transport_rolling() && play_loop) {
1163
1164
1165                 // if (_transport_frame > location->end()) {
1166
1167                 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1168                         // relocate to beginning of loop
1169                         clear_events (SessionEvent::LocateRoll);
1170
1171                         request_locate (location->start(), true);
1172
1173                 }
1174                 else if (Config->get_seamless_loop() && !loop_changing) {
1175
1176                         // schedule a locate-roll to refill the diskstreams at the
1177                         // previous loop end
1178                         loop_changing = true;
1179
1180                         if (location->end() > last_loopend) {
1181                                 clear_events (SessionEvent::LocateRoll);
1182                                 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1183                                 queue_event (ev);
1184                         }
1185
1186                 }
1187         }
1188
1189         last_loopend = location->end();
1190 }
1191
1192 void
1193 Session::set_auto_punch_location (Location* location)
1194 {
1195         Location* existing;
1196
1197         if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1198                 punch_connections.drop_connections();
1199                 existing->set_auto_punch (false, this);
1200                 remove_event (existing->start(), SessionEvent::PunchIn);
1201                 clear_events (SessionEvent::PunchOut);
1202                 auto_punch_location_changed (0);
1203         }
1204
1205         set_dirty();
1206
1207         if (location == 0) {
1208                 return;
1209         }
1210
1211         if (location->end() <= location->start()) {
1212                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1213                 return;
1214         }
1215
1216         punch_connections.drop_connections ();
1217
1218         location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1219         location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1220         location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1221
1222         location->set_auto_punch (true, this);
1223
1224         auto_punch_changed (location);
1225
1226         auto_punch_location_changed (location);
1227 }
1228
1229 void
1230 Session::set_auto_loop_location (Location* location)
1231 {
1232         Location* existing;
1233
1234         if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1235                 loop_connections.drop_connections ();
1236                 existing->set_auto_loop (false, this);
1237                 remove_event (existing->end(), SessionEvent::AutoLoop);
1238                 framepos_t dcp;
1239                 framecnt_t dcl;
1240                 auto_loop_declick_range (existing, dcp, dcl);
1241                 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1242                 auto_loop_location_changed (0);
1243         }
1244
1245         set_dirty();
1246
1247         if (location == 0) {
1248                 return;
1249         }
1250
1251         if (location->end() <= location->start()) {
1252                 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1253                 return;
1254         }
1255
1256         last_loopend = location->end();
1257
1258         loop_connections.drop_connections ();
1259
1260         location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1261         location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1262         location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1263
1264         location->set_auto_loop (true, this);
1265
1266         /* take care of our stuff first */
1267
1268         auto_loop_changed (location);
1269
1270         /* now tell everyone else */
1271
1272         auto_loop_location_changed (location);
1273 }
1274
1275 void
1276 Session::locations_added (Location *)
1277 {
1278         set_dirty ();
1279 }
1280
1281 void
1282 Session::locations_changed ()
1283 {
1284         _locations->apply (*this, &Session::handle_locations_changed);
1285 }
1286
1287 void
1288 Session::handle_locations_changed (Locations::LocationList& locations)
1289 {
1290         Locations::LocationList::iterator i;
1291         Location* location;
1292         bool set_loop = false;
1293         bool set_punch = false;
1294
1295         for (i = locations.begin(); i != locations.end(); ++i) {
1296
1297                 location =* i;
1298
1299                 if (location->is_auto_punch()) {
1300                         set_auto_punch_location (location);
1301                         set_punch = true;
1302                 }
1303                 if (location->is_auto_loop()) {
1304                         set_auto_loop_location (location);
1305                         set_loop = true;
1306                 }
1307
1308                 if (location->is_session_range()) {
1309                         _session_range_location = location;
1310                 }
1311         }
1312
1313         if (!set_loop) {
1314                 set_auto_loop_location (0);
1315         }
1316         if (!set_punch) {
1317                 set_auto_punch_location (0);
1318         }
1319
1320         set_dirty();
1321 }
1322
1323 void
1324 Session::enable_record ()
1325 {
1326         if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1327                 /* no recording at anything except normal speed */
1328                 return;
1329         }
1330
1331         while (1) {
1332                 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1333
1334                 if (rs == Recording) {
1335                         break;
1336                 }
1337                 
1338                 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1339
1340                         _last_record_location = _transport_frame;
1341                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1342
1343                         if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1344                                 set_track_monitor_input_status (true);
1345                         }
1346
1347                         RecordStateChanged ();
1348                         break;
1349                 }
1350         }
1351 }
1352
1353 void
1354 Session::disable_record (bool rt_context, bool force)
1355 {
1356         RecordState rs;
1357
1358         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1359
1360                 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1361                         g_atomic_int_set (&_record_status, Disabled);
1362                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1363                 } else {
1364                         if (rs == Recording) {
1365                                 g_atomic_int_set (&_record_status, Enabled);
1366                         }
1367                 }
1368
1369                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1370                         set_track_monitor_input_status (false);
1371                 }
1372
1373                 RecordStateChanged (); /* emit signal */
1374
1375                 if (!rt_context) {
1376                         remove_pending_capture_state ();
1377                 }
1378         }
1379 }
1380
1381 void
1382 Session::step_back_from_record ()
1383 {
1384         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1385
1386                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1387                         set_track_monitor_input_status (false);
1388                 }
1389
1390                 RecordStateChanged (); /* emit signal */
1391         }
1392 }
1393
1394 void
1395 Session::maybe_enable_record ()
1396 {
1397         if (_step_editors > 0) {
1398                 return;
1399         }
1400
1401         g_atomic_int_set (&_record_status, Enabled);
1402
1403         /* This function is currently called from somewhere other than an RT thread.
1404            This save_state() call therefore doesn't impact anything.  Doing it here
1405            means that we save pending state of which sources the next record will use,
1406            which gives us some chance of recovering from a crash during the record.
1407         */
1408
1409         save_state ("", true);
1410
1411         if (_transport_speed) {
1412                 if (!config.get_punch_in()) {
1413                         enable_record ();
1414                 }
1415         } else {
1416                 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1417                 RecordStateChanged (); /* EMIT SIGNAL */
1418         }
1419
1420         set_dirty();
1421 }
1422
1423 framepos_t
1424 Session::audible_frame () const
1425 {
1426         framepos_t ret;
1427         framepos_t tf;
1428         framecnt_t offset;
1429
1430         /* the first of these two possible settings for "offset"
1431            mean that the audible frame is stationary until
1432            audio emerges from the latency compensation
1433            "pseudo-pipeline".
1434
1435            the second means that the audible frame is stationary
1436            until audio would emerge from a physical port
1437            in the absence of any plugin latency compensation
1438         */
1439
1440         offset = worst_playback_latency ();
1441
1442         if (offset > current_block_size) {
1443                 offset -= current_block_size;
1444         } else {
1445                 /* XXX is this correct? if we have no external
1446                    physical connections and everything is internal
1447                    then surely this is zero? still, how
1448                    likely is that anyway?
1449                 */
1450                 offset = current_block_size;
1451         }
1452
1453         if (synced_to_jack()) {
1454                 tf = _engine.transport_frame();
1455         } else {
1456                 tf = _transport_frame;
1457         }
1458
1459         ret = tf;
1460
1461         if (!non_realtime_work_pending()) {
1462
1463                 /* MOVING */
1464
1465                 /* Check to see if we have passed the first guaranteed
1466                    audible frame past our last start position. if not,
1467                    return that last start point because in terms
1468                    of audible frames, we have not moved yet.
1469
1470                    `Start position' in this context means the time we last
1471                    either started, located, or changed transport direction.
1472                 */
1473
1474                 if (_transport_speed > 0.0f) {
1475
1476                         if (!play_loop || !have_looped) {
1477                                 if (tf < _last_roll_or_reversal_location + offset) {
1478                                         return _last_roll_or_reversal_location;
1479                                 }
1480                         }
1481
1482
1483                         /* forwards */
1484                         ret -= offset;
1485
1486                 } else if (_transport_speed < 0.0f) {
1487
1488                         /* XXX wot? no backward looping? */
1489
1490                         if (tf > _last_roll_or_reversal_location - offset) {
1491                                 return _last_roll_or_reversal_location;
1492                         } else {
1493                                 /* backwards */
1494                                 ret += offset;
1495                         }
1496                 }
1497         }
1498
1499         return ret;
1500 }
1501
1502 void
1503 Session::set_frame_rate (framecnt_t frames_per_second)
1504 {
1505         /** \fn void Session::set_frame_size(framecnt_t)
1506                 the AudioEngine object that calls this guarantees
1507                 that it will not be called while we are also in
1508                 ::process(). Its fine to do things that block
1509                 here.
1510         */
1511
1512         _base_frame_rate = frames_per_second;
1513         _nominal_frame_rate = frames_per_second;
1514
1515         sync_time_vars();
1516
1517         clear_clicks ();
1518
1519         // XXX we need some equivalent to this, somehow
1520         // SndFileSource::setup_standard_crossfades (frames_per_second);
1521
1522         set_dirty();
1523
1524         /* XXX need to reset/reinstantiate all LADSPA plugins */
1525 }
1526
1527 void
1528 Session::set_block_size (pframes_t nframes)
1529 {
1530         /* the AudioEngine guarantees
1531            that it will not be called while we are also in
1532            ::process(). It is therefore fine to do things that block
1533            here.
1534         */
1535         
1536         {
1537                 current_block_size = nframes;
1538
1539                 ensure_buffers ();
1540
1541                 boost::shared_ptr<RouteList> r = routes.reader ();
1542
1543                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1544                         (*i)->set_block_size (nframes);
1545                 }
1546
1547                 boost::shared_ptr<RouteList> rl = routes.reader ();
1548                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1549                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1550                         if (tr) {
1551                                 tr->set_block_size (nframes);
1552                         }
1553                 }
1554
1555                 set_worst_io_latencies ();
1556         }
1557 }
1558
1559
1560 static void
1561 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1562 {
1563         boost::shared_ptr<Route> r2;
1564
1565         if (r1->feeds (rbase) && rbase->feeds (r1)) {
1566                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1567                 return;
1568         }
1569
1570         /* make a copy of the existing list of routes that feed r1 */
1571
1572         Route::FedBy existing (r1->fed_by());
1573
1574         /* for each route that feeds r1, recurse, marking it as feeding
1575            rbase as well.
1576         */
1577
1578         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1579                 if (!(r2 = i->r.lock ())) {
1580                         /* (*i) went away, ignore it */
1581                         continue;
1582                 }
1583
1584                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1585                    base as being fed by r2
1586                 */
1587
1588                 rbase->add_fed_by (r2, i->sends_only);
1589
1590                 if (r2 != rbase) {
1591
1592                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1593                            stop here.
1594                         */
1595
1596                         if (r1->feeds (r2) && r2->feeds (r1)) {
1597                                 continue;
1598                         }
1599
1600                         /* now recurse, so that we can mark base as being fed by
1601                            all routes that feed r2
1602                         */
1603
1604                         trace_terminal (r2, rbase);
1605                 }
1606
1607         }
1608 }
1609
1610 void
1611 Session::resort_routes ()
1612 {
1613         /* don't do anything here with signals emitted
1614            by Routes during initial setup or while we
1615            are being destroyed.
1616         */
1617
1618         if (_state_of_the_state & (InitialConnecting | Deletion)) {
1619                 return;
1620         }
1621
1622         {
1623                 RCUWriter<RouteList> writer (routes);
1624                 boost::shared_ptr<RouteList> r = writer.get_copy ();
1625                 resort_routes_using (r);
1626                 /* writer goes out of scope and forces update */
1627         }
1628
1629 #ifndef NDEBUG
1630         boost::shared_ptr<RouteList> rl = routes.reader ();
1631         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1632                 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1633
1634                 const Route::FedBy& fb ((*i)->fed_by());
1635
1636                 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1637                         boost::shared_ptr<Route> sf = f->r.lock();
1638                         if (sf) {
1639                                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1640                         }
1641                 }
1642         }
1643 #endif
1644
1645 }
1646
1647 /** This is called whenever we need to rebuild the graph of how we will process
1648  *  routes.
1649  *  @param r List of routes, in any order.
1650  */
1651
1652 void
1653 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1654 {
1655         /* We are going to build a directed graph of our routes;
1656            this is where the edges of that graph are put.
1657         */
1658         
1659         GraphEdges edges;
1660
1661         /* Go through all routes doing two things:
1662          *
1663          * 1. Collect the edges of the route graph.  Each of these edges
1664          *    is a pair of routes, one of which directly feeds the other
1665          *    either by a JACK connection or by an internal send.
1666          *
1667          * 2. Begin the process of making routes aware of which other
1668          *    routes directly or indirectly feed them.  This information
1669          *    is used by the solo code.
1670          */
1671            
1672         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1673
1674                 /* Clear out the route's list of direct or indirect feeds */
1675                 (*i)->clear_fed_by ();
1676
1677                 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1678
1679                         bool via_sends_only;
1680
1681                         /* See if this *j feeds *i according to the current state of the JACK
1682                            connections and internal sends.
1683                         */
1684                         if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1685                                 /* add the edge to the graph (part #1) */
1686                                 edges.add (*j, *i, via_sends_only);
1687                                 /* tell the route (for part #2) */
1688                                 (*i)->add_fed_by (*j, via_sends_only);
1689                         }
1690                 }
1691         }
1692
1693         /* Attempt a topological sort of the route graph */
1694         boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1695         
1696         if (sorted_routes) {
1697                 /* We got a satisfactory topological sort, so there is no feedback;
1698                    use this new graph.
1699
1700                    Note: the process graph rechain does not require a
1701                    topologically-sorted list, but hey ho.
1702                 */
1703                 if (_process_graph) {
1704                         _process_graph->rechain (sorted_routes, edges);
1705                 }
1706                 
1707                 _current_route_graph = edges;
1708
1709                 /* Complete the building of the routes' lists of what directly
1710                    or indirectly feeds them.
1711                 */
1712                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1713                         trace_terminal (*i, *i);
1714                 }
1715
1716                 *r = *sorted_routes;
1717
1718 #ifndef NDEBUG
1719                 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1720                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1721                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1722                                                                    (*i)->name(), (*i)->order_key (MixerSort)));
1723                 }
1724 #endif
1725
1726                 SuccessfulGraphSort (); /* EMIT SIGNAL */
1727
1728         } else {
1729                 /* The topological sort failed, so we have a problem.  Tell everyone
1730                    and stick to the old graph; this will continue to be processed, so
1731                    until the feedback is fixed, what is played back will not quite
1732                    reflect what is actually connected.  Note also that we do not
1733                    do trace_terminal here, as it would fail due to an endless recursion,
1734                    so the solo code will think that everything is still connected
1735                    as it was before.
1736                 */
1737                 
1738                 FeedbackDetected (); /* EMIT SIGNAL */
1739         }
1740
1741 }
1742
1743 /** Find a route name starting with \a base, maybe followed by the
1744  *  lowest \a id.  \a id will always be added if \a definitely_add_number
1745  *  is true on entry; otherwise it will only be added if required
1746  *  to make the name unique.
1747  *
1748  *  Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1749  *  The available route name with the lowest ID will be used, and \a id
1750  *  will be set to the ID.
1751  *
1752  *  \return false if a route name could not be found, and \a track_name
1753  *  and \a id do not reflect a free route name.
1754  */
1755 bool
1756 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1757 {
1758         if (!definitely_add_number && route_by_name (base) == 0) {
1759                 /* juse use the base */
1760                 snprintf (name, name_len, "%s", base.c_str());
1761                 return true;
1762         }
1763
1764         do {
1765                 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1766
1767                 if (route_by_name (name) == 0) {
1768                         return true;
1769                 }
1770
1771                 ++id;
1772                 
1773         } while (id < (UINT_MAX-1));
1774
1775         return false;
1776 }
1777
1778 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1779 void
1780 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1781 {
1782         in  = ChanCount::ZERO;
1783         out = ChanCount::ZERO;
1784
1785         boost::shared_ptr<RouteList> r = routes.reader ();
1786
1787         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1788                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1789                 if (tr && !tr->is_auditioner()) {
1790                         in  += tr->n_inputs();
1791                         out += tr->n_outputs();
1792                 }
1793         }
1794 }
1795
1796 /** Caller must not hold process lock
1797  *  @param name_template string to use for the start of the name, or "" to use "MIDI".
1798  *  @param instrument plugin info for the instrument to insert pre-fader, if any
1799  */
1800 list<boost::shared_ptr<MidiTrack> >
1801 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument, 
1802                          TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1803 {
1804         char track_name[32];
1805         uint32_t track_id = 0;
1806         string port;
1807         RouteList new_routes;
1808         list<boost::shared_ptr<MidiTrack> > ret;
1809
1810         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1811
1812         while (how_many) {
1813                 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1814                         error << "cannot find name for new midi track" << endmsg;
1815                         goto failed;
1816                 }
1817
1818                 boost::shared_ptr<MidiTrack> track;
1819
1820                 try {
1821                         track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1822
1823                         if (track->init ()) {
1824                                 goto failed;
1825                         }
1826
1827                         track->use_new_diskstream();
1828
1829 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1830                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1831 #endif
1832                         {
1833                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1834                                 if (track->input()->ensure_io (input, false, this)) {
1835                                         error << "cannot configure " << input << " out configuration for new midi track" << endmsg;     
1836                                         goto failed;
1837                                 }
1838
1839                                 if (track->output()->ensure_io (output, false, this)) {
1840                                         error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1841                                         goto failed;
1842                                 }
1843                         }
1844
1845                         track->non_realtime_input_change();
1846
1847                         if (route_group) {
1848                                 route_group->add (track);
1849                         }
1850
1851                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1852
1853                         if (Config->get_remote_model() == UserOrdered) {
1854                                 track->set_remote_control_id (next_control_id());
1855                         }
1856
1857                         new_routes.push_back (track);
1858                         ret.push_back (track);
1859                 }
1860
1861                 catch (failed_constructor &err) {
1862                         error << _("Session: could not create new midi track.") << endmsg;
1863                         goto failed;
1864                 }
1865
1866                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1867
1868                         error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
1869                         goto failed;
1870                 }
1871
1872                 --how_many;
1873         }
1874
1875   failed:
1876         if (!new_routes.empty()) {
1877                 add_routes (new_routes, true, true, true);
1878
1879                 if (instrument) {
1880                         for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1881                                 PluginPtr plugin = instrument->load (*this);
1882                                 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1883                                 (*r)->add_processor (p, PreFader);
1884                                 
1885                         }
1886                 }
1887         }
1888
1889         return ret;
1890 }
1891
1892 void
1893 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1894 {
1895         boost::shared_ptr<Route> midi_track (wmt.lock());
1896
1897         if (!midi_track) {
1898                 return;
1899         }
1900
1901         if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1902
1903                 if (change.after.n_audio() <= change.before.n_audio()) {
1904                         return;
1905                 }
1906
1907                 /* new audio ports: make sure the audio goes somewhere useful,
1908                    unless the user has no-auto-connect selected.
1909
1910                    The existing ChanCounts don't matter for this call as they are only
1911                    to do with matching input and output indices, and we are only changing
1912                    outputs here.
1913                 */
1914
1915                 ChanCount dummy;
1916
1917                 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1918         }
1919 }
1920
1921 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1922  *  @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1923  *  @param output_start As \a input_start, but for outputs.
1924  */
1925 void
1926 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1927                              bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1928 {
1929         if (!IO::connecting_legal) {
1930                 return;
1931         }
1932
1933         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1934
1935         if (with_lock) {
1936                 lm.acquire ();
1937         }
1938
1939         /* If both inputs and outputs are auto-connected to physical ports,
1940            use the max of input and output offsets to ensure auto-connected
1941            port numbers always match up (e.g. the first audio input and the
1942            first audio output of the route will have the same physical
1943            port number).  Otherwise just use the lowest input or output
1944            offset possible.
1945         */
1946
1947         DEBUG_TRACE (DEBUG::Graph,
1948                      string_compose("Auto-connect: existing in = %1 out = %2\n",
1949                                     existing_inputs, existing_outputs));
1950
1951         const bool in_out_physical =
1952                 (Config->get_input_auto_connect() & AutoConnectPhysical)
1953                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1954                 && connect_inputs;
1955
1956         const ChanCount in_offset = in_out_physical
1957                 ? ChanCount::max(existing_inputs, existing_outputs)
1958                 : existing_inputs;
1959
1960         const ChanCount out_offset = in_out_physical
1961                 ? ChanCount::max(existing_inputs, existing_outputs)
1962                 : existing_outputs;
1963
1964         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1965                 vector<string> physinputs;
1966                 vector<string> physoutputs;
1967
1968                 _engine.get_physical_outputs (*t, physoutputs);
1969                 _engine.get_physical_inputs (*t, physinputs);
1970
1971                 if (!physinputs.empty() && connect_inputs) {
1972                         uint32_t nphysical_in = physinputs.size();
1973
1974                         DEBUG_TRACE (DEBUG::Graph,
1975                                      string_compose("There are %1 physical inputs of type %2\n",
1976                                                     nphysical_in, *t));
1977
1978                         for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1979                                 string port;
1980
1981                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1982                                         DEBUG_TRACE (DEBUG::Graph,
1983                                                      string_compose("Get index %1 + %2 % %3 = %4\n",
1984                                                                     in_offset.get(*t), i, nphysical_in,
1985                                                                     (in_offset.get(*t) + i) % nphysical_in));
1986                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1987                                 }
1988
1989                                 DEBUG_TRACE (DEBUG::Graph,
1990                                              string_compose("Connect route %1 IN to %2\n",
1991                                                             route->name(), port));
1992
1993                                 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1994                                         break;
1995                                 }
1996
1997                                 ChanCount one_added (*t, 1);
1998                                 existing_inputs += one_added;
1999                         }
2000                 }
2001
2002                 if (!physoutputs.empty()) {
2003                         uint32_t nphysical_out = physoutputs.size();
2004                         for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2005                                 string port;
2006
2007                                 if ((*t) == DataType::MIDI || Config->get_output_auto_connect() & AutoConnectPhysical) {
2008                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2009                                 } else if ((*t) == DataType::AUDIO && Config->get_output_auto_connect() & AutoConnectMaster) {
2010                                         /* master bus is audio only */
2011                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2012                                                 port = _master_out->input()->ports().port(*t,
2013                                                                 i % _master_out->input()->n_ports().get(*t))->name();
2014                                         }
2015                                 }
2016
2017                                 DEBUG_TRACE (DEBUG::Graph,
2018                                              string_compose("Connect route %1 OUT to %2\n",
2019                                                             route->name(), port));
2020
2021                                 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2022                                         break;
2023                                 }
2024
2025                                 ChanCount one_added (*t, 1);
2026                                 existing_outputs += one_added;
2027                         }
2028                 }
2029         }
2030 }
2031
2032 /** Caller must not hold process lock
2033  *  @param name_template string to use for the start of the name, or "" to use "Audio".
2034  */
2035 list< boost::shared_ptr<AudioTrack> >
2036 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, 
2037                           uint32_t how_many, string name_template)
2038 {
2039         char track_name[32];
2040         uint32_t track_id = 0;
2041         string port;
2042         RouteList new_routes;
2043         list<boost::shared_ptr<AudioTrack> > ret;
2044
2045         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2046
2047         while (how_many) {
2048                 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2049                         error << "cannot find name for new audio track" << endmsg;
2050                         goto failed;
2051                 }
2052
2053                 boost::shared_ptr<AudioTrack> track;
2054
2055                 try {
2056                         track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2057
2058                         if (track->init ()) {
2059                                 goto failed;
2060                         }
2061
2062                         track->use_new_diskstream();
2063
2064 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2065                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2066 #endif
2067                         {
2068                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2069
2070                                 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2071                                         error << string_compose (
2072                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2073                                                 input_channels, output_channels)
2074                                               << endmsg;
2075                                         goto failed;
2076                                 }
2077
2078                                 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2079                                         error << string_compose (
2080                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2081                                                 input_channels, output_channels)
2082                                               << endmsg;
2083                                         goto failed;
2084                                 }
2085                         }
2086
2087                         if (route_group) {
2088                                 route_group->add (track);
2089                         }
2090
2091                         track->non_realtime_input_change();
2092
2093                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2094                         if (Config->get_remote_model() == UserOrdered) {
2095                                 track->set_remote_control_id (next_control_id());
2096                         }
2097
2098                         new_routes.push_back (track);
2099                         ret.push_back (track);
2100                 }
2101
2102                 catch (failed_constructor &err) {
2103                         error << _("Session: could not create new audio track.") << endmsg;
2104                         goto failed;
2105                 }
2106
2107                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2108
2109                         error << pfe.what() << endmsg;
2110                         goto failed;
2111                 }
2112
2113                 --how_many;
2114         }
2115
2116   failed:
2117         if (!new_routes.empty()) {
2118                 add_routes (new_routes, true, true, true);
2119         }
2120
2121         return ret;
2122 }
2123
2124 /** Caller must not hold process lock.
2125  *  @param name_template string to use for the start of the name, or "" to use "Bus".
2126  */
2127 RouteList
2128 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2129 {
2130         char bus_name[32];
2131         uint32_t bus_id = 0;
2132         string port;
2133         RouteList ret;
2134
2135         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2136         
2137         while (how_many) {
2138                 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2139                         error << "cannot find name for new audio bus" << endmsg;
2140                         goto failure;
2141                 }
2142
2143                 try {
2144                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2145
2146                         if (bus->init ()) {
2147                                 goto failure;
2148                         }
2149
2150 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2151                         // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2152 #endif
2153                         {
2154                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2155
2156                                 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2157                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2158                                                                  input_channels, output_channels)
2159                                               << endmsg;
2160                                         goto failure;
2161                                 }
2162
2163
2164                                 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2165                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2166                                                                  input_channels, output_channels)
2167                                               << endmsg;
2168                                         goto failure;
2169                                 }
2170                         }
2171
2172                         if (route_group) {
2173                                 route_group->add (bus);
2174                         }
2175                         if (Config->get_remote_model() == UserOrdered) {
2176                                 bus->set_remote_control_id (next_control_id());
2177                         }
2178
2179                         bus->add_internal_return ();
2180
2181                         ret.push_back (bus);
2182                         
2183                         ARDOUR::GUIIdle ();
2184                 }
2185
2186
2187                 catch (failed_constructor &err) {
2188                         error << _("Session: could not create new audio route.") << endmsg;
2189                         goto failure;
2190                 }
2191
2192                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2193                         error << pfe.what() << endmsg;
2194                         goto failure;
2195                 }
2196
2197
2198                 --how_many;
2199         }
2200
2201   failure:
2202         if (!ret.empty()) {
2203                 add_routes (ret, false, true, true); // autoconnect outputs only
2204         }
2205
2206         return ret;
2207
2208 }
2209
2210 RouteList
2211 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2212 {
2213         RouteList ret;
2214         uint32_t control_id;
2215         XMLTree tree;
2216         uint32_t number = 0;
2217         const uint32_t being_added = how_many;
2218
2219         if (!tree.read (template_path.c_str())) {
2220                 return ret;
2221         }
2222
2223         XMLNode* node = tree.root();
2224
2225         IO::disable_connecting ();
2226
2227         control_id = next_control_id ();
2228
2229         while (how_many) {
2230
2231                 XMLNode node_copy (*node);
2232
2233                 /* Remove IDs of everything so that new ones are used */
2234                 node_copy.remove_property_recursively (X_("id"));
2235
2236                 try {
2237                         char name[32];
2238
2239                         if (!name_base.empty()) {
2240
2241                                 /* if we're adding more than one routes, force
2242                                  * all the names of the new routes to be
2243                                  * numbered, via the final parameter.
2244                                  */
2245
2246                                 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2247                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2248                                         /*NOTREACHDE*/
2249                                 }
2250
2251                         } else {
2252
2253                                 string const route_name  = node_copy.property(X_("name"))->value ();
2254                         
2255                                 /* generate a new name by adding a number to the end of the template name */
2256                                 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2257                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2258                                         /*NOTREACHED*/
2259                                 }
2260                         }
2261
2262                         /* set this name in the XML description that we are about to use */
2263                         Route::set_name_in_state (node_copy, name);
2264
2265                         /* trim bitslots from listen sends so that new ones are used */
2266                         XMLNodeList children = node_copy.children ();
2267                         for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2268                                 if ((*i)->name() == X_("Processor")) {
2269                                         XMLProperty* role = (*i)->property (X_("role"));
2270                                         if (role && role->value() == X_("Listen")) {
2271                                                 (*i)->remove_property (X_("bitslot"));
2272                                         }
2273                                 }
2274                         }
2275                         
2276                         boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2277
2278                         if (route == 0) {
2279                                 error << _("Session: cannot create track/bus from template description") << endmsg;
2280                                 goto out;
2281                         }
2282
2283                         if (boost::dynamic_pointer_cast<Track>(route)) {
2284                                 /* force input/output change signals so that the new diskstream
2285                                    picks up the configuration of the route. During session
2286                                    loading this normally happens in a different way.
2287                                 */
2288
2289                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2290
2291                                 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2292                                 change.after = route->input()->n_ports();
2293                                 route->input()->changed (change, this);
2294                                 change.after = route->output()->n_ports();
2295                                 route->output()->changed (change, this);
2296                         }
2297
2298                         route->set_remote_control_id (control_id);
2299                         ++control_id;
2300
2301                         ret.push_back (route);
2302                 }
2303
2304                 catch (failed_constructor &err) {
2305                         error << _("Session: could not create new route from template") << endmsg;
2306                         goto out;
2307                 }
2308
2309                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2310                         error << pfe.what() << endmsg;
2311                         goto out;
2312                 }
2313
2314                 --how_many;
2315         }
2316
2317   out:
2318         if (!ret.empty()) {
2319                 add_routes (ret, true, true, true);
2320                 IO::enable_connecting ();
2321         }
2322
2323         return ret;
2324 }
2325
2326 void
2327 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2328 {
2329         try {
2330                 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2331                 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2332
2333         } catch (...) {
2334                 error << _("Adding new tracks/busses failed") << endmsg;
2335         }
2336
2337         graph_reordered ();
2338
2339         update_latency (true);
2340         update_latency (false);
2341                 
2342         set_dirty();
2343         
2344         if (save) {
2345                 save_state (_current_snapshot_name);
2346         }
2347         
2348         RouteAdded (new_routes); /* EMIT SIGNAL */
2349 }
2350
2351 void
2352 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2353 {
2354         ChanCount existing_inputs;
2355         ChanCount existing_outputs;
2356         uint32_t order = next_control_id();
2357
2358         count_existing_track_channels (existing_inputs, existing_outputs);
2359
2360         {
2361                 RCUWriter<RouteList> writer (routes);
2362                 boost::shared_ptr<RouteList> r = writer.get_copy ();
2363                 r->insert (r->end(), new_routes.begin(), new_routes.end());
2364
2365                 /* if there is no control out and we're not in the middle of loading,
2366                    resort the graph here. if there is a control out, we will resort
2367                    toward the end of this method. if we are in the middle of loading,
2368                    we will resort when done.
2369                 */
2370
2371                 if (!_monitor_out && IO::connecting_legal) {
2372                         resort_routes_using (r);
2373                 }
2374         }
2375
2376         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2377
2378                 boost::weak_ptr<Route> wpr (*x);
2379                 boost::shared_ptr<Route> r (*x);
2380
2381                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2382                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2383                 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2384                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2385                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2386                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2387
2388                 if (r->is_master()) {
2389                         _master_out = r;
2390                 }
2391
2392                 if (r->is_monitor()) {
2393                         _monitor_out = r;
2394                 }
2395
2396                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2397                 if (tr) {
2398                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2399                         track_playlist_changed (boost::weak_ptr<Track> (tr));
2400                         tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2401
2402                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2403                         if (mt) {
2404                                 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2405                                 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2406                         }
2407                 }
2408
2409
2410                 if (input_auto_connect || output_auto_connect) {
2411                         auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2412                 }
2413
2414                 /* order keys are a GUI responsibility but we need to set up
2415                    reasonable defaults because they also affect the remote control
2416                    ID in most situations.
2417                 */
2418
2419                 if (!r->has_order_key (EditorSort)) {
2420                         if (r->is_auditioner()) {
2421                                 /* use an arbitrarily high value */
2422                                 r->set_order_key (EditorSort, UINT_MAX);
2423                                 r->set_order_key (MixerSort, UINT_MAX);
2424                         } else {
2425                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2426                                 r->set_order_key (EditorSort, order);
2427                                 r->set_order_key (MixerSort, order);
2428                                 order++;
2429                         }
2430                 }
2431
2432                 ARDOUR::GUIIdle ();
2433         }
2434
2435         if (_monitor_out && IO::connecting_legal) {
2436                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());         
2437                 
2438                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2439                         if ((*x)->is_monitor()) {
2440                                 /* relax */
2441                         } else if ((*x)->is_master()) {
2442                                         /* relax */
2443                         } else {
2444                                 (*x)->enable_monitor_send ();
2445                         }
2446                 }
2447         }
2448 }
2449
2450 void
2451 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2452 {
2453         boost::shared_ptr<RouteList> r = routes.reader ();
2454         boost::shared_ptr<Send> s;
2455
2456         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2457                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2458                         s->amp()->gain_control()->set_value (0.0);
2459                 }
2460         }
2461 }
2462
2463 void
2464 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2465 {
2466         boost::shared_ptr<RouteList> r = routes.reader ();
2467         boost::shared_ptr<Send> s;
2468
2469         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2470                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2471                         s->amp()->gain_control()->set_value (1.0);
2472                 }
2473         }
2474 }
2475
2476 void
2477 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2478 {
2479         boost::shared_ptr<RouteList> r = routes.reader ();
2480         boost::shared_ptr<Send> s;
2481
2482         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2483                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2484                         s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2485                 }
2486         }
2487 }
2488
2489 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2490 void
2491 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2492 {
2493         boost::shared_ptr<RouteList> r = routes.reader ();
2494         boost::shared_ptr<RouteList> t (new RouteList);
2495
2496         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2497                 /* no MIDI sends because there are no MIDI busses yet */
2498                 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2499                         t->push_back (*i);
2500                 }
2501         }
2502
2503         add_internal_sends (dest, p, t);
2504 }
2505
2506 void
2507 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2508 {
2509         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2510                 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2511         }
2512 }
2513
2514 void
2515 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2516 {
2517         add_internal_send (dest, sender->before_processor_for_index (index), sender);
2518 }
2519
2520 void
2521 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2522 {
2523         if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2524                 return;
2525         }
2526
2527         if (!dest->internal_return()) {
2528                 dest->add_internal_return ();
2529         }
2530
2531         sender->add_aux_send (dest, before);
2532
2533         graph_reordered ();
2534 }
2535
2536 void
2537 Session::remove_route (boost::shared_ptr<Route> route)
2538 {
2539         if (route == _master_out) {
2540                 return;
2541         }
2542
2543         route->set_solo (false, this);
2544
2545         {
2546                 RCUWriter<RouteList> writer (routes);
2547                 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2548
2549                 rs->remove (route);
2550
2551                 /* deleting the master out seems like a dumb
2552                    idea, but its more of a UI policy issue
2553                    than our concern.
2554                 */
2555
2556                 if (route == _master_out) {
2557                         _master_out = boost::shared_ptr<Route> ();
2558                 }
2559
2560                 if (route == _monitor_out) {
2561                         _monitor_out.reset ();
2562                 }
2563
2564                 /* writer goes out of scope, forces route list update */
2565         }
2566
2567         update_route_solo_state ();
2568
2569         // We need to disconnect the route's inputs and outputs
2570
2571         route->input()->disconnect (0);
2572         route->output()->disconnect (0);
2573
2574         /* if the route had internal sends sending to it, remove them */
2575         if (route->internal_return()) {
2576
2577                 boost::shared_ptr<RouteList> r = routes.reader ();
2578                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2579                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2580                         if (s) {
2581                                 (*i)->remove_processor (s);
2582                         }
2583                 }
2584         }
2585
2586         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2587         if (mt && mt->step_editing()) {
2588                 if (_step_editors > 0) {
2589                         _step_editors--;
2590                 }
2591         }
2592
2593         update_latency_compensation ();
2594         set_dirty();
2595
2596         /* Re-sort routes to remove the graph's current references to the one that is
2597          * going away, then flush old references out of the graph.
2598          */
2599
2600         resort_routes ();
2601         if (_process_graph) {
2602                 _process_graph->clear_other_chain ();
2603         }
2604
2605         /* get rid of it from the dead wood collection in the route list manager */
2606
2607         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2608
2609         routes.flush ();
2610
2611         /* try to cause everyone to drop their references */
2612
2613         route->drop_references ();
2614
2615         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2616
2617         /* save the new state of the world */
2618
2619         if (save_state (_current_snapshot_name)) {
2620                 save_history (_current_snapshot_name);
2621         }
2622 }
2623
2624 void
2625 Session::route_mute_changed (void* /*src*/)
2626 {
2627         set_dirty ();
2628 }
2629
2630 void
2631 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2632 {
2633         boost::shared_ptr<Route> route = wpr.lock();
2634         if (!route) {
2635                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2636                 return;
2637         }
2638
2639         if (route->listening_via_monitor ()) {
2640
2641                 if (Config->get_exclusive_solo()) {
2642                         /* new listen: disable all other listen */
2643                         boost::shared_ptr<RouteList> r = routes.reader ();
2644                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2645                                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2646                                         continue;
2647                                 }
2648                                 (*i)->set_listen (false, this);
2649                         }
2650                 }
2651
2652                 _listen_cnt++;
2653
2654         } else if (_listen_cnt > 0) {
2655
2656                 _listen_cnt--;
2657         }
2658
2659         update_route_solo_state ();
2660 }
2661 void
2662 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2663 {
2664         boost::shared_ptr<Route> route = wpr.lock ();
2665
2666         if (!route) {
2667                 /* should not happen */
2668                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2669                 return;
2670         }
2671
2672         bool send_changed = false;
2673
2674         if (route->solo_isolated()) {
2675                 if (_solo_isolated_cnt == 0) {
2676                         send_changed = true;
2677                 }
2678                 _solo_isolated_cnt++;
2679         } else if (_solo_isolated_cnt > 0) {
2680                 _solo_isolated_cnt--;
2681                 if (_solo_isolated_cnt == 0) {
2682                         send_changed = true;
2683                 }
2684         }
2685
2686         if (send_changed) {
2687                 IsolatedChanged (); /* EMIT SIGNAL */
2688         }
2689 }
2690
2691 void
2692 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2693 {
2694         DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2695
2696         if (!self_solo_change) {
2697                 // session doesn't care about changes to soloed-by-others
2698                 return;
2699         }
2700
2701         if (solo_update_disabled) {
2702                 // We know already
2703                 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2704                 return;
2705         }
2706
2707         boost::shared_ptr<Route> route = wpr.lock ();
2708         assert (route);
2709
2710         boost::shared_ptr<RouteList> r = routes.reader ();
2711         int32_t delta;
2712
2713         if (route->self_soloed()) {
2714                 delta = 1;
2715         } else {
2716                 delta = -1;
2717         }
2718
2719         RouteGroup* rg = route->route_group ();
2720         bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2721
2722         if (delta == 1 && Config->get_exclusive_solo()) {
2723                 
2724                 /* new solo: disable all other solos, but not the group if its solo-enabled */
2725
2726                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2727                         if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2728                             (leave_group_alone && ((*i)->route_group() == rg))) {
2729                                 continue;
2730                         }
2731                         (*i)->set_solo (false, this);
2732                 }
2733         }
2734
2735         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2736
2737         solo_update_disabled = true;
2738
2739         RouteList uninvolved;
2740
2741         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2742
2743         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2744                 bool via_sends_only;
2745                 bool in_signal_flow;
2746
2747                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2748                     (leave_group_alone && ((*i)->route_group() == rg))) {
2749                         continue;
2750                 }
2751
2752                 in_signal_flow = false;
2753
2754                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2755                 
2756                 if ((*i)->feeds (route, &via_sends_only)) {
2757                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2758                         if (!via_sends_only) {
2759                                 if (!route->soloed_by_others_upstream()) {
2760                                         (*i)->mod_solo_by_others_downstream (delta);
2761                                 }
2762                         } else {
2763                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2764                         }
2765                         in_signal_flow = true;
2766                 } else {
2767                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2768                 }
2769                 
2770                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2771
2772                 if (route->feeds (*i, &via_sends_only)) {
2773                         /* propagate solo upstream only if routing other than
2774                            sends is involved, but do consider the other route
2775                            (*i) to be part of the signal flow even if only
2776                            sends are involved.
2777                         */
2778                         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2779                                                                   route->name(),
2780                                                                   (*i)->name(),
2781                                                                   via_sends_only,
2782                                                                   route->soloed_by_others_downstream(),
2783                                                                   route->soloed_by_others_upstream()));
2784                         if (!via_sends_only) {
2785                                 if (!route->soloed_by_others_downstream()) {
2786                                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2787                                         (*i)->mod_solo_by_others_upstream (delta);
2788                                 } else {
2789                                         DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2790                                 }
2791                         } else {
2792                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2793                         }
2794                         in_signal_flow = true;
2795                 } else {
2796                         DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2797                 }
2798
2799                 if (!in_signal_flow) {
2800                         uninvolved.push_back (*i);
2801                 }
2802         }
2803
2804         solo_update_disabled = false;
2805         DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2806
2807         update_route_solo_state (r);
2808
2809         /* now notify that the mute state of the routes not involved in the signal
2810            pathway of the just-solo-changed route may have altered.
2811         */
2812
2813         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2814                 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2815                 (*i)->mute_changed (this);
2816         }
2817
2818         SoloChanged (); /* EMIT SIGNAL */
2819         set_dirty();
2820 }
2821
2822 void
2823 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2824 {
2825         /* now figure out if anything that matters is soloed (or is "listening")*/
2826
2827         bool something_soloed = false;
2828         uint32_t listeners = 0;
2829         uint32_t isolated = 0;
2830
2831         if (!r) {
2832                 r = routes.reader();
2833         }
2834
2835         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2836                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2837                         something_soloed = true;
2838                 }
2839
2840                 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2841                         if (Config->get_solo_control_is_listen_control()) {
2842                                 listeners++;
2843                         } else {
2844                                 (*i)->set_listen (false, this);
2845                         }
2846                 }
2847
2848                 if ((*i)->solo_isolated()) {
2849                         isolated++;
2850                 }
2851         }
2852
2853         if (something_soloed != _non_soloed_outs_muted) {
2854                 _non_soloed_outs_muted = something_soloed;
2855                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2856         }
2857
2858         _listen_cnt = listeners;
2859
2860         if (isolated != _solo_isolated_cnt) {
2861                 _solo_isolated_cnt = isolated;
2862                 IsolatedChanged (); /* EMIT SIGNAL */
2863         }
2864
2865         DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2866                                                   something_soloed, listeners, isolated));
2867 }
2868
2869 boost::shared_ptr<RouteList>
2870 Session::get_routes_with_internal_returns() const
2871 {
2872         boost::shared_ptr<RouteList> r = routes.reader ();
2873         boost::shared_ptr<RouteList> rl (new RouteList);
2874
2875         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2876                 if ((*i)->internal_return ()) {
2877                         rl->push_back (*i);
2878                 }
2879         }
2880         return rl;
2881 }
2882
2883 bool
2884 Session::io_name_is_legal (const std::string& name)
2885 {
2886         boost::shared_ptr<RouteList> r = routes.reader ();
2887
2888         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2889                 if ((*i)->name() == name) {
2890                         return false;
2891                 }
2892
2893                 if ((*i)->has_io_processor_named (name)) {
2894                         return false;
2895                 }
2896         }
2897
2898         return true;
2899 }
2900
2901 void
2902 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2903 {
2904         RouteList rl2;
2905         vector<string> connections;
2906
2907         /* if we are passed only a single route and we're not told to turn
2908          * others off, then just do the simple thing.
2909          */
2910
2911         if (flip_others == false && rl->size() == 1) {
2912                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2913                 if (mt) {
2914                         mt->set_input_active (onoff);
2915                         return;
2916                 }
2917         }
2918
2919         for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2920
2921                 PortSet& ps ((*rt)->input()->ports());
2922                 
2923                 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2924                         p->get_connections (connections);
2925                 }
2926                 
2927                 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2928                         routes_using_input_from (*s, rl2);
2929                 }
2930                 
2931                 /* scan all relevant routes to see if others are on or off */
2932                 
2933                 bool others_are_already_on = false;
2934                 
2935                 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2936
2937                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2938
2939                         if (!mt) {
2940                                 continue;
2941                         }
2942
2943                         if ((*r) != (*rt)) {
2944                                 if (mt->input_active()) {
2945                                         others_are_already_on = true;
2946                                 }
2947                         } else {
2948                                 /* this one needs changing */
2949                                 mt->set_input_active (onoff);
2950                         }
2951                 }
2952                 
2953                 if (flip_others) {
2954
2955                         /* globally reverse other routes */
2956                         
2957                         for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2958                                 if ((*r) != (*rt)) {
2959                                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2960                                         if (mt) {
2961                                                 mt->set_input_active (!others_are_already_on);
2962                                         }
2963                                 }
2964                         }
2965                 }
2966         }
2967 }
2968
2969 void
2970 Session::routes_using_input_from (const string& str, RouteList& rl)
2971 {
2972         boost::shared_ptr<RouteList> r = routes.reader();
2973
2974         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2975                 if ((*i)->input()->connected_to (str)) {
2976                         rl.push_back (*i);
2977                 }
2978         }
2979 }
2980
2981 boost::shared_ptr<Route>
2982 Session::route_by_name (string name)
2983 {
2984         boost::shared_ptr<RouteList> r = routes.reader ();
2985
2986         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2987                 if ((*i)->name() == name) {
2988                         return *i;
2989                 }
2990         }
2991
2992         return boost::shared_ptr<Route> ((Route*) 0);
2993 }
2994
2995 boost::shared_ptr<Route>
2996 Session::route_by_id (PBD::ID id)
2997 {
2998         boost::shared_ptr<RouteList> r = routes.reader ();
2999
3000         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3001                 if ((*i)->id() == id) {
3002                         return *i;
3003                 }
3004         }
3005
3006         return boost::shared_ptr<Route> ((Route*) 0);
3007 }
3008
3009 boost::shared_ptr<Track>
3010 Session::track_by_diskstream_id (PBD::ID id)
3011 {
3012         boost::shared_ptr<RouteList> r = routes.reader ();
3013
3014         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3015                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3016                 if (t && t->using_diskstream_id (id)) {
3017                         return t;
3018                 }
3019         }
3020
3021         return boost::shared_ptr<Track> ();
3022 }
3023
3024 boost::shared_ptr<Route>
3025 Session::route_by_remote_id (uint32_t id)
3026 {
3027         boost::shared_ptr<RouteList> r = routes.reader ();
3028
3029         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3030                 if ((*i)->remote_control_id() == id) {
3031                         return *i;
3032                 }
3033         }
3034
3035         return boost::shared_ptr<Route> ((Route*) 0);
3036 }
3037
3038 void
3039 Session::playlist_region_added (boost::weak_ptr<Region> w)
3040 {
3041         boost::shared_ptr<Region> r = w.lock ();
3042         if (!r) {
3043                 return;
3044         }
3045
3046         /* These are the operations that are currently in progress... */
3047         list<GQuark> curr = _current_trans_quarks;
3048         curr.sort ();
3049
3050         /* ...and these are the operations during which we want to update
3051            the session range location markers.
3052         */
3053         list<GQuark> ops;
3054         ops.push_back (Operations::capture);
3055         ops.push_back (Operations::paste);
3056         ops.push_back (Operations::duplicate_region);
3057         ops.push_back (Operations::insert_file);
3058         ops.push_back (Operations::insert_region);
3059         ops.push_back (Operations::drag_region_brush);
3060         ops.push_back (Operations::region_drag);
3061         ops.push_back (Operations::selection_grab);
3062         ops.push_back (Operations::region_fill);
3063         ops.push_back (Operations::fill_selection);
3064         ops.push_back (Operations::create_region);
3065         ops.push_back (Operations::region_copy);
3066         ops.push_back (Operations::fixed_time_region_copy);
3067         ops.sort ();
3068
3069         /* See if any of the current operations match the ones that we want */
3070         list<GQuark> in;
3071         set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3072
3073         /* If so, update the session range markers */
3074         if (!in.empty ()) {
3075                 maybe_update_session_range (r->position (), r->last_frame ());
3076         }
3077 }
3078
3079 /** Update the session range markers if a is before the current start or
3080  *  b is after the current end.
3081  */
3082 void
3083 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3084 {
3085         if (_state_of_the_state & Loading) {
3086                 return;
3087         }
3088
3089         if (_session_range_location == 0) {
3090
3091                 add_session_range_location (a, b);
3092
3093         } else {
3094
3095                 if (a < _session_range_location->start()) {
3096                         _session_range_location->set_start (a);
3097                 }
3098
3099                 if (b > _session_range_location->end()) {
3100                         _session_range_location->set_end (b);
3101                 }
3102         }
3103 }
3104
3105 void
3106 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3107 {
3108         for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3109                 maybe_update_session_range (i->to, i->to + i->length);
3110         }
3111 }
3112
3113 void
3114 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3115 {
3116         for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3117                 maybe_update_session_range (i->from, i->to);
3118         }
3119 }
3120
3121 /* Region management */
3122
3123 boost::shared_ptr<Region>
3124 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3125 {
3126         const RegionFactory::RegionMap& regions (RegionFactory::regions());
3127         RegionFactory::RegionMap::const_iterator i;
3128         boost::shared_ptr<Region> region;
3129
3130         Glib::Threads::Mutex::Lock lm (region_lock);
3131
3132         for (i = regions.begin(); i != regions.end(); ++i) {
3133
3134                 region = i->second;
3135
3136                 if (region->whole_file()) {
3137
3138                         if (child->source_equivalent (region)) {
3139                                 return region;
3140                         }
3141                 }
3142         }
3143
3144         return boost::shared_ptr<Region> ();
3145 }
3146
3147 int
3148 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3149 {
3150         set<boost::shared_ptr<Region> > relevant_regions;
3151
3152         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3153                 RegionFactory::get_regions_using_source (*s, relevant_regions);
3154         }
3155
3156         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3157                 set<boost::shared_ptr<Region> >::iterator tmp;
3158
3159                 tmp = r;
3160                 ++tmp;
3161
3162                 playlists->destroy_region (*r);
3163                 RegionFactory::map_remove (*r);
3164
3165                 (*r)->drop_sources ();
3166                 (*r)->drop_references ();
3167
3168                 relevant_regions.erase (r);
3169
3170                 r = tmp;
3171         }
3172
3173         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3174
3175                 {
3176                         Glib::Threads::Mutex::Lock ls (source_lock);
3177                         /* remove from the main source list */
3178                         sources.erase ((*s)->id());
3179                 }
3180
3181                 (*s)->mark_for_remove ();
3182                 (*s)->drop_references ();
3183
3184                 s = srcs.erase (s);
3185         }
3186
3187         return 0;
3188 }
3189
3190 int
3191 Session::remove_last_capture ()
3192 {
3193         list<boost::shared_ptr<Source> > srcs;
3194
3195         boost::shared_ptr<RouteList> rl = routes.reader ();
3196         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3197                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3198                 if (!tr) {
3199                         continue;
3200                 }
3201
3202                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3203
3204                 if (!l.empty()) {
3205                         srcs.insert (srcs.end(), l.begin(), l.end());
3206                         l.clear ();
3207                 }
3208         }
3209
3210         destroy_sources (srcs);
3211
3212         save_state (_current_snapshot_name);
3213
3214         return 0;
3215 }
3216
3217 /* Source Management */
3218
3219 void
3220 Session::add_source (boost::shared_ptr<Source> source)
3221 {
3222         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3223         pair<SourceMap::iterator,bool> result;
3224
3225         entry.first = source->id();
3226         entry.second = source;
3227
3228         {
3229                 Glib::Threads::Mutex::Lock lm (source_lock);
3230                 result = sources.insert (entry);
3231         }
3232
3233         if (result.second) {
3234
3235                 /* yay, new source */
3236
3237                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3238                 
3239                 if (fs) {
3240                         if (!fs->within_session()) {
3241                                 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3242                         }
3243                 }
3244                 
3245                 set_dirty();
3246
3247                 boost::shared_ptr<AudioFileSource> afs;
3248
3249                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3250                         if (Config->get_auto_analyse_audio()) {
3251                                 Analyser::queue_source_for_analysis (source, false);
3252                         }
3253                 }
3254
3255                 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3256         }
3257 }
3258
3259 void
3260 Session::remove_source (boost::weak_ptr<Source> src)
3261 {
3262         if (_state_of_the_state & Deletion) {
3263                 return;
3264         }
3265
3266         SourceMap::iterator i;
3267         boost::shared_ptr<Source> source = src.lock();
3268
3269         if (!source) {
3270                 return;
3271         }
3272
3273         {
3274                 Glib::Threads::Mutex::Lock lm (source_lock);
3275
3276                 if ((i = sources.find (source->id())) != sources.end()) {
3277                         sources.erase (i);
3278                 }
3279         }
3280
3281         if (!(_state_of_the_state & InCleanup)) {
3282
3283                 /* save state so we don't end up with a session file
3284                    referring to non-existent sources.
3285                 */
3286
3287                 save_state (_current_snapshot_name);
3288         }
3289 }
3290
3291 boost::shared_ptr<Source>
3292 Session::source_by_id (const PBD::ID& id)
3293 {
3294         Glib::Threads::Mutex::Lock lm (source_lock);
3295         SourceMap::iterator i;
3296         boost::shared_ptr<Source> source;
3297
3298         if ((i = sources.find (id)) != sources.end()) {
3299                 source = i->second;
3300         }
3301
3302         return source;
3303 }
3304
3305 boost::shared_ptr<Source>
3306 Session::source_by_path_and_channel (const string& path, uint16_t chn)
3307 {
3308         Glib::Threads::Mutex::Lock lm (source_lock);
3309
3310         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3311                 boost::shared_ptr<AudioFileSource> afs
3312                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3313
3314                 if (afs && afs->path() == path && chn == afs->channel()) {
3315                         return afs;
3316                 }
3317         }
3318         return boost::shared_ptr<Source>();
3319 }
3320
3321 uint32_t
3322 Session::count_sources_by_origin (const string& path)
3323 {
3324         uint32_t cnt = 0;
3325         Glib::Threads::Mutex::Lock lm (source_lock);
3326
3327         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3328                 boost::shared_ptr<FileSource> fs
3329                         = boost::dynamic_pointer_cast<FileSource>(i->second);
3330
3331                 if (fs && fs->origin() == path) {
3332                         ++cnt;
3333                 }
3334         }
3335
3336         return cnt;
3337 }
3338
3339
3340 string
3341 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3342 {
3343         string look_for;
3344         string old_basename = PBD::basename_nosuffix (oldname);
3345         string new_legalized = legalize_for_path (newname);
3346
3347         /* note: we know (or assume) the old path is already valid */
3348
3349         if (destructive) {
3350
3351                 /* destructive file sources have a name of the form:
3352
3353                     /path/to/Tnnnn-NAME(%[LR])?.wav
3354
3355                     the task here is to replace NAME with the new name.
3356                 */
3357
3358                 string dir;
3359                 string prefix;
3360                 string::size_type dash;
3361
3362                 dir = Glib::path_get_dirname (path);
3363                 path = Glib::path_get_basename (path);
3364
3365                 /* '-' is not a legal character for the NAME part of the path */
3366
3367                 if ((dash = path.find_last_of ('-')) == string::npos) {
3368                         return "";
3369                 }
3370
3371                 prefix = path.substr (0, dash);
3372
3373                 path += prefix;
3374                 path += '-';
3375                 path += new_legalized;
3376                 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3377                 path = Glib::build_filename (dir, path);
3378
3379         } else {
3380
3381                 /* non-destructive file sources have a name of the form:
3382
3383                     /path/to/NAME-nnnnn(%[LR])?.ext
3384
3385                     the task here is to replace NAME with the new name.
3386                 */
3387
3388                 string dir;
3389                 string suffix;
3390                 string::size_type dash;
3391                 string::size_type postfix;
3392
3393                 dir = Glib::path_get_dirname (path);
3394                 path = Glib::path_get_basename (path);
3395
3396                 /* '-' is not a legal character for the NAME part of the path */
3397
3398                 if ((dash = path.find_last_of ('-')) == string::npos) {
3399                         return "";
3400                 }
3401
3402                 suffix = path.substr (dash+1);
3403
3404                 // Suffix is now everything after the dash. Now we need to eliminate
3405                 // the nnnnn part, which is done by either finding a '%' or a '.'
3406
3407                 postfix = suffix.find_last_of ("%");
3408                 if (postfix == string::npos) {
3409                         postfix = suffix.find_last_of ('.');
3410                 }
3411
3412                 if (postfix != string::npos) {
3413                         suffix = suffix.substr (postfix);
3414                 } else {
3415                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3416                         return "";
3417                 }
3418
3419                 const uint32_t limit = 10000;
3420                 char buf[PATH_MAX+1];
3421
3422                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3423
3424                         snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
3425
3426                         if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
3427                                 path = Glib::build_filename (dir, buf);
3428                                 break;
3429                         }
3430
3431                         path = "";
3432                 }
3433
3434                 if (path.empty()) {
3435                         fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
3436                                                  newname) << endl;
3437                         /*NOTREACHED*/
3438                 }
3439         }
3440
3441         return path;
3442 }
3443
3444 /** Return the full path (in some session directory) for a new within-session source.
3445  * \a name must be a session-unique name that does not contain slashes
3446  *         (e.g. as returned by new_*_source_name)
3447  */
3448 string
3449 Session::new_source_path_from_name (DataType type, const string& name)
3450 {
3451         assert(name.find("/") == string::npos);
3452
3453         SessionDirectory sdir(get_best_session_directory_for_new_source());
3454
3455         std::string p;
3456         if (type == DataType::AUDIO) {
3457                 p = sdir.sound_path();
3458         } else if (type == DataType::MIDI) {
3459                 p = sdir.midi_path();
3460         } else {
3461                 error << "Unknown source type, unable to create file path" << endmsg;
3462                 return "";
3463         }
3464
3465         return Glib::build_filename (p, name);
3466 }
3467
3468 string
3469 Session::peak_path (string base) const
3470 {
3471         return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3472 }
3473
3474 /** Return a unique name based on \a base for a new internal audio source */
3475 string
3476 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3477 {
3478         uint32_t cnt;
3479         char buf[PATH_MAX+1];
3480         const uint32_t limit = 10000;
3481         string legalized;
3482         string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3483
3484         buf[0] = '\0';
3485         legalized = legalize_for_path (base);
3486
3487         // Find a "version" of the base name that doesn't exist in any of the possible directories.
3488         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3489
3490                 vector<space_and_path>::iterator i;
3491                 uint32_t existing = 0;
3492
3493                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3494
3495                         if (destructive) {
3496
3497                                 if (nchan < 2) {
3498                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
3499                                                   cnt, legalized.c_str(), ext.c_str());
3500                                 } else if (nchan == 2) {
3501                                         if (chan == 0) {
3502                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3503                                                           cnt, legalized.c_str(), ext.c_str());
3504                                         } else {
3505                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3506                                                           cnt, legalized.c_str(), ext.c_str());
3507                                         }
3508                                 } else if (nchan < 26) {
3509                                         snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3510                                                   cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3511                                 } else {
3512                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
3513                                                   cnt, legalized.c_str(), ext.c_str());
3514                                 }
3515
3516                         } else {
3517
3518                                 if (nchan < 2) {
3519                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3520                                 } else if (nchan == 2) {
3521                                         if (chan == 0) {
3522                                                 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3523                                         } else {
3524                                                 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3525                                         }
3526                                 } else if (nchan < 26) {
3527                                         snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3528                                 } else {
3529                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3530                                 }
3531                         }
3532
3533                         SessionDirectory sdir((*i).path);
3534
3535                         string spath = sdir.sound_path();
3536
3537                         /* note that we search *without* the extension so that
3538                            we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3539                            in the event that this new name is required for
3540                            a file format change.
3541                         */
3542
3543                         if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3544                                 existing++;
3545                                 break;
3546                         }
3547                 }
3548
3549                 if (existing == 0) {
3550                         break;
3551                 }
3552
3553                 if (cnt > limit) {
3554                         error << string_compose(
3555                                         _("There are already %1 recordings for %2, which I consider too many."),
3556                                         limit, base) << endmsg;
3557                         destroy ();
3558                         throw failed_constructor();
3559                 }
3560         }
3561
3562         return Glib::path_get_basename (buf);
3563 }
3564
3565 /** Create a new within-session audio source */
3566 boost::shared_ptr<AudioFileSource>
3567 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3568 {
3569         const string name    = new_audio_source_name (n, n_chans, chan, destructive);
3570         const string path    = new_source_path_from_name(DataType::AUDIO, name);
3571
3572         return boost::dynamic_pointer_cast<AudioFileSource> (
3573                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3574 }
3575
3576 /** Return a unique name based on \a base for a new internal MIDI source */
3577 string
3578 Session::new_midi_source_name (const string& base)
3579 {
3580         uint32_t cnt;
3581         char buf[PATH_MAX+1];
3582         const uint32_t limit = 10000;
3583         string legalized;
3584
3585         buf[0] = '\0';
3586         legalized = legalize_for_path (base);
3587
3588         // Find a "version" of the file name that doesn't exist in any of the possible directories.
3589         for (cnt = 1; cnt <= limit; ++cnt) {
3590
3591                 vector<space_and_path>::iterator i;
3592                 uint32_t existing = 0;
3593
3594                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3595
3596                         SessionDirectory sdir((*i).path);
3597
3598                         std::string p = Glib::build_filename (sdir.midi_path(), legalized);
3599
3600                         snprintf (buf, sizeof(buf), "%s-%u.mid", p.c_str(), cnt);
3601
3602                         if (Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
3603                                 existing++;
3604                         }
3605                 }
3606
3607                 if (existing == 0) {
3608                         break;
3609                 }
3610
3611                 if (cnt > limit) {
3612                         error << string_compose(
3613                                         _("There are already %1 recordings for %2, which I consider too many."),
3614                                         limit, base) << endmsg;
3615                         destroy ();
3616                         throw failed_constructor();
3617                 }
3618         }
3619
3620         return Glib::path_get_basename(buf);
3621 }
3622
3623
3624 /** Create a new within-session MIDI source */
3625 boost::shared_ptr<MidiSource>
3626 Session::create_midi_source_for_session (Track* track, string const & n)
3627 {
3628         /* try to use the existing write source for the track, to keep numbering sane
3629          */
3630
3631         if (track) {
3632                 /*MidiTrack* mt = dynamic_cast<Track*> (track);
3633                   assert (mt);
3634                 */
3635
3636                 list<boost::shared_ptr<Source> > l = track->steal_write_sources ();
3637
3638                 if (!l.empty()) {
3639                         assert (boost::dynamic_pointer_cast<MidiSource> (l.front()));
3640                         return boost::dynamic_pointer_cast<MidiSource> (l.front());
3641                 }
3642         }
3643
3644         const string name = new_midi_source_name (n);
3645         const string path = new_source_path_from_name (DataType::MIDI, name);
3646
3647         return boost::dynamic_pointer_cast<SMFSource> (
3648                 SourceFactory::createWritable (
3649                         DataType::MIDI, *this, path, false, frame_rate()));
3650 }
3651
3652
3653 void
3654 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3655 {
3656         if (playlist->hidden()) {
3657                 return;
3658         }
3659
3660         playlists->add (playlist);
3661
3662         if (unused) {
3663                 playlist->release();
3664         }
3665
3666         set_dirty();
3667 }
3668
3669 void
3670 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3671 {
3672         if (_state_of_the_state & Deletion) {
3673                 return;
3674         }
3675
3676         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3677
3678         if (!playlist) {
3679                 return;
3680         }
3681
3682         playlists->remove (playlist);
3683
3684         set_dirty();
3685 }
3686
3687 void
3688 Session::set_audition (boost::shared_ptr<Region> r)
3689 {
3690         pending_audition_region = r;
3691         add_post_transport_work (PostTransportAudition);
3692         _butler->schedule_transport_work ();
3693 }
3694
3695 void
3696 Session::audition_playlist ()
3697 {
3698         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3699         ev->region.reset ();
3700         queue_event (ev);
3701 }
3702
3703 void
3704 Session::non_realtime_set_audition ()
3705 {
3706         assert (pending_audition_region);
3707         auditioner->audition_region (pending_audition_region);
3708         pending_audition_region.reset ();
3709         AuditionActive (true); /* EMIT SIGNAL */
3710 }
3711
3712 void
3713 Session::audition_region (boost::shared_ptr<Region> r)
3714 {
3715         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3716         ev->region = r;
3717         queue_event (ev);
3718 }
3719
3720 void
3721 Session::cancel_audition ()
3722 {
3723         if (auditioner->auditioning()) {
3724                 auditioner->cancel_audition ();
3725                 AuditionActive (false); /* EMIT SIGNAL */
3726         }
3727 }
3728
3729 bool
3730 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3731 {
3732         if (a->is_monitor()) {
3733                 return true;
3734         }
3735         if (b->is_monitor()) {
3736                 return false;
3737         }
3738         return a->order_key (MixerSort) < b->order_key (MixerSort);
3739 }
3740
3741 bool
3742 Session::is_auditioning () const
3743 {
3744         /* can be called before we have an auditioner object */
3745         if (auditioner) {
3746                 return auditioner->auditioning();
3747         } else {
3748                 return false;
3749         }
3750 }
3751
3752 void
3753 Session::graph_reordered ()
3754 {
3755         /* don't do this stuff if we are setting up connections
3756            from a set_state() call or creating new tracks. Ditto for deletion.
3757         */
3758
3759         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3760                 return;
3761         }
3762
3763         /* every track/bus asked for this to be handled but it was deferred because
3764            we were connecting. do it now.
3765         */
3766
3767         request_input_change_handling ();
3768
3769         resort_routes ();
3770
3771         /* force all diskstreams to update their capture offset values to
3772            reflect any changes in latencies within the graph.
3773         */
3774
3775         boost::shared_ptr<RouteList> rl = routes.reader ();
3776         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3777                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3778                 if (tr) {
3779                         tr->set_capture_offset ();
3780                 }
3781         }
3782 }
3783
3784 /** @return Number of frames that there is disk space available to write,
3785  *  if known.
3786  */
3787 boost::optional<framecnt_t>
3788 Session::available_capture_duration ()
3789 {
3790         Glib::Threads::Mutex::Lock lm (space_lock);
3791
3792         if (_total_free_4k_blocks_uncertain) {
3793                 return boost::optional<framecnt_t> ();
3794         }
3795         
3796         float sample_bytes_on_disk = 4.0; // keep gcc happy
3797
3798         switch (config.get_native_file_data_format()) {
3799         case FormatFloat:
3800                 sample_bytes_on_disk = 4.0;
3801                 break;
3802
3803         case FormatInt24:
3804                 sample_bytes_on_disk = 3.0;
3805                 break;
3806
3807         case FormatInt16:
3808                 sample_bytes_on_disk = 2.0;
3809                 break;
3810
3811         default:
3812                 /* impossible, but keep some gcc versions happy */
3813                 fatal << string_compose (_("programming error: %1"),
3814                                          X_("illegal native file data format"))
3815                       << endmsg;
3816                 /*NOTREACHED*/
3817         }
3818
3819         double scale = 4096.0 / sample_bytes_on_disk;
3820
3821         if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3822                 return max_framecnt;
3823         }
3824
3825         return (framecnt_t) floor (_total_free_4k_blocks * scale);
3826 }
3827
3828 void
3829 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3830 {
3831         {
3832                 RCUWriter<BundleList> writer (_bundles);
3833                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3834                 b->push_back (bundle);
3835         }
3836
3837         BundleAdded (bundle); /* EMIT SIGNAL */
3838
3839         set_dirty();
3840 }
3841
3842 void
3843 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3844 {
3845         bool removed = false;
3846
3847         {
3848                 RCUWriter<BundleList> writer (_bundles);
3849                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3850                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3851
3852                 if (i != b->end()) {
3853                         b->erase (i);
3854                         removed = true;
3855                 }
3856         }
3857
3858         if (removed) {
3859                  BundleRemoved (bundle); /* EMIT SIGNAL */
3860         }
3861
3862         set_dirty();
3863 }
3864
3865 boost::shared_ptr<Bundle>
3866 Session::bundle_by_name (string name) const
3867 {
3868         boost::shared_ptr<BundleList> b = _bundles.reader ();
3869
3870         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3871                 if ((*i)->name() == name) {
3872                         return* i;
3873                 }
3874         }
3875
3876         return boost::shared_ptr<Bundle> ();
3877 }
3878
3879 void
3880 Session::tempo_map_changed (const PropertyChange&)
3881 {
3882         clear_clicks ();
3883
3884         playlists->update_after_tempo_map_change ();
3885
3886         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3887
3888         set_dirty ();
3889 }
3890
3891 void
3892 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3893 {
3894         for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3895                 (*i)->recompute_frames_from_bbt ();
3896         }
3897 }
3898
3899 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3900  * the given count with the current block size.
3901  */
3902 void
3903 Session::ensure_buffers (ChanCount howmany)
3904 {
3905         BufferManager::ensure_buffers (howmany);
3906 }
3907
3908 void
3909 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3910 {
3911         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3912                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3913         }
3914 }
3915
3916 uint32_t
3917 Session::next_insert_id ()
3918 {
3919         /* this doesn't really loop forever. just think about it */
3920
3921         while (true) {
3922                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3923                         if (!insert_bitset[n]) {
3924                                 insert_bitset[n] = true;
3925                                 return n;
3926
3927                         }
3928                 }
3929
3930                 /* none available, so resize and try again */
3931
3932                 insert_bitset.resize (insert_bitset.size() + 16, false);
3933         }
3934 }
3935
3936 uint32_t
3937 Session::next_send_id ()
3938 {
3939         /* this doesn't really loop forever. just think about it */
3940
3941         while (true) {
3942                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3943                         if (!send_bitset[n]) {
3944                                 send_bitset[n] = true;
3945                                 return n;
3946
3947                         }
3948                 }
3949
3950                 /* none available, so resize and try again */
3951
3952                 send_bitset.resize (send_bitset.size() + 16, false);
3953         }
3954 }
3955
3956 uint32_t
3957 Session::next_aux_send_id ()
3958 {
3959         /* this doesn't really loop forever. just think about it */
3960
3961         while (true) {
3962                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3963                         if (!aux_send_bitset[n]) {
3964                                 aux_send_bitset[n] = true;
3965                                 return n;
3966
3967                         }
3968                 }
3969
3970                 /* none available, so resize and try again */
3971
3972                 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3973         }
3974 }
3975
3976 uint32_t
3977 Session::next_return_id ()
3978 {
3979         /* this doesn't really loop forever. just think about it */
3980
3981         while (true) {
3982                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3983                         if (!return_bitset[n]) {
3984                                 return_bitset[n] = true;
3985                                 return n;
3986
3987                         }
3988                 }
3989
3990                 /* none available, so resize and try again */
3991
3992                 return_bitset.resize (return_bitset.size() + 16, false);
3993         }
3994 }
3995
3996 void
3997 Session::mark_send_id (uint32_t id)
3998 {
3999         if (id >= send_bitset.size()) {
4000                 send_bitset.resize (id+16, false);
4001         }
4002         if (send_bitset[id]) {
4003                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4004         }
4005         send_bitset[id] = true;
4006 }
4007
4008 void
4009 Session::mark_aux_send_id (uint32_t id)
4010 {
4011         if (id >= aux_send_bitset.size()) {
4012                 aux_send_bitset.resize (id+16, false);
4013         }
4014         if (aux_send_bitset[id]) {
4015                 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4016         }
4017         aux_send_bitset[id] = true;
4018 }
4019
4020 void
4021 Session::mark_return_id (uint32_t id)
4022 {
4023         if (id >= return_bitset.size()) {
4024                 return_bitset.resize (id+16, false);
4025         }
4026         if (return_bitset[id]) {
4027                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4028         }
4029         return_bitset[id] = true;
4030 }
4031
4032 void
4033 Session::mark_insert_id (uint32_t id)
4034 {
4035         if (id >= insert_bitset.size()) {
4036                 insert_bitset.resize (id+16, false);
4037         }
4038         if (insert_bitset[id]) {
4039                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4040         }
4041         insert_bitset[id] = true;
4042 }
4043
4044 void
4045 Session::unmark_send_id (uint32_t id)
4046 {
4047         if (id < send_bitset.size()) {
4048                 send_bitset[id] = false;
4049         }
4050 }
4051
4052 void
4053 Session::unmark_aux_send_id (uint32_t id)
4054 {
4055         if (id < aux_send_bitset.size()) {
4056                 aux_send_bitset[id] = false;
4057         }
4058 }
4059
4060 void
4061 Session::unmark_return_id (uint32_t id)
4062 {
4063         if (id < return_bitset.size()) {
4064                 return_bitset[id] = false;
4065         }
4066 }
4067
4068 void
4069 Session::unmark_insert_id (uint32_t id)
4070 {
4071         if (id < insert_bitset.size()) {
4072                 insert_bitset[id] = false;
4073         }
4074 }
4075
4076 void
4077 Session::reset_native_file_format ()
4078 {
4079         boost::shared_ptr<RouteList> rl = routes.reader ();
4080         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4081                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4082                 if (tr) {
4083                         /* don't save state as we do this, there's no point
4084                          */
4085
4086                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4087                         tr->reset_write_sources (false);
4088                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4089                 }
4090         }
4091 }
4092
4093 bool
4094 Session::route_name_unique (string n) const
4095 {
4096         boost::shared_ptr<RouteList> r = routes.reader ();
4097
4098         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4099                 if ((*i)->name() == n) {
4100                         return false;
4101                 }
4102         }
4103
4104         return true;
4105 }
4106
4107 bool
4108 Session::route_name_internal (string n) const
4109 {
4110         if (auditioner && auditioner->name() == n) {
4111                 return true;
4112         }
4113
4114         if (_click_io && _click_io->name() == n) {
4115                 return true;
4116         }
4117
4118         return false;
4119 }
4120
4121 int
4122 Session::freeze_all (InterThreadInfo& itt)
4123 {
4124         boost::shared_ptr<RouteList> r = routes.reader ();
4125
4126         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4127
4128                 boost::shared_ptr<Track> t;
4129
4130                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4131                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
4132                            of every track.
4133                         */
4134                         t->freeze_me (itt);
4135                 }
4136         }
4137
4138         return 0;
4139 }
4140
4141 boost::shared_ptr<Region>
4142 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4143                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4144                           InterThreadInfo& itt, 
4145                           boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4146                           bool for_export)
4147 {
4148         boost::shared_ptr<Region> result;
4149         boost::shared_ptr<Playlist> playlist;
4150         boost::shared_ptr<AudioFileSource> fsource;
4151         uint32_t x;
4152         char buf[PATH_MAX+1];
4153         ChanCount diskstream_channels (track.n_channels());
4154         framepos_t position;
4155         framecnt_t this_chunk;
4156         framepos_t to_do;
4157         BufferSet buffers;
4158         SessionDirectory sdir(get_best_session_directory_for_new_source ());
4159         const string sound_dir = sdir.sound_path();
4160         framepos_t len = end - start;
4161         bool need_block_size_reset = false;
4162         string ext;
4163         ChanCount const max_proc = track.max_processor_streams ();
4164
4165         if (end <= start) {
4166                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4167                                          end, start) << endmsg;
4168                 return result;
4169         }
4170
4171         const framecnt_t chunk_size = (256 * 1024)/4;
4172
4173         // block all process callback handling
4174
4175         block_processing ();
4176
4177         /* call tree *MUST* hold route_lock */
4178
4179         if ((playlist = track.playlist()) == 0) {
4180                 goto out;
4181         }
4182
4183         ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4184
4185         for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4186
4187                 for (x = 0; x < 99999; ++x) {
4188                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 "%s", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1, ext.c_str());
4189                         if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4190                                 break;
4191                         }
4192                 }
4193
4194                 if (x == 99999) {
4195                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4196                         goto out;
4197                 }
4198
4199                 try {
4200                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4201                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4202                 }
4203
4204                 catch (failed_constructor& err) {
4205                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4206                         goto out;
4207                 }
4208
4209                 srcs.push_back (fsource);
4210         }
4211
4212         /* tell redirects that care that we are about to use a much larger
4213          * blocksize. this will flush all plugins too, so that they are ready
4214          * to be used for this process.
4215          */
4216
4217         need_block_size_reset = true;
4218         track.set_block_size (chunk_size);
4219
4220         position = start;
4221         to_do = len;
4222
4223         /* create a set of reasonably-sized buffers */
4224         buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
4225         buffers.set_count (max_proc);
4226
4227         for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4228                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4229                 if (afs)
4230                         afs->prepare_for_peakfile_writes ();
4231         }
4232
4233         while (to_do && !itt.cancel) {
4234
4235                 this_chunk = min (to_do, chunk_size);
4236
4237                 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4238                         goto out;
4239                 }
4240
4241                 uint32_t n = 0;
4242                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4243                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4244
4245                         if (afs) {
4246                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4247                                         goto out;
4248                                 }
4249                         }
4250                 }
4251
4252                 start += this_chunk;
4253                 to_do -= this_chunk;
4254
4255                 itt.progress = (float) (1.0 - ((double) to_do / len));
4256
4257         }
4258
4259         if (!itt.cancel) {
4260
4261                 time_t now;
4262                 struct tm* xnow;
4263                 time (&now);
4264                 xnow = localtime (&now);
4265
4266                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4267                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4268
4269                         if (afs) {
4270                                 afs->update_header (position, *xnow, now);
4271                                 afs->flush_header ();
4272                         }
4273                 }
4274
4275                 /* construct a region to represent the bounced material */
4276
4277                 PropertyList plist;
4278
4279                 plist.add (Properties::start, 0);
4280                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4281                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4282
4283                 result = RegionFactory::create (srcs, plist);
4284
4285         }
4286
4287   out:
4288         if (!result) {
4289                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4290                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4291
4292                         if (afs) {
4293                                 afs->mark_for_remove ();
4294                         }
4295
4296                         (*src)->drop_references ();
4297                 }
4298
4299         } else {
4300                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4301                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4302
4303                         if (afs)
4304                                 afs->done_with_peakfile_writes ();
4305                 }
4306         }
4307
4308
4309         if (need_block_size_reset) {
4310                 track.set_block_size (get_block_size());
4311         }
4312
4313         unblock_processing ();
4314
4315         return result;
4316 }
4317
4318 gain_t*
4319 Session::gain_automation_buffer() const
4320 {
4321         return ProcessThread::gain_automation_buffer ();
4322 }
4323
4324 gain_t*
4325 Session::send_gain_automation_buffer() const
4326 {
4327         return ProcessThread::send_gain_automation_buffer ();
4328 }
4329
4330 pan_t**
4331 Session::pan_automation_buffer() const
4332 {
4333         return ProcessThread::pan_automation_buffer ();
4334 }
4335
4336 BufferSet&
4337 Session::get_silent_buffers (ChanCount count)
4338 {
4339         return ProcessThread::get_silent_buffers (count);
4340 }
4341
4342 BufferSet&
4343 Session::get_scratch_buffers (ChanCount count, bool silence)
4344 {
4345         return ProcessThread::get_scratch_buffers (count, silence);
4346 }
4347
4348 BufferSet&
4349 Session::get_route_buffers (ChanCount count, bool silence)
4350 {
4351         return ProcessThread::get_route_buffers (count, silence);
4352 }
4353
4354
4355 BufferSet&
4356 Session::get_mix_buffers (ChanCount count)
4357 {
4358         return ProcessThread::get_mix_buffers (count);
4359 }
4360
4361 uint32_t
4362 Session::ntracks () const
4363 {
4364         uint32_t n = 0;
4365         boost::shared_ptr<RouteList> r = routes.reader ();
4366
4367         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4368                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4369                         ++n;
4370                 }
4371         }
4372
4373         return n;
4374 }
4375
4376 uint32_t
4377 Session::nbusses () const
4378 {
4379         uint32_t n = 0;
4380         boost::shared_ptr<RouteList> r = routes.reader ();
4381
4382         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4383                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4384                         ++n;
4385                 }
4386         }
4387
4388         return n;
4389 }
4390
4391 void
4392 Session::add_automation_list(AutomationList *al)
4393 {
4394         automation_lists[al->id()] = al;
4395 }
4396
4397 /** @return true if there is at least one record-enabled track, otherwise false */
4398 bool
4399 Session::have_rec_enabled_track () const
4400 {
4401         return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4402 }
4403
4404 /** Update the state of our rec-enabled tracks flag */
4405 void
4406 Session::update_have_rec_enabled_track ()
4407 {
4408         boost::shared_ptr<RouteList> rl = routes.reader ();
4409         RouteList::iterator i = rl->begin();
4410         while (i != rl->end ()) {
4411
4412                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4413                 if (tr && tr->record_enabled ()) {
4414                         break;
4415                 }
4416
4417                 ++i;
4418         }
4419
4420         int const old = g_atomic_int_get (&_have_rec_enabled_track);
4421
4422         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4423
4424         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4425                 RecordStateChanged (); /* EMIT SIGNAL */
4426         }
4427 }
4428
4429 void
4430 Session::listen_position_changed ()
4431 {
4432         boost::shared_ptr<RouteList> r = routes.reader ();
4433
4434         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4435                 (*i)->listen_position_changed ();
4436         }
4437 }
4438
4439 void
4440 Session::solo_control_mode_changed ()
4441 {
4442         /* cancel all solo or all listen when solo control mode changes */
4443
4444         if (soloing()) {
4445                 set_solo (get_routes(), false);
4446         } else if (listening()) {
4447                 set_listen (get_routes(), false);
4448         }
4449 }
4450
4451 /** Called when a property of one of our route groups changes */
4452 void
4453 Session::route_group_property_changed (RouteGroup* rg)
4454 {
4455         RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4456 }
4457
4458 /** Called when a route is added to one of our route groups */
4459 void
4460 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4461 {
4462         RouteAddedToRouteGroup (rg, r);
4463 }
4464
4465 /** Called when a route is removed from one of our route groups */
4466 void
4467 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4468 {
4469         RouteRemovedFromRouteGroup (rg, r);
4470 }
4471
4472 boost::shared_ptr<RouteList>
4473 Session::get_routes_with_regions_at (framepos_t const p) const
4474 {
4475         boost::shared_ptr<RouteList> r = routes.reader ();
4476         boost::shared_ptr<RouteList> rl (new RouteList);
4477
4478         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4479                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4480                 if (!tr) {
4481                         continue;
4482                 }
4483
4484                 boost::shared_ptr<Playlist> pl = tr->playlist ();
4485                 if (!pl) {
4486                         continue;
4487                 }
4488
4489                 if (pl->has_region_at (p)) {
4490                         rl->push_back (*i);
4491                 }
4492         }
4493
4494         return rl;
4495 }
4496
4497 void
4498 Session::goto_end ()
4499 {
4500         if (_session_range_location) {
4501                 request_locate (_session_range_location->end(), false);
4502         } else {
4503                 request_locate (0, false);
4504         }
4505 }
4506
4507 void
4508 Session::goto_start ()
4509 {
4510         if (_session_range_location) {
4511                 request_locate (_session_range_location->start(), false);
4512         } else {
4513                 request_locate (0, false);
4514         }
4515 }
4516
4517 framepos_t
4518 Session::current_start_frame () const
4519 {
4520         return _session_range_location ? _session_range_location->start() : 0;
4521 }
4522
4523 framepos_t
4524 Session::current_end_frame () const
4525 {
4526         return _session_range_location ? _session_range_location->end() : 0;
4527 }
4528
4529 void
4530 Session::add_session_range_location (framepos_t start, framepos_t end)
4531 {
4532         _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4533         _locations->add (_session_range_location);
4534 }
4535
4536 void
4537 Session::step_edit_status_change (bool yn)
4538 {
4539         bool send = false;
4540
4541         bool val = false;
4542         if (yn) {
4543                 send = (_step_editors == 0);
4544                 val = true;
4545
4546                 _step_editors++;
4547         } else {
4548                 send = (_step_editors == 1);
4549                 val = false;
4550
4551                 if (_step_editors > 0) {
4552                         _step_editors--;
4553                 }
4554         }
4555
4556         if (send) {
4557                 StepEditStatusChange (val);
4558         }
4559 }
4560
4561
4562 void
4563 Session::start_time_changed (framepos_t old)
4564 {
4565         /* Update the auto loop range to match the session range
4566            (unless the auto loop range has been changed by the user)
4567         */
4568
4569         Location* s = _locations->session_range_location ();
4570         if (s == 0) {
4571                 return;
4572         }
4573
4574         Location* l = _locations->auto_loop_location ();
4575
4576         if (l && l->start() == old) {
4577                 l->set_start (s->start(), true);
4578         }
4579 }
4580
4581 void
4582 Session::end_time_changed (framepos_t old)
4583 {
4584         /* Update the auto loop range to match the session range
4585            (unless the auto loop range has been changed by the user)
4586         */
4587
4588         Location* s = _locations->session_range_location ();
4589         if (s == 0) {
4590                 return;
4591         }
4592
4593         Location* l = _locations->auto_loop_location ();
4594
4595         if (l && l->end() == old) {
4596                 l->set_end (s->end(), true);
4597         }
4598 }
4599
4600 string
4601 Session::source_search_path (DataType type) const
4602 {
4603         vector<string> s;
4604
4605         if (session_dirs.size() == 1) {
4606                 switch (type) {
4607                 case DataType::AUDIO:
4608                         s.push_back (_session_dir->sound_path());
4609                         break;
4610                 case DataType::MIDI:
4611                         s.push_back (_session_dir->midi_path());
4612                         break;
4613                 }
4614         } else {
4615                 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4616                         SessionDirectory sdir (i->path);
4617                         switch (type) {
4618                         case DataType::AUDIO:
4619                                 s.push_back (sdir.sound_path());
4620                                 break;
4621                         case DataType::MIDI:
4622                                 s.push_back (sdir.midi_path());
4623                                 break;
4624                         }
4625                 }
4626         }
4627
4628         if (type == DataType::AUDIO) {
4629                 const string sound_path_2X = _session_dir->sound_path_2X();
4630                 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4631                         if (find (s.begin(), s.end(), sound_path_2X) == s.end()) {
4632                                 s.push_back (sound_path_2X);
4633                         }
4634                 }
4635         }
4636
4637         /* now check the explicit (possibly user-specified) search path
4638          */
4639
4640         vector<string> dirs;
4641
4642         switch (type) {
4643         case DataType::AUDIO:
4644                 split (config.get_audio_search_path (), dirs, ':');
4645                 break;
4646         case DataType::MIDI:
4647                 split (config.get_midi_search_path (), dirs, ':');
4648                 break;
4649         }
4650
4651         for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4652                 if (find (s.begin(), s.end(), *i) == s.end()) {
4653                         s.push_back (*i);
4654                 }
4655         }
4656         
4657         string search_path;
4658
4659         for (vector<string>::iterator si = s.begin(); si != s.end(); ++si) {
4660                 if (!search_path.empty()) {
4661                         search_path += ':';
4662                 }
4663                 search_path += *si;
4664         }
4665
4666         return search_path;
4667 }
4668
4669 void
4670 Session::ensure_search_path_includes (const string& path, DataType type)
4671 {
4672         string search_path;
4673         vector<string> dirs;
4674
4675         if (path == ".") {
4676                 return;
4677         }
4678
4679         switch (type) {
4680         case DataType::AUDIO:
4681                 search_path = config.get_audio_search_path ();
4682                 break;
4683         case DataType::MIDI:
4684                 search_path = config.get_midi_search_path ();
4685                 break;
4686         }
4687
4688         split (search_path, dirs, ':');
4689
4690         for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4691                 /* No need to add this new directory if it has the same inode as
4692                    an existing one; checking inode rather than name prevents duplicated
4693                    directories when we are using symlinks.
4694
4695                    On Windows, I think we could just do if (*i == path) here.
4696                 */
4697                 if (PBD::equivalent_paths (*i, path)) {
4698                         return;
4699                 }
4700         }
4701
4702         if (!search_path.empty()) {
4703                 search_path += ':';
4704         }
4705
4706         search_path += path;
4707
4708         switch (type) {
4709         case DataType::AUDIO:
4710                 config.set_audio_search_path (search_path);
4711                 break;
4712         case DataType::MIDI:
4713                 config.set_midi_search_path (search_path);
4714                 break;
4715         }
4716 }
4717
4718 boost::shared_ptr<Speakers>
4719 Session::get_speakers()
4720 {
4721         return _speakers;
4722 }
4723
4724 list<string>
4725 Session::unknown_processors () const
4726 {
4727         list<string> p;
4728
4729         boost::shared_ptr<RouteList> r = routes.reader ();
4730         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4731                 list<string> t = (*i)->unknown_processors ();
4732                 copy (t.begin(), t.end(), back_inserter (p));
4733         }
4734
4735         p.sort ();
4736         p.unique ();
4737
4738         return p;
4739 }
4740
4741 void
4742 Session::update_latency (bool playback)
4743 {
4744         DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4745
4746         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4747                 return;
4748         }
4749
4750         boost::shared_ptr<RouteList> r = routes.reader ();
4751         framecnt_t max_latency = 0;
4752
4753         if (playback) {
4754                 /* reverse the list so that we work backwards from the last route to run to the first */
4755                 RouteList* rl = routes.reader().get();
4756                 r.reset (new RouteList (*rl));
4757                 reverse (r->begin(), r->end());
4758         }
4759
4760         /* compute actual latency values for the given direction and store them all in per-port
4761            structures. this will also publish the same values (to JACK) so that computation of latency
4762            for routes can consistently use public latency values.
4763         */
4764
4765         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4766                 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4767         }
4768
4769         /* because we latency compensate playback, our published playback latencies should
4770            be the same for all output ports - all material played back by ardour has
4771            the same latency, whether its caused by plugins or by latency compensation. since
4772            these may differ from the values computed above, reset all playback port latencies
4773            to the same value.
4774         */
4775
4776         DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4777
4778         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4779                 (*i)->set_public_port_latencies (max_latency, playback);
4780         }
4781
4782         if (playback) {
4783
4784                 post_playback_latency ();
4785
4786         } else {
4787
4788                 post_capture_latency ();
4789         }
4790
4791         DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4792 }
4793
4794 void
4795 Session::post_playback_latency ()
4796 {
4797         set_worst_playback_latency ();
4798
4799         boost::shared_ptr<RouteList> r = routes.reader ();
4800
4801         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4802                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4803                         _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4804                 }
4805         }
4806
4807         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4808                 (*i)->set_latency_compensation (_worst_track_latency);
4809         }
4810 }
4811
4812 void
4813 Session::post_capture_latency ()
4814 {
4815         set_worst_capture_latency ();
4816
4817         /* reflect any changes in capture latencies into capture offsets
4818          */
4819
4820         boost::shared_ptr<RouteList> rl = routes.reader();
4821         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4822                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4823                 if (tr) {
4824                         tr->set_capture_offset ();
4825                 }
4826         }
4827 }
4828
4829 void
4830 Session::initialize_latencies ()
4831 {
4832         {
4833                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4834                 update_latency (false);
4835                 update_latency (true);
4836         }
4837
4838         set_worst_io_latencies ();
4839 }
4840
4841 void
4842 Session::set_worst_io_latencies ()
4843 {
4844         set_worst_playback_latency ();
4845         set_worst_capture_latency ();
4846 }
4847
4848 void
4849 Session::set_worst_playback_latency ()
4850 {
4851         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4852                 return;
4853         }
4854
4855         _worst_output_latency = 0;
4856
4857         if (!_engine.connected()) {
4858                 return;
4859         }
4860
4861         boost::shared_ptr<RouteList> r = routes.reader ();
4862
4863         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4864                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4865         }
4866
4867         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4868 }
4869
4870 void
4871 Session::set_worst_capture_latency ()
4872 {
4873         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4874                 return;
4875         }
4876
4877         _worst_input_latency = 0;
4878
4879         if (!_engine.connected()) {
4880                 return;
4881         }
4882
4883         boost::shared_ptr<RouteList> r = routes.reader ();
4884
4885         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4886                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4887         }
4888
4889         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4890 }
4891
4892 void
4893 Session::update_latency_compensation (bool force_whole_graph)
4894 {
4895         bool some_track_latency_changed = false;
4896
4897         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4898                 return;
4899         }
4900
4901         DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4902
4903         _worst_track_latency = 0;
4904
4905         boost::shared_ptr<RouteList> r = routes.reader ();
4906
4907         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4908                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4909                         framecnt_t tl;
4910                         if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4911                                 some_track_latency_changed = true;
4912                         }
4913                         _worst_track_latency = max (tl, _worst_track_latency);
4914                 }
4915         }
4916
4917         DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4918                                                      (some_track_latency_changed ? "yes" : "no")));
4919
4920         DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4921         
4922         if (some_track_latency_changed || force_whole_graph)  {
4923                 _engine.update_latencies ();
4924         }
4925
4926
4927         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4928                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4929                 if (!tr) {
4930                         continue;
4931                 }
4932                 tr->set_capture_offset ();
4933         }
4934 }
4935
4936 char
4937 Session::session_name_is_legal (const string& path)
4938 {
4939         char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4940
4941         for (int i = 0; illegal_chars[i]; ++i) {
4942                 if (path.find (illegal_chars[i]) != string::npos) {
4943                         return illegal_chars[i];
4944                 }
4945         }
4946
4947         return 0;
4948 }
4949
4950 uint32_t 
4951 Session::next_control_id () const
4952 {
4953         int subtract = 0;
4954
4955         /* the monitor bus remote ID is in a different
4956          * "namespace" than regular routes. its existence doesn't
4957          * affect normal (low) numbered routes.
4958          */
4959
4960         if (_monitor_out) {
4961                 subtract++;
4962         }
4963
4964         return nroutes() - subtract;
4965 }
4966
4967 void
4968 Session::notify_remote_id_change ()
4969 {
4970         if (deletion_in_progress()) {
4971                 return;
4972         }
4973
4974         switch (Config->get_remote_model()) {
4975         case MixerSort:
4976         case EditorSort:
4977                 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4978                 break;
4979         default:
4980                 break;
4981         }
4982 }
4983
4984 void
4985 Session::sync_order_keys (RouteSortOrderKey sort_key_changed)
4986 {
4987         if (deletion_in_progress()) {
4988                 return;
4989         }
4990
4991         /* tell everyone that something has happened to the sort keys
4992            and let them sync up with the change(s)
4993            this will give objects that manage the sort order keys the
4994            opportunity to keep them in sync if they wish to.
4995         */
4996
4997         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("Sync Order Keys, based on %1\n", enum_2_string (sort_key_changed)));
4998
4999         Route::SyncOrderKeys (sort_key_changed); /* EMIT SIGNAL */
5000
5001         DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5002 }
5003
5004 bool
5005 Session::operation_in_progress (GQuark op) const
5006 {
5007         return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5008 }
5009
5010 boost::shared_ptr<Port>
5011 Session::ltc_input_port () const
5012 {
5013         return _ltc_input->nth (0);
5014 }
5015
5016 boost::shared_ptr<Port>
5017 Session::ltc_output_port () const
5018 {
5019         return _ltc_output->nth (0);
5020 }
5021
5022 void
5023 Session::reconnect_ltc_input ()
5024 {
5025         if (_ltc_input) {
5026
5027                 string src = Config->get_ltc_source_port();
5028
5029                 _ltc_input->disconnect (this);
5030
5031                 if (src != _("None") && !src.empty())  {
5032                         _ltc_input->nth (0)->connect (src);
5033                 }
5034         }
5035 }
5036
5037 void
5038 Session::reconnect_ltc_output ()
5039 {
5040         if (_ltc_output) {
5041
5042 #if 0
5043                 string src = Config->get_ltc_sink_port();
5044
5045                 _ltc_output->disconnect (this);
5046
5047                 if (src != _("None") && !src.empty())  {
5048                         _ltc_output->nth (0)->connect (src);
5049                 }
5050 #endif
5051         }
5052 }