move latency-recompute into dedicated thread.
[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 <cstdio> /* sprintf(3) ... grrr */
27 #include <cmath>
28 #include <cerrno>
29 #include <unistd.h>
30 #include <limits.h>
31
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
35
36 #include <boost/algorithm/string/erase.hpp>
37
38 #include "pbd/basename.h"
39 #include "pbd/convert.h"
40 #include "pbd/convert.h"
41 #include "pbd/error.h"
42 #include "pbd/file_utils.h"
43 #include "pbd/md5.h"
44 #include "pbd/pthread_utils.h"
45 #include "pbd/search_path.h"
46 #include "pbd/stacktrace.h"
47 #include "pbd/stl_delete.h"
48 #include "pbd/replace_all.h"
49 #include "pbd/unwind.h"
50
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/boost_debug.h"
62 #include "ardour/buffer_manager.h"
63 #include "ardour/buffer_set.h"
64 #include "ardour/bundle.h"
65 #include "ardour/butler.h"
66 #include "ardour/click.h"
67 #include "ardour/control_protocol_manager.h"
68 #include "ardour/data_type.h"
69 #include "ardour/debug.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
73 #endif
74 #include "ardour/filename_extensions.h"
75 #include "ardour/gain_control.h"
76 #include "ardour/graph.h"
77 #include "ardour/luabindings.h"
78 #include "ardour/midiport_manager.h"
79 #include "ardour/scene_changer.h"
80 #include "ardour/midi_patch_manager.h"
81 #include "ardour/midi_track.h"
82 #include "ardour/midi_ui.h"
83 #include "ardour/operations.h"
84 #include "ardour/playlist.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/revision.h"
94 #include "ardour/route_graph.h"
95 #include "ardour/route_group.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/solo_isolate_control.h"
102 #include "ardour/source_factory.h"
103 #include "ardour/speakers.h"
104 #include "ardour/tempo.h"
105 #include "ardour/ticker.h"
106 #include "ardour/track.h"
107 #include "ardour/user_bundle.h"
108 #include "ardour/utils.h"
109 #include "ardour/vca_manager.h"
110 #include "ardour/vca.h"
111
112 #include "midi++/port.h"
113 #include "midi++/mmc.h"
114
115 #include "LuaBridge/LuaBridge.h"
116
117 #include "i18n.h"
118
119 #include <glibmm/checksum.h>
120
121 namespace ARDOUR {
122 class MidiSource;
123 class Processor;
124 class Speakers;
125 }
126
127 using namespace std;
128 using namespace ARDOUR;
129 using namespace PBD;
130
131 bool Session::_disable_all_loaded_plugins = false;
132 bool Session::_bypass_all_loaded_plugins = false;
133 guint Session::_name_id_counter = 0;
134
135 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
136 PBD::Signal1<void,std::string> Session::Dialog;
137 PBD::Signal0<int> Session::AskAboutPendingState;
138 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
139 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
140 PBD::Signal0<void> Session::SendFeedback;
141 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
142
143 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
144 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
145 PBD::Signal2<void,std::string, std::string> Session::Exported;
146 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
147 PBD::Signal0<void> Session::Quit;
148 PBD::Signal0<void> Session::FeedbackDetected;
149 PBD::Signal0<void> Session::SuccessfulGraphSort;
150 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
151
152 const framecnt_t Session::bounce_chunk_size = 8192;
153 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
154 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
155
156 // seconds should be added after the region exceeds end marker
157 #ifdef USE_TRACKS_CODE_FEATURES
158 const uint32_t Session::session_end_shift = 5;
159 #else
160 const uint32_t Session::session_end_shift = 0;
161 #endif
162
163 /** @param snapshot_name Snapshot name, without .ardour suffix */
164 Session::Session (AudioEngine &eng,
165                   const string& fullpath,
166                   const string& snapshot_name,
167                   BusProfile* bus_profile,
168                   string mix_template)
169         : playlists (new SessionPlaylists)
170         , _engine (eng)
171         , process_function (&Session::process_with_events)
172         , _bounce_processing_active (false)
173         , waiting_for_sync_offset (false)
174         , _base_frame_rate (0)
175         , _nominal_frame_rate (0)
176         , _current_frame_rate (0)
177         , transport_sub_state (0)
178         , _record_status (Disabled)
179         , _transport_frame (0)
180         , _session_range_location (0)
181         , _slave (0)
182         , _silent (false)
183         , _transport_speed (0)
184         , _default_transport_speed (1.0)
185         , _last_transport_speed (0)
186         , _target_transport_speed (0.0)
187         , auto_play_legal (false)
188         , _last_slave_transport_frame (0)
189         , maximum_output_latency (0)
190         , _requested_return_frame (-1)
191         , current_block_size (0)
192         , _worst_output_latency (0)
193         , _worst_input_latency (0)
194         , _worst_track_latency (0)
195         , _have_captured (false)
196         , _non_soloed_outs_muted (false)
197         , _listening (false)
198         , _listen_cnt (0)
199         , _solo_isolated_cnt (0)
200         , _writable (false)
201         , _was_seamless (Config->get_seamless_loop ())
202         , _under_nsm_control (false)
203         , _xrun_count (0)
204         , delta_accumulator_cnt (0)
205         , average_slave_delta (1800) // !!! why 1800 ???
206         , average_dir (0)
207         , have_first_delta_accumulator (false)
208         , _slave_state (Stopped)
209         , _mtc_active (false)
210         , _ltc_active (false)
211         , post_export_sync (false)
212         , post_export_position (0)
213         , _exporting (false)
214         , _export_rolling (false)
215         , _export_preroll (0)
216         , _pre_export_mmc_enabled (false)
217         , _name (snapshot_name)
218         , _is_new (true)
219         , _send_qf_mtc (false)
220         , _pframes_since_last_mtc (0)
221         , session_midi_feedback (0)
222         , play_loop (false)
223         , loop_changing (false)
224         , last_loopend (0)
225         , _session_dir (new SessionDirectory (fullpath))
226         , _current_snapshot_name (snapshot_name)
227         , state_tree (0)
228         , state_was_pending (false)
229         , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
230         , _suspend_save (0)
231         , _save_queued (false)
232         , _last_roll_location (0)
233         , _last_roll_or_reversal_location (0)
234         , _last_record_location (0)
235         , pending_locate_roll (false)
236         , pending_locate_frame (0)
237         , pending_locate_flush (false)
238         , pending_abort (false)
239         , pending_auto_loop (false)
240         , _mempool ("Session", 2097152)
241         , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
242         , _n_lua_scripts (0)
243         , _butler (new Butler (*this))
244         , _post_transport_work (0)
245         ,  cumulative_rf_motion (0)
246         , rf_scale (1.0)
247         , _locations (new Locations (*this))
248         , _ignore_skips_updates (false)
249         , _rt_thread_active (false)
250         , _rt_emit_pending (false)
251         , _ac_thread_active (false)
252         , step_speed (0)
253         , outbound_mtc_timecode_frame (0)
254         , next_quarter_frame_to_send (-1)
255         , _frames_per_timecode_frame (0)
256         , _frames_per_hour (0)
257         , _timecode_frames_per_hour (0)
258         , last_timecode_valid (false)
259         , last_timecode_when (0)
260         , _send_timecode_update (false)
261         , ltc_encoder (0)
262         , ltc_enc_buf(0)
263         , ltc_buf_off (0)
264         , ltc_buf_len (0)
265         , ltc_speed (0)
266         , ltc_enc_byte (0)
267         , ltc_enc_pos (0)
268         , ltc_enc_cnt (0)
269         , ltc_enc_off (0)
270         , restarting (false)
271         , ltc_prev_cycle (0)
272         , ltc_timecode_offset (0)
273         , ltc_timecode_negative_offset (false)
274         , midi_control_ui (0)
275         , _tempo_map (0)
276         , _all_route_group (new RouteGroup (*this, "all"))
277         , routes (new RouteList)
278         , _adding_routes_in_progress (false)
279         , _reconnecting_routes_in_progress (false)
280         , _route_deletion_in_progress (false)
281         , destructive_index (0)
282         , _latency_recompute_pending (0)
283         , _track_number_decimals(1)
284         , default_fade_steepness (0)
285         , default_fade_msecs (0)
286         , _total_free_4k_blocks (0)
287         , _total_free_4k_blocks_uncertain (false)
288         , no_questions_about_missing_files (false)
289         , _playback_load (0)
290         , _capture_load (0)
291         , _bundles (new BundleList)
292         , _bundle_xml_node (0)
293         , _current_trans (0)
294         , _clicking (false)
295         , click_data (0)
296         , click_emphasis_data (0)
297         , click_length (0)
298         , click_emphasis_length (0)
299         , _clicks_cleared (0)
300         , _play_range (false)
301         , _range_selection (-1,-1)
302         , _object_selection (-1,-1)
303         , main_outs (0)
304         , first_file_data_format_reset (true)
305         , first_file_header_format_reset (true)
306         , have_looped (false)
307         , _have_rec_enabled_track (false)
308         , _have_rec_disabled_track (true)
309         , _step_editors (0)
310         , _suspend_timecode_transmission (0)
311         ,  _speakers (new Speakers)
312         , ignore_route_processor_changes (false)
313         , midi_clock (0)
314         , _scene_changer (0)
315         , _midi_ports (0)
316         , _mmc (0)
317         , _vca_manager (new VCAManager (*this))
318 {
319         uint32_t sr = 0;
320
321         created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
322
323         pthread_mutex_init (&_rt_emit_mutex, 0);
324         pthread_cond_init (&_rt_emit_cond, 0);
325
326         pthread_mutex_init (&_auto_connect_mutex, 0);
327         pthread_cond_init (&_auto_connect_cond, 0);
328
329         init_name_id_counter (1); // reset for new sessions, start at 1
330         VCA::set_next_vca_number (1); // reset for new sessions, start at 1
331
332         pre_engine_init (fullpath);
333
334         setup_lua ();
335
336         if (_is_new) {
337
338                 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
339
340 #ifdef USE_TRACKS_CODE_FEATURES
341                 sr = EngineStateController::instance()->get_current_sample_rate();
342 #endif
343                 if (ensure_engine (sr, true)) {
344                         destroy ();
345                         throw SessionException (_("Cannot connect to audio/midi engine"));
346                 }
347
348                 // set samplerate for plugins added early
349                 // e.g from templates or MB channelstrip
350                 set_block_size (_engine.samples_per_cycle());
351                 set_frame_rate (_engine.sample_rate());
352
353                 if (create (mix_template, bus_profile)) {
354                         destroy ();
355                         throw SessionException (_("Session initialization failed"));
356                 }
357
358                 /* if a mix template was provided, then ::create() will
359                  * have copied it into the session and we need to load it
360                  * so that we have the state ready for ::set_state()
361                  * after the engine is started.
362                  *
363                  * Note that we do NOT try to get the sample rate from
364                  * the template at this time, though doing so would
365                  * be easy if we decided this was an appropriate part
366                  * of a template.
367                  */
368
369                 if (!mix_template.empty()) {
370                         if (load_state (_current_snapshot_name)) {
371                                 throw SessionException (_("Failed to load template/snapshot state"));
372                         }
373                         store_recent_templates (mix_template);
374                 }
375
376                 /* load default session properties - if any */
377                 config.load_state();
378
379         } else {
380
381                 if (load_state (_current_snapshot_name)) {
382                         throw SessionException (_("Failed to load state"));
383                 }
384
385                 /* try to get sample rate from XML state so that we
386                  * can influence the SR if we set up the audio
387                  * engine.
388                  */
389
390                 if (state_tree) {
391                         XMLProperty const * prop;
392                         XMLNode const * root (state_tree->root());
393                         if ((prop = root->property (X_("sample-rate"))) != 0) {
394                                 sr = atoi (prop->value());
395                         }
396                 }
397
398                 if (ensure_engine (sr, false)) {
399                         destroy ();
400                         throw SessionException (_("Cannot connect to audio/midi engine"));
401                 }
402         }
403
404         if (post_engine_init ()) {
405                 destroy ();
406                 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
407         }
408
409         store_recent_sessions (_name, _path);
410
411         bool was_dirty = dirty();
412
413         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
414
415         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
416         config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
417
418         if (was_dirty) {
419                 DirtyChanged (); /* EMIT SIGNAL */
420         }
421
422         StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
423         EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
424
425         emit_thread_start ();
426         auto_connect_thread_start ();
427
428         /* hook us up to the engine since we are now completely constructed */
429
430         BootMessage (_("Connect to engine"));
431
432         _engine.set_session (this);
433         _engine.reset_timebase ();
434
435 #ifdef USE_TRACKS_CODE_FEATURES
436
437         EngineStateController::instance()->set_session(this);
438
439         if (_is_new ) {
440                 if ( ARDOUR::Profile->get_trx () ) {
441
442                         /* Waves Tracks: fill session with tracks basing on the amount of inputs.
443                          * each available input must have corresponding track when session starts.
444                          */
445
446                         uint32_t how_many (0);
447
448                         std::vector<std::string> inputs;
449                         EngineStateController::instance()->get_physical_audio_inputs(inputs);
450
451                         how_many = inputs.size();
452
453                         list<boost::shared_ptr<AudioTrack> > tracks;
454
455                         // Track names after driver
456                         if (Config->get_tracks_auto_naming() == NameAfterDriver) {
457                                 string track_name = "";
458                                 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
459                                         string track_name;
460                                         track_name = inputs[i];
461                                         replace_all (track_name, "system:capture", "");
462
463                                         list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
464                                         tracks.insert(tracks.begin(), single_track.front());
465                                 }
466                         } else { // Default track names
467                                 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
468                         }
469
470                         if (tracks.size() != how_many) {
471                                 destroy ();
472                                 throw failed_constructor ();
473                         }
474                 }
475         }
476 #endif
477
478         _is_new = false;
479         session_loaded ();
480
481         BootMessage (_("Session loading complete"));
482 }
483
484 Session::~Session ()
485 {
486 #ifdef PT_TIMING
487         ST.dump ("ST.dump");
488 #endif
489         destroy ();
490 }
491
492 unsigned int
493 Session::next_name_id ()
494 {
495         return g_atomic_int_add (&_name_id_counter, 1);
496 }
497
498 unsigned int
499 Session::name_id_counter ()
500 {
501         return g_atomic_int_get (&_name_id_counter);
502 }
503
504 void
505 Session::init_name_id_counter (guint n)
506 {
507         g_atomic_int_set (&_name_id_counter, n);
508 }
509
510 int
511 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
512 {
513         if (_engine.current_backend() == 0) {
514                 /* backend is unknown ... */
515                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
516                 if (r.get_value_or (-1) != 0) {
517                         return -1;
518                 }
519         } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
520                 /* keep engine */
521         } else if (_engine.setup_required()) {
522                 /* backend is known, but setup is needed */
523                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
524                 if (r.get_value_or (-1) != 0) {
525                         return -1;
526                 }
527         } else if (!_engine.running()) {
528                 if (_engine.start()) {
529                         return -1;
530                 }
531         }
532
533         /* at this point the engine should be running */
534
535         if (!_engine.running()) {
536                 return -1;
537         }
538
539         return immediately_post_engine ();
540
541 }
542
543 int
544 Session::immediately_post_engine ()
545 {
546         /* Do various initializations that should take place directly after we
547          * know that the engine is running, but before we either create a
548          * session or set state for an existing one.
549          */
550
551         if (how_many_dsp_threads () > 1) {
552                 /* For now, only create the graph if we are using >1 DSP threads, as
553                    it is a bit slower than the old code with 1 thread.
554                 */
555                 _process_graph.reset (new Graph (*this));
556         }
557
558         /* every time we reconnect, recompute worst case output latencies */
559
560         _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
561
562         if (synced_to_engine()) {
563                 _engine.transport_stop ();
564         }
565
566         if (config.get_jack_time_master()) {
567                 _engine.transport_locate (_transport_frame);
568         }
569
570         try {
571                 LocaleGuard lg;
572                 BootMessage (_("Set up LTC"));
573                 setup_ltc ();
574                 BootMessage (_("Set up Click"));
575                 setup_click ();
576                 BootMessage (_("Set up standard connections"));
577                 setup_bundles ();
578         }
579
580         catch (failed_constructor& err) {
581                 return -1;
582         }
583
584         /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
585          * can we do that? */
586          _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
587
588         return 0;
589 }
590
591 void
592 Session::destroy ()
593 {
594         vector<void*> debug_pointers;
595
596         /* if we got to here, leaving pending capture state around
597            is a mistake.
598         */
599
600         remove_pending_capture_state ();
601
602         Analyser::flush ();
603
604         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
605
606         /* stop autoconnecting */
607         auto_connect_thread_terminate ();
608
609         /* disconnect from any and all signals that we are connected to */
610
611         Port::PortSignalDrop (); /* EMIT SIGNAL */
612         drop_connections ();
613
614         /* shutdown control surface protocols while we still have ports
615            and the engine to move data to any devices.
616         */
617
618         ControlProtocolManager::instance().drop_protocols ();
619
620         MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
621
622         _engine.remove_session ();
623
624 #ifdef USE_TRACKS_CODE_FEATURES
625         EngineStateController::instance()->remove_session();
626 #endif
627
628         /* deregister all ports - there will be no process or any other
629          * callbacks from the engine any more.
630          */
631
632         Port::PortDrop (); /* EMIT SIGNAL */
633
634         ltc_tx_cleanup();
635
636         /* clear history so that no references to objects are held any more */
637
638         _history.clear ();
639
640         /* clear state tree so that no references to objects are held any more */
641
642         delete state_tree;
643         state_tree = 0;
644
645         // unregister all lua functions, drop held references (if any)
646         (*_lua_cleanup)();
647         lua.do_command ("Session = nil");
648         delete _lua_run;
649         delete _lua_add;
650         delete _lua_del;
651         delete _lua_list;
652         delete _lua_save;
653         delete _lua_load;
654         delete _lua_cleanup;
655         lua.collect_garbage ();
656
657         /* reset dynamic state version back to default */
658         Stateful::loading_state_version = 0;
659
660         _butler->drop_references ();
661         delete _butler;
662         _butler = 0;
663
664         delete _all_route_group;
665
666         DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
667         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
668                 delete *i;
669         }
670
671         if (click_data != default_click) {
672                 delete [] click_data;
673         }
674
675         if (click_emphasis_data != default_click_emphasis) {
676                 delete [] click_emphasis_data;
677         }
678
679         clear_clicks ();
680
681         /* need to remove auditioner before monitoring section
682          * otherwise it is re-connected */
683         auditioner.reset ();
684
685         /* drop references to routes held by the monitoring section
686          * specifically _monitor_out aux/listen references */
687         remove_monitor_section();
688
689         /* clear out any pending dead wood from RCU managed objects */
690
691         routes.flush ();
692         _bundles.flush ();
693
694         AudioDiskstream::free_working_buffers();
695
696         /* tell everyone who is still standing that we're about to die */
697         drop_references ();
698
699         /* tell everyone to drop references and delete objects as we go */
700
701         DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
702         RegionFactory::delete_all_regions ();
703
704         /* Do this early so that VCAs no longer hold references to routes */
705
706         DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
707         delete _vca_manager;
708
709         DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
710
711         /* reset these three references to special routes before we do the usual route delete thing */
712
713         _master_out.reset ();
714         _monitor_out.reset ();
715
716         {
717                 RCUWriter<RouteList> writer (routes);
718                 boost::shared_ptr<RouteList> r = writer.get_copy ();
719
720                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
721                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
722                         (*i)->drop_references ();
723                 }
724
725                 r->clear ();
726                 /* writer goes out of scope and updates master */
727         }
728         routes.flush ();
729
730         {
731                 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
732                 Glib::Threads::Mutex::Lock lm (source_lock);
733                 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
734                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
735                         i->second->drop_references ();
736                 }
737
738                 sources.clear ();
739         }
740
741         /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
742         playlists.reset ();
743
744         emit_thread_terminate ();
745
746         pthread_cond_destroy (&_rt_emit_cond);
747         pthread_mutex_destroy (&_rt_emit_mutex);
748
749         pthread_cond_destroy (&_auto_connect_cond);
750         pthread_mutex_destroy (&_auto_connect_mutex);
751
752         delete _scene_changer; _scene_changer = 0;
753         delete midi_control_ui; midi_control_ui = 0;
754
755         delete _mmc; _mmc = 0;
756         delete _midi_ports; _midi_ports = 0;
757         delete _locations; _locations = 0;
758
759         delete midi_clock;
760         delete _tempo_map;
761
762         /* clear event queue, the session is gone, nobody is interested in
763          * those anymore, but they do leak memory if not removed
764          */
765         while (!immediate_events.empty ()) {
766                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
767                 SessionEvent *ev = immediate_events.front ();
768                 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
769                 immediate_events.pop_front ();
770                 bool remove = true;
771                 bool del = true;
772                 switch (ev->type) {
773                         case SessionEvent::AutoLoop:
774                         case SessionEvent::AutoLoopDeclick:
775                         case SessionEvent::Skip:
776                         case SessionEvent::PunchIn:
777                         case SessionEvent::PunchOut:
778                         case SessionEvent::StopOnce:
779                         case SessionEvent::RangeStop:
780                         case SessionEvent::RangeLocate:
781                                 remove = false;
782                                 del = false;
783                                 break;
784                         case SessionEvent::RealTimeOperation:
785                                 process_rtop (ev);
786                                 del = false;
787                         default:
788                                 break;
789                 }
790                 if (remove) {
791                         del = del && !_remove_event (ev);
792                 }
793                 if (del) {
794                         delete ev;
795                 }
796         }
797
798         DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
799
800         BOOST_SHOW_POINTERS ();
801 }
802
803 void
804 Session::setup_ltc ()
805 {
806         XMLNode* child = 0;
807
808         _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
809         _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
810
811         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
812                 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
813         } else {
814                 {
815                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
816                         _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
817                 }
818                 reconnect_ltc_input ();
819         }
820
821         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
822                 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
823         } else {
824                 {
825                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
826                         _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
827                 }
828                 reconnect_ltc_output ();
829         }
830
831         /* fix up names of LTC ports because we don't want the normal
832          * IO style of NAME/TYPE-{in,out}N
833          */
834
835         _ltc_input->nth (0)->set_name (X_("LTC-in"));
836         _ltc_output->nth (0)->set_name (X_("LTC-out"));
837 }
838
839 void
840 Session::setup_click ()
841 {
842         _clicking = false;
843
844         boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
845         boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
846
847         _click_io.reset (new ClickIO (*this, X_("Click")));
848         _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
849         _click_gain->activate ();
850         if (state_tree) {
851                 setup_click_state (state_tree->root());
852         } else {
853                 setup_click_state (0);
854         }
855 }
856
857 void
858 Session::setup_click_state (const XMLNode* node)
859 {
860         const XMLNode* child = 0;
861
862         if (node && (child = find_named_node (*node, "Click")) != 0) {
863
864                 /* existing state for Click */
865                 int c = 0;
866
867                 if (Stateful::loading_state_version < 3000) {
868                         c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
869                 } else {
870                         const XMLNodeList& children (child->children());
871                         XMLNodeList::const_iterator i = children.begin();
872                         if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
873                                 ++i;
874                                 if (i != children.end()) {
875                                         c = _click_gain->set_state (**i, Stateful::loading_state_version);
876                                 }
877                         }
878                 }
879
880                 if (c == 0) {
881                         _clicking = Config->get_clicking ();
882
883                 } else {
884
885                         error << _("could not setup Click I/O") << endmsg;
886                         _clicking = false;
887                 }
888
889
890         } else {
891
892                 /* default state for Click: dual-mono to first 2 physical outputs */
893
894                 vector<string> outs;
895                 _engine.get_physical_outputs (DataType::AUDIO, outs);
896
897                 for (uint32_t physport = 0; physport < 2; ++physport) {
898                         if (outs.size() > physport) {
899                                 if (_click_io->add_port (outs[physport], this)) {
900                                         // relax, even though its an error
901                                 }
902                         }
903                 }
904
905                 if (_click_io->n_ports () > ChanCount::ZERO) {
906                         _clicking = Config->get_clicking ();
907                 }
908         }
909 }
910
911 void
912 Session::setup_bundles ()
913 {
914
915         {
916                 RCUWriter<BundleList> writer (_bundles);
917                 boost::shared_ptr<BundleList> b = writer.get_copy ();
918                 for (BundleList::iterator i = b->begin(); i != b->end();) {
919                         if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
920                                 ++i;
921                                 continue;
922                         }
923                         i = b->erase(i);
924                 }
925         }
926
927         vector<string> inputs[DataType::num_types];
928         vector<string> outputs[DataType::num_types];
929         for (uint32_t i = 0; i < DataType::num_types; ++i) {
930                 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
931                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
932         }
933
934         /* Create a set of Bundle objects that map
935            to the physical I/O currently available.  We create both
936            mono and stereo bundles, so that the common cases of mono
937            and stereo tracks get bundles to put in their mixer strip
938            in / out menus.  There may be a nicer way of achieving that;
939            it doesn't really scale that well to higher channel counts
940         */
941
942         /* mono output bundles */
943
944         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
945                 char buf[64];
946                 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
947                 if (!pn.empty()) {
948                         snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
949                 } else {
950                         snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
951                 }
952
953                 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
954                 c->add_channel (_("mono"), DataType::AUDIO);
955                 c->set_port (0, outputs[DataType::AUDIO][np]);
956
957                 add_bundle (c, false);
958         }
959
960         /* stereo output bundles */
961
962         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
963                 if (np + 1 < outputs[DataType::AUDIO].size()) {
964                         char buf[32];
965                         snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
966                         boost::shared_ptr<Bundle> c (new Bundle (buf, true));
967                         c->add_channel (_("L"), DataType::AUDIO);
968                         c->set_port (0, outputs[DataType::AUDIO][np]);
969                         c->add_channel (_("R"), DataType::AUDIO);
970                         c->set_port (1, outputs[DataType::AUDIO][np + 1]);
971
972                         add_bundle (c, false);
973                 }
974         }
975
976         /* mono input bundles */
977
978         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
979                 char buf[64];
980                 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
981                 if (!pn.empty()) {
982                         snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
983                 } else {
984                         snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
985                 }
986
987                 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
988                 c->add_channel (_("mono"), DataType::AUDIO);
989                 c->set_port (0, inputs[DataType::AUDIO][np]);
990
991                 add_bundle (c, false);
992         }
993
994         /* stereo input bundles */
995
996         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
997                 if (np + 1 < inputs[DataType::AUDIO].size()) {
998                         char buf[32];
999                         snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1000
1001                         boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1002                         c->add_channel (_("L"), DataType::AUDIO);
1003                         c->set_port (0, inputs[DataType::AUDIO][np]);
1004                         c->add_channel (_("R"), DataType::AUDIO);
1005                         c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1006
1007                         add_bundle (c, false);
1008                 }
1009         }
1010
1011         /* MIDI input bundles */
1012
1013         for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1014                 string n = inputs[DataType::MIDI][np];
1015                 std::string pn = _engine.get_pretty_name_by_name (n);
1016                 if (!pn.empty()) {
1017                         n = pn;
1018                 } else {
1019                         boost::erase_first (n, X_("alsa_pcm:"));
1020                 }
1021                 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1022                 c->add_channel ("", DataType::MIDI);
1023                 c->set_port (0, inputs[DataType::MIDI][np]);
1024                 add_bundle (c, false);
1025         }
1026
1027         /* MIDI output bundles */
1028
1029         for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1030                 string n = outputs[DataType::MIDI][np];
1031                 std::string pn = _engine.get_pretty_name_by_name (n);
1032                 if (!pn.empty()) {
1033                         n = pn;
1034                 } else {
1035                         boost::erase_first (n, X_("alsa_pcm:"));
1036                 }
1037                 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1038                 c->add_channel ("", DataType::MIDI);
1039                 c->set_port (0, outputs[DataType::MIDI][np]);
1040                 add_bundle (c, false);
1041         }
1042
1043         // we trust the backend to only calls us if there's a change
1044         BundleAddedOrRemoved (); /* EMIT SIGNAL */
1045 }
1046
1047 void
1048 Session::auto_connect_master_bus ()
1049 {
1050         if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1051                 return;
1052         }
1053
1054         // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1055         // In this case it means "Multi Out" output mode
1056         if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1057                 return;
1058         }
1059
1060         /* if requested auto-connect the outputs to the first N physical ports.
1061          */
1062
1063         uint32_t limit = _master_out->n_outputs().n_total();
1064         vector<string> outputs[DataType::num_types];
1065
1066         for (uint32_t i = 0; i < DataType::num_types; ++i) {
1067                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1068         }
1069
1070         for (uint32_t n = 0; n < limit; ++n) {
1071                 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1072                 string connect_to;
1073                 if (outputs[p->type()].size() > n) {
1074                         connect_to = outputs[p->type()][n];
1075                 }
1076
1077                 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1078                         if (_master_out->output()->connect (p, connect_to, this)) {
1079                                 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1080                                       << endmsg;
1081                                 break;
1082                         }
1083                 }
1084         }
1085 }
1086
1087 void
1088 Session::remove_monitor_section ()
1089 {
1090         if (!_monitor_out || Profile->get_trx()) {
1091                 return;
1092         }
1093
1094         /* force reversion to Solo-In-Place */
1095         Config->set_solo_control_is_listen_control (false);
1096
1097         /* if we are auditioning, cancel it ... this is a workaround
1098            to a problem (auditioning does not execute the process graph,
1099            which is needed to remove routes when using >1 core for processing)
1100         */
1101         cancel_audition ();
1102
1103         {
1104                 /* Hold process lock while doing this so that we don't hear bits and
1105                  * pieces of audio as we work on each route.
1106                  */
1107
1108                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1109
1110                 /* Connect tracks to monitor section. Note that in an
1111                    existing session, the internal sends will already exist, but we want the
1112                    routes to notice that they connect to the control out specifically.
1113                 */
1114
1115
1116                 boost::shared_ptr<RouteList> r = routes.reader ();
1117                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1118
1119                 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1120
1121                         if ((*x)->is_monitor()) {
1122                                 /* relax */
1123                         } else if ((*x)->is_master()) {
1124                                 /* relax */
1125                         } else {
1126                                 (*x)->remove_aux_or_listen (_monitor_out);
1127                         }
1128                 }
1129         }
1130
1131         remove_route (_monitor_out);
1132         if (_state_of_the_state & Deletion) {
1133                 return;
1134         }
1135
1136         auto_connect_master_bus ();
1137
1138         if (auditioner) {
1139                 auditioner->connect ();
1140         }
1141
1142         Config->ParameterChanged ("use-monitor-bus");
1143 }
1144
1145 void
1146 Session::add_monitor_section ()
1147 {
1148         RouteList rl;
1149
1150         if (_monitor_out || !_master_out || Profile->get_trx()) {
1151                 return;
1152         }
1153
1154         boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1155
1156         if (r->init ()) {
1157                 return;
1158         }
1159
1160         BOOST_MARK_ROUTE(r);
1161
1162         try {
1163                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1164                 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1165                 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1166         } catch (...) {
1167                 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1168                 return;
1169         }
1170
1171         rl.push_back (r);
1172         add_routes (rl, false, false, false, 0);
1173
1174         assert (_monitor_out);
1175
1176         /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1177            are undefined, at best.
1178         */
1179
1180         uint32_t limit = _monitor_out->n_inputs().n_audio();
1181
1182         if (_master_out) {
1183
1184                 /* connect the inputs to the master bus outputs. this
1185                  * represents a separate data feed from the internal sends from
1186                  * each route. as of jan 2011, it allows the monitor section to
1187                  * conditionally ignore either the internal sends or the normal
1188                  * input feed, but we should really find a better way to do
1189                  * this, i think.
1190                  */
1191
1192                 _master_out->output()->disconnect (this);
1193
1194                 for (uint32_t n = 0; n < limit; ++n) {
1195                         boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1196                         boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1197
1198                         if (o) {
1199                                 string connect_to = o->name();
1200                                 if (_monitor_out->input()->connect (p, connect_to, this)) {
1201                                         error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1202                                               << endmsg;
1203                                         break;
1204                                 }
1205                         }
1206                 }
1207         }
1208
1209         /* if monitor section is not connected, connect it to physical outs
1210          */
1211
1212         if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1213
1214                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1215
1216                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1217
1218                         if (b) {
1219                                 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1220                         } else {
1221                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1222                                                            Config->get_monitor_bus_preferred_bundle())
1223                                         << endmsg;
1224                         }
1225
1226                 } else {
1227
1228                         /* Monitor bus is audio only */
1229
1230                         vector<string> outputs[DataType::num_types];
1231
1232                         for (uint32_t i = 0; i < DataType::num_types; ++i) {
1233                                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1234                         }
1235
1236                         uint32_t mod = outputs[DataType::AUDIO].size();
1237                         uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1238
1239                         if (mod != 0) {
1240
1241                                 for (uint32_t n = 0; n < limit; ++n) {
1242
1243                                         boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1244                                         string connect_to;
1245                                         if (outputs[DataType::AUDIO].size() > (n % mod)) {
1246                                                 connect_to = outputs[DataType::AUDIO][n % mod];
1247                                         }
1248
1249                                         if (!connect_to.empty()) {
1250                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
1251                                                         error << string_compose (
1252                                                                 _("cannot connect control output %1 to %2"),
1253                                                                 n, connect_to)
1254                                                               << endmsg;
1255                                                         break;
1256                                                 }
1257                                         }
1258                                 }
1259                         }
1260                 }
1261         }
1262
1263         /* Hold process lock while doing this so that we don't hear bits and
1264          * pieces of audio as we work on each route.
1265          */
1266
1267         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1268
1269         /* Connect tracks to monitor section. Note that in an
1270            existing session, the internal sends will already exist, but we want the
1271            routes to notice that they connect to the control out specifically.
1272         */
1273
1274
1275         boost::shared_ptr<RouteList> rls = routes.reader ();
1276
1277         PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1278
1279         for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1280
1281                 if ((*x)->is_monitor()) {
1282                         /* relax */
1283                 } else if ((*x)->is_master()) {
1284                         /* relax */
1285                 } else {
1286                         (*x)->enable_monitor_send ();
1287                 }
1288         }
1289
1290         if (auditioner) {
1291                 auditioner->connect ();
1292         }
1293         Config->ParameterChanged ("use-monitor-bus");
1294 }
1295
1296 void
1297 Session::reset_monitor_section ()
1298 {
1299         /* Process lock should be held by the caller.*/
1300
1301         if (!_monitor_out || Profile->get_trx()) {
1302                 return;
1303         }
1304
1305         uint32_t limit = _master_out->n_outputs().n_audio();
1306
1307         /* connect the inputs to the master bus outputs. this
1308          * represents a separate data feed from the internal sends from
1309          * each route. as of jan 2011, it allows the monitor section to
1310          * conditionally ignore either the internal sends or the normal
1311          * input feed, but we should really find a better way to do
1312          * this, i think.
1313          */
1314
1315         _master_out->output()->disconnect (this);
1316         _monitor_out->output()->disconnect (this);
1317
1318         // monitor section follow master bus - except midi
1319         ChanCount mon_chn (_master_out->output()->n_ports());
1320         mon_chn.set_midi (0);
1321
1322         _monitor_out->input()->ensure_io (mon_chn, false, this);
1323         _monitor_out->output()->ensure_io (mon_chn, false, this);
1324
1325         for (uint32_t n = 0; n < limit; ++n) {
1326                 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1327                 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1328
1329                 if (o) {
1330                         string connect_to = o->name();
1331                         if (_monitor_out->input()->connect (p, connect_to, this)) {
1332                                 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1333                                       << endmsg;
1334                                 break;
1335                         }
1336                 }
1337         }
1338
1339         /* connect monitor section to physical outs
1340          */
1341
1342         if (Config->get_auto_connect_standard_busses()) {
1343
1344                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1345
1346                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1347
1348                         if (b) {
1349                                 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1350                         } else {
1351                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1352                                                            Config->get_monitor_bus_preferred_bundle())
1353                                         << endmsg;
1354                         }
1355
1356                 } else {
1357
1358                         /* Monitor bus is audio only */
1359
1360                         vector<string> outputs[DataType::num_types];
1361
1362                         for (uint32_t i = 0; i < DataType::num_types; ++i) {
1363                                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1364                         }
1365
1366                         uint32_t mod = outputs[DataType::AUDIO].size();
1367                         uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1368
1369                         if (mod != 0) {
1370
1371                                 for (uint32_t n = 0; n < limit; ++n) {
1372
1373                                         boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1374                                         string connect_to;
1375                                         if (outputs[DataType::AUDIO].size() > (n % mod)) {
1376                                                 connect_to = outputs[DataType::AUDIO][n % mod];
1377                                         }
1378
1379                                         if (!connect_to.empty()) {
1380                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
1381                                                         error << string_compose (
1382                                                                 _("cannot connect control output %1 to %2"),
1383                                                                 n, connect_to)
1384                                                               << endmsg;
1385                                                         break;
1386                                                 }
1387                                         }
1388                                 }
1389                         }
1390                 }
1391         }
1392
1393         /* Connect tracks to monitor section. Note that in an
1394            existing session, the internal sends will already exist, but we want the
1395            routes to notice that they connect to the control out specifically.
1396         */
1397
1398
1399         boost::shared_ptr<RouteList> rls = routes.reader ();
1400
1401         PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1402
1403         for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1404
1405                 if ((*x)->is_monitor()) {
1406                         /* relax */
1407                 } else if ((*x)->is_master()) {
1408                         /* relax */
1409                 } else {
1410                         (*x)->enable_monitor_send ();
1411                 }
1412         }
1413 }
1414
1415 void
1416 Session::hookup_io ()
1417 {
1418         /* stop graph reordering notifications from
1419            causing resorts, etc.
1420         */
1421
1422         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1423
1424         if (!auditioner) {
1425
1426                 /* we delay creating the auditioner till now because
1427                    it makes its own connections to ports.
1428                 */
1429
1430                 try {
1431                         boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1432                         if (a->init()) {
1433                                 throw failed_constructor ();
1434                         }
1435                         a->use_new_diskstream ();
1436                         auditioner = a;
1437                 }
1438
1439                 catch (failed_constructor& err) {
1440                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1441                 }
1442         }
1443
1444         /* load bundles, which we may have postponed earlier on */
1445         if (_bundle_xml_node) {
1446                 load_bundles (*_bundle_xml_node);
1447                 delete _bundle_xml_node;
1448         }
1449
1450         /* Tell all IO objects to connect themselves together */
1451
1452         IO::enable_connecting ();
1453
1454         /* Now tell all "floating" ports to connect to whatever
1455            they should be connected to.
1456         */
1457
1458         AudioEngine::instance()->reconnect_ports ();
1459
1460         /* Anyone who cares about input state, wake up and do something */
1461
1462         IOConnectionsComplete (); /* EMIT SIGNAL */
1463
1464         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1465
1466         /* now handle the whole enchilada as if it was one
1467            graph reorder event.
1468         */
1469
1470         graph_reordered ();
1471
1472         /* update the full solo state, which can't be
1473            correctly determined on a per-route basis, but
1474            needs the global overview that only the session
1475            has.
1476         */
1477
1478         update_route_solo_state ();
1479 }
1480
1481 void
1482 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1483 {
1484         boost::shared_ptr<Track> track = wp.lock ();
1485         if (!track) {
1486                 return;
1487         }
1488
1489         boost::shared_ptr<Playlist> playlist;
1490
1491         if ((playlist = track->playlist()) != 0) {
1492                 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1493                 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1494                 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1495         }
1496 }
1497
1498 bool
1499 Session::record_enabling_legal () const
1500 {
1501         /* this used to be in here, but survey says.... we don't need to restrict it */
1502         // if (record_status() == Recording) {
1503         //      return false;
1504         // }
1505
1506         if (Config->get_all_safe()) {
1507                 return false;
1508         }
1509         return true;
1510 }
1511
1512 void
1513 Session::set_track_monitor_input_status (bool yn)
1514 {
1515         boost::shared_ptr<RouteList> rl = routes.reader ();
1516         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1517                 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1518                 if (tr && tr->rec_enable_control()->get_value()) {
1519                         //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1520                         tr->request_input_monitoring (yn);
1521                 }
1522         }
1523 }
1524
1525 void
1526 Session::auto_punch_start_changed (Location* location)
1527 {
1528         replace_event (SessionEvent::PunchIn, location->start());
1529
1530         if (get_record_enabled() && config.get_punch_in()) {
1531                 /* capture start has been changed, so save new pending state */
1532                 save_state ("", true);
1533         }
1534 }
1535
1536 void
1537 Session::auto_punch_end_changed (Location* location)
1538 {
1539         framepos_t when_to_stop = location->end();
1540         // when_to_stop += _worst_output_latency + _worst_input_latency;
1541         replace_event (SessionEvent::PunchOut, when_to_stop);
1542 }
1543
1544 void
1545 Session::auto_punch_changed (Location* location)
1546 {
1547         framepos_t when_to_stop = location->end();
1548
1549         replace_event (SessionEvent::PunchIn, location->start());
1550         //when_to_stop += _worst_output_latency + _worst_input_latency;
1551         replace_event (SessionEvent::PunchOut, when_to_stop);
1552 }
1553
1554 /** @param loc A loop location.
1555  *  @param pos Filled in with the start time of the required fade-out (in session frames).
1556  *  @param length Filled in with the length of the required fade-out.
1557  */
1558 void
1559 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1560 {
1561         pos = max (loc->start(), loc->end() - 64);
1562         length = loc->end() - pos;
1563 }
1564
1565 void
1566 Session::auto_loop_changed (Location* location)
1567 {
1568         replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1569         framepos_t dcp;
1570         framecnt_t dcl;
1571         auto_loop_declick_range (location, dcp, dcl);
1572
1573         if (transport_rolling() && play_loop) {
1574
1575                 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1576
1577                 // if (_transport_frame > location->end()) {
1578
1579                 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1580                         // relocate to beginning of loop
1581                         clear_events (SessionEvent::LocateRoll);
1582
1583                         request_locate (location->start(), true);
1584
1585                 }
1586                 else if (Config->get_seamless_loop() && !loop_changing) {
1587
1588                         // schedule a locate-roll to refill the diskstreams at the
1589                         // previous loop end
1590                         loop_changing = true;
1591
1592                         if (location->end() > last_loopend) {
1593                                 clear_events (SessionEvent::LocateRoll);
1594                                 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1595                                 queue_event (ev);
1596                         }
1597
1598                 }
1599         } else {
1600                 clear_events (SessionEvent::AutoLoopDeclick);
1601                 clear_events (SessionEvent::AutoLoop);
1602         }
1603
1604         /* possibly move playhead if not rolling; if we are rolling we'll move
1605            to the loop start on stop if that is appropriate.
1606          */
1607
1608         framepos_t pos;
1609
1610         if (!transport_rolling() && select_playhead_priority_target (pos)) {
1611                 if (pos == location->start()) {
1612                         request_locate (pos);
1613                 }
1614         }
1615
1616
1617         last_loopend = location->end();
1618         set_dirty ();
1619 }
1620
1621 void
1622 Session::set_auto_punch_location (Location* location)
1623 {
1624         Location* existing;
1625
1626         if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1627                 punch_connections.drop_connections();
1628                 existing->set_auto_punch (false, this);
1629                 remove_event (existing->start(), SessionEvent::PunchIn);
1630                 clear_events (SessionEvent::PunchOut);
1631                 auto_punch_location_changed (0);
1632         }
1633
1634         set_dirty();
1635
1636         if (location == 0) {
1637                 return;
1638         }
1639
1640         if (location->end() <= location->start()) {
1641                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1642                 return;
1643         }
1644
1645         punch_connections.drop_connections ();
1646
1647         location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1648         location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1649         location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1650
1651         location->set_auto_punch (true, this);
1652
1653         auto_punch_changed (location);
1654
1655         auto_punch_location_changed (location);
1656 }
1657
1658 void
1659 Session::set_session_extents (framepos_t start, framepos_t end)
1660 {
1661         Location* existing;
1662         if ((existing = _locations->session_range_location()) == 0) {
1663                 //if there is no existing session, we need to make a new session location  (should never happen)
1664                 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1665         }
1666
1667         if (end <= start) {
1668                 error << _("Session: you can't use that location for session start/end)") << endmsg;
1669                 return;
1670         }
1671
1672         existing->set( start, end );
1673
1674         set_dirty();
1675 }
1676
1677 void
1678 Session::set_auto_loop_location (Location* location)
1679 {
1680         Location* existing;
1681
1682         if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1683                 loop_connections.drop_connections ();
1684                 existing->set_auto_loop (false, this);
1685                 remove_event (existing->end(), SessionEvent::AutoLoop);
1686                 framepos_t dcp;
1687                 framecnt_t dcl;
1688                 auto_loop_declick_range (existing, dcp, dcl);
1689                 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1690                 auto_loop_location_changed (0);
1691         }
1692
1693         set_dirty();
1694
1695         if (location == 0) {
1696                 return;
1697         }
1698
1699         if (location->end() <= location->start()) {
1700                 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1701                 return;
1702         }
1703
1704         last_loopend = location->end();
1705
1706         loop_connections.drop_connections ();
1707
1708         location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1709         location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1710         location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1711         location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1712
1713         location->set_auto_loop (true, this);
1714
1715         if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1716                 // set all tracks to use internal looping
1717                 boost::shared_ptr<RouteList> rl = routes.reader ();
1718                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1719                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1720                         if (tr && !tr->hidden()) {
1721                                 tr->set_loop (location);
1722                         }
1723                 }
1724         }
1725
1726         /* take care of our stuff first */
1727
1728         auto_loop_changed (location);
1729
1730         /* now tell everyone else */
1731
1732         auto_loop_location_changed (location);
1733 }
1734
1735 void
1736 Session::update_marks (Location*)
1737 {
1738         set_dirty ();
1739 }
1740
1741 void
1742 Session::update_skips (Location* loc, bool consolidate)
1743 {
1744         if (_ignore_skips_updates) {
1745                 return;
1746         }
1747
1748         Locations::LocationList skips;
1749
1750         if (consolidate) {
1751                 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1752                 consolidate_skips (loc);
1753         }
1754
1755         sync_locations_to_skips ();
1756
1757         set_dirty ();
1758 }
1759
1760 void
1761 Session::consolidate_skips (Location* loc)
1762 {
1763         Locations::LocationList all_locations = _locations->list ();
1764
1765         for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1766
1767                 if (!(*l)->is_skip ()) {
1768                         ++l;
1769                         continue;
1770                 }
1771
1772                 /* don't test against self */
1773
1774                 if (*l == loc) {
1775                         ++l;
1776                         continue;
1777                 }
1778
1779                 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1780                 case Evoral::OverlapInternal:
1781                 case Evoral::OverlapExternal:
1782                 case Evoral::OverlapStart:
1783                 case Evoral::OverlapEnd:
1784                         /* adjust new location to cover existing one */
1785                         loc->set_start (min (loc->start(), (*l)->start()));
1786                         loc->set_end (max (loc->end(), (*l)->end()));
1787                         /* we don't need this one any more */
1788                         _locations->remove (*l);
1789                         /* the location has been deleted, so remove reference to it in our local list */
1790                         l = all_locations.erase (l);
1791                         break;
1792
1793                 case Evoral::OverlapNone:
1794                         ++l;
1795                         break;
1796                 }
1797         }
1798 }
1799
1800 void
1801 Session::sync_locations_to_skips ()
1802 {
1803         /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1804          * Session::_sync_locations_to_skips() from the audioengine thread.
1805          */
1806         clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1807 }
1808
1809 void
1810 Session::_sync_locations_to_skips ()
1811 {
1812         /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1813
1814         Locations::LocationList const & locs (_locations->list());
1815
1816         for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1817
1818                 Location* location = *i;
1819
1820                 if (location->is_skip() && location->is_skipping()) {
1821                         SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1822                         queue_event (ev);
1823                 }
1824         }
1825 }
1826
1827
1828 void
1829 Session::location_added (Location *location)
1830 {
1831         if (location->is_auto_punch()) {
1832                 set_auto_punch_location (location);
1833         }
1834
1835         if (location->is_auto_loop()) {
1836                 set_auto_loop_location (location);
1837         }
1838
1839         if (location->is_session_range()) {
1840                 /* no need for any signal handling or event setting with the session range,
1841                    because we keep a direct reference to it and use its start/end directly.
1842                 */
1843                 _session_range_location = location;
1844         }
1845
1846         if (location->is_mark()) {
1847                 /* listen for per-location signals that require us to do any * global updates for marks */
1848
1849                 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1850                 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1851                 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1852                 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1853         }
1854
1855         if (location->is_skip()) {
1856                 /* listen for per-location signals that require us to update skip-locate events */
1857
1858                 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1859                 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1860                 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1861                 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1862
1863                 update_skips (location, true);
1864         }
1865
1866         set_dirty ();
1867 }
1868
1869 void
1870 Session::location_removed (Location *location)
1871 {
1872         if (location->is_auto_loop()) {
1873                 set_auto_loop_location (0);
1874                 set_track_loop (false);
1875         }
1876
1877         if (location->is_auto_punch()) {
1878                 set_auto_punch_location (0);
1879         }
1880
1881         if (location->is_session_range()) {
1882                 /* this is never supposed to happen */
1883                 error << _("programming error: session range removed!") << endl;
1884         }
1885
1886         if (location->is_skip()) {
1887
1888                 update_skips (location, false);
1889         }
1890
1891         set_dirty ();
1892 }
1893
1894 void
1895 Session::locations_changed ()
1896 {
1897         _locations->apply (*this, &Session::_locations_changed);
1898 }
1899
1900 void
1901 Session::_locations_changed (const Locations::LocationList& locations)
1902 {
1903         /* There was some mass-change in the Locations object.
1904
1905            We might be re-adding a location here but it doesn't actually matter
1906            for all the locations that the Session takes an interest in.
1907         */
1908
1909         {
1910                 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1911                 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1912                         location_added (*i);
1913                 }
1914         }
1915
1916         update_skips (NULL, false);
1917 }
1918
1919 void
1920 Session::enable_record ()
1921 {
1922         if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1923                 /* no recording at anything except normal speed */
1924                 return;
1925         }
1926
1927         while (1) {
1928                 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1929
1930                 if (rs == Recording) {
1931                         break;
1932                 }
1933
1934                 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1935
1936                         _last_record_location = _transport_frame;
1937                         send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1938
1939                         if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1940                                 set_track_monitor_input_status (true);
1941                         }
1942
1943                         RecordStateChanged ();
1944                         break;
1945                 }
1946         }
1947 }
1948
1949 void
1950 Session::set_all_tracks_record_enabled (bool enable )
1951 {
1952         boost::shared_ptr<RouteList> rl = routes.reader();
1953         set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1954 }
1955
1956 void
1957 Session::disable_record (bool rt_context, bool force)
1958 {
1959         RecordState rs;
1960
1961         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1962
1963                 if (!Config->get_latched_record_enable () || force) {
1964                         g_atomic_int_set (&_record_status, Disabled);
1965                         send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1966                 } else {
1967                         if (rs == Recording) {
1968                                 g_atomic_int_set (&_record_status, Enabled);
1969                         }
1970                 }
1971
1972                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1973                         set_track_monitor_input_status (false);
1974                 }
1975
1976                 RecordStateChanged (); /* emit signal */
1977
1978                 if (!rt_context) {
1979                         remove_pending_capture_state ();
1980                 }
1981         }
1982 }
1983
1984 void
1985 Session::step_back_from_record ()
1986 {
1987         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1988
1989                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1990                         set_track_monitor_input_status (false);
1991                 }
1992
1993                 RecordStateChanged (); /* emit signal */
1994         }
1995 }
1996
1997 void
1998 Session::maybe_enable_record ()
1999 {
2000         if (_step_editors > 0) {
2001                 return;
2002         }
2003
2004         g_atomic_int_set (&_record_status, Enabled);
2005
2006         /* This function is currently called from somewhere other than an RT thread.
2007            This save_state() call therefore doesn't impact anything.  Doing it here
2008            means that we save pending state of which sources the next record will use,
2009            which gives us some chance of recovering from a crash during the record.
2010         */
2011
2012         save_state ("", true);
2013
2014         if (_transport_speed) {
2015                 if (!config.get_punch_in()) {
2016                         enable_record ();
2017                 }
2018         } else {
2019                 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2020                 RecordStateChanged (); /* EMIT SIGNAL */
2021         }
2022
2023         set_dirty();
2024 }
2025
2026 framepos_t
2027 Session::audible_frame () const
2028 {
2029         framepos_t ret;
2030         framepos_t tf;
2031         framecnt_t offset;
2032
2033         offset = worst_playback_latency ();
2034
2035         if (synced_to_engine()) {
2036                 /* Note: this is basically just sync-to-JACK */
2037                 tf = _engine.transport_frame();
2038         } else {
2039                 tf = _transport_frame;
2040         }
2041
2042         ret = tf;
2043
2044         if (!non_realtime_work_pending()) {
2045
2046                 /* MOVING */
2047
2048                 /* Check to see if we have passed the first guaranteed
2049                    audible frame past our last start position. if not,
2050                    return that last start point because in terms
2051                    of audible frames, we have not moved yet.
2052
2053                    `Start position' in this context means the time we last
2054                    either started, located, or changed transport direction.
2055                 */
2056
2057                 if (_transport_speed > 0.0f) {
2058
2059                         if (!play_loop || !have_looped) {
2060                                 if (tf < _last_roll_or_reversal_location + offset) {
2061                                         return _last_roll_or_reversal_location;
2062                                 }
2063                         }
2064
2065
2066                         /* forwards */
2067                         ret -= offset;
2068
2069                 } else if (_transport_speed < 0.0f) {
2070
2071                         /* XXX wot? no backward looping? */
2072
2073                         if (tf > _last_roll_or_reversal_location - offset) {
2074                                 return _last_roll_or_reversal_location;
2075                         } else {
2076                                 /* backwards */
2077                                 ret += offset;
2078                         }
2079                 }
2080         }
2081
2082         return ret;
2083 }
2084
2085 void
2086 Session::set_frame_rate (framecnt_t frames_per_second)
2087 {
2088         /** \fn void Session::set_frame_size(framecnt_t)
2089                 the AudioEngine object that calls this guarantees
2090                 that it will not be called while we are also in
2091                 ::process(). Its fine to do things that block
2092                 here.
2093         */
2094
2095         if (_base_frame_rate == 0) {
2096                 _base_frame_rate = frames_per_second;
2097         }
2098         else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2099                 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2100         }
2101         _nominal_frame_rate = frames_per_second;
2102
2103         sync_time_vars();
2104
2105         clear_clicks ();
2106         reset_write_sources (false);
2107
2108         // XXX we need some equivalent to this, somehow
2109         // SndFileSource::setup_standard_crossfades (frames_per_second);
2110
2111         set_dirty();
2112
2113         /* XXX need to reset/reinstantiate all LADSPA plugins */
2114 }
2115
2116 void
2117 Session::set_block_size (pframes_t nframes)
2118 {
2119         /* the AudioEngine guarantees
2120            that it will not be called while we are also in
2121            ::process(). It is therefore fine to do things that block
2122            here.
2123         */
2124
2125         {
2126                 current_block_size = nframes;
2127
2128                 ensure_buffers ();
2129
2130                 boost::shared_ptr<RouteList> r = routes.reader ();
2131
2132                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2133                         (*i)->set_block_size (nframes);
2134                 }
2135
2136                 boost::shared_ptr<RouteList> rl = routes.reader ();
2137                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2138                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2139                         if (tr) {
2140                                 tr->set_block_size (nframes);
2141                         }
2142                 }
2143
2144                 set_worst_io_latencies ();
2145         }
2146 }
2147
2148
2149 static void
2150 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2151 {
2152         boost::shared_ptr<Route> r2;
2153
2154         if (r1->feeds (rbase) && rbase->feeds (r1)) {
2155                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2156                 return;
2157         }
2158
2159         /* make a copy of the existing list of routes that feed r1 */
2160
2161         Route::FedBy existing (r1->fed_by());
2162
2163         /* for each route that feeds r1, recurse, marking it as feeding
2164            rbase as well.
2165         */
2166
2167         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2168                 if (!(r2 = i->r.lock ())) {
2169                         /* (*i) went away, ignore it */
2170                         continue;
2171                 }
2172
2173                 /* r2 is a route that feeds r1 which somehow feeds base. mark
2174                    base as being fed by r2
2175                 */
2176
2177                 rbase->add_fed_by (r2, i->sends_only);
2178
2179                 if (r2 != rbase) {
2180
2181                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2182                            stop here.
2183                         */
2184
2185                         if (r1->feeds (r2) && r2->feeds (r1)) {
2186                                 continue;
2187                         }
2188
2189                         /* now recurse, so that we can mark base as being fed by
2190                            all routes that feed r2
2191                         */
2192
2193                         trace_terminal (r2, rbase);
2194                 }
2195
2196         }
2197 }
2198
2199 void
2200 Session::resort_routes ()
2201 {
2202         /* don't do anything here with signals emitted
2203            by Routes during initial setup or while we
2204            are being destroyed.
2205         */
2206
2207         if (_state_of_the_state & (InitialConnecting | Deletion)) {
2208                 return;
2209         }
2210
2211         if (_route_deletion_in_progress) {
2212                 return;
2213         }
2214
2215         {
2216                 RCUWriter<RouteList> writer (routes);
2217                 boost::shared_ptr<RouteList> r = writer.get_copy ();
2218                 resort_routes_using (r);
2219                 /* writer goes out of scope and forces update */
2220         }
2221
2222 #ifndef NDEBUG
2223         if (DEBUG_ENABLED(DEBUG::Graph)) {
2224                 boost::shared_ptr<RouteList> rl = routes.reader ();
2225                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2226                         DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2227
2228                         const Route::FedBy& fb ((*i)->fed_by());
2229
2230                         for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2231                                 boost::shared_ptr<Route> sf = f->r.lock();
2232                                 if (sf) {
2233                                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2234                                 }
2235                         }
2236                 }
2237         }
2238 #endif
2239
2240 }
2241
2242 /** This is called whenever we need to rebuild the graph of how we will process
2243  *  routes.
2244  *  @param r List of routes, in any order.
2245  */
2246
2247 void
2248 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2249 {
2250         /* We are going to build a directed graph of our routes;
2251            this is where the edges of that graph are put.
2252         */
2253
2254         GraphEdges edges;
2255
2256         /* Go through all routes doing two things:
2257          *
2258          * 1. Collect the edges of the route graph.  Each of these edges
2259          *    is a pair of routes, one of which directly feeds the other
2260          *    either by a JACK connection or by an internal send.
2261          *
2262          * 2. Begin the process of making routes aware of which other
2263          *    routes directly or indirectly feed them.  This information
2264          *    is used by the solo code.
2265          */
2266
2267         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2268
2269                 /* Clear out the route's list of direct or indirect feeds */
2270                 (*i)->clear_fed_by ();
2271
2272                 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2273
2274                         bool via_sends_only;
2275
2276                         /* See if this *j feeds *i according to the current state of the JACK
2277                            connections and internal sends.
2278                         */
2279                         if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2280                                 /* add the edge to the graph (part #1) */
2281                                 edges.add (*j, *i, via_sends_only);
2282                                 /* tell the route (for part #2) */
2283                                 (*i)->add_fed_by (*j, via_sends_only);
2284                         }
2285                 }
2286         }
2287
2288         /* Attempt a topological sort of the route graph */
2289         boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2290
2291         if (sorted_routes) {
2292                 /* We got a satisfactory topological sort, so there is no feedback;
2293                    use this new graph.
2294
2295                    Note: the process graph rechain does not require a
2296                    topologically-sorted list, but hey ho.
2297                 */
2298                 if (_process_graph) {
2299                         _process_graph->rechain (sorted_routes, edges);
2300                 }
2301
2302                 _current_route_graph = edges;
2303
2304                 /* Complete the building of the routes' lists of what directly
2305                    or indirectly feeds them.
2306                 */
2307                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2308                         trace_terminal (*i, *i);
2309                 }
2310
2311                 *r = *sorted_routes;
2312
2313 #ifndef NDEBUG
2314                 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2315                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2316                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2317                 }
2318 #endif
2319
2320                 SuccessfulGraphSort (); /* EMIT SIGNAL */
2321
2322         } else {
2323                 /* The topological sort failed, so we have a problem.  Tell everyone
2324                    and stick to the old graph; this will continue to be processed, so
2325                    until the feedback is fixed, what is played back will not quite
2326                    reflect what is actually connected.  Note also that we do not
2327                    do trace_terminal here, as it would fail due to an endless recursion,
2328                    so the solo code will think that everything is still connected
2329                    as it was before.
2330                 */
2331
2332                 FeedbackDetected (); /* EMIT SIGNAL */
2333         }
2334
2335 }
2336
2337 /** Find a route name starting with \a base, maybe followed by the
2338  *  lowest \a id.  \a id will always be added if \a definitely_add_number
2339  *  is true on entry; otherwise it will only be added if required
2340  *  to make the name unique.
2341  *
2342  *  Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2343  *  The available route name with the lowest ID will be used, and \a id
2344  *  will be set to the ID.
2345  *
2346  *  \return false if a route name could not be found, and \a track_name
2347  *  and \a id do not reflect a free route name.
2348  */
2349 bool
2350 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2351 {
2352         /* the base may conflict with ports that do not belong to existing
2353            routes, but hidden objects like the click track. So check port names
2354            before anything else.
2355         */
2356
2357         for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2358                 if (base == *reserved) {
2359                         /* Check if this reserved name already exists, and if
2360                            so, disallow it without a numeric suffix.
2361                         */
2362                         if (route_by_name (*reserved)) {
2363                                 definitely_add_number = true;
2364                                 if (id < 1) {
2365                                         id = 1;
2366                                 }
2367                         }
2368                         break;
2369                 }
2370         }
2371
2372         if (!definitely_add_number && route_by_name (base) == 0) {
2373                 /* juse use the base */
2374                 name = base;
2375                 return true;
2376         }
2377
2378         do {
2379                 name = string_compose ("%1 %2", base, id);
2380
2381                 if (route_by_name (name) == 0) {
2382                         return true;
2383                 }
2384
2385                 ++id;
2386
2387         } while (id < (UINT_MAX-1));
2388
2389         return false;
2390 }
2391
2392 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2393 void
2394 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2395 {
2396         in  = ChanCount::ZERO;
2397         out = ChanCount::ZERO;
2398
2399         boost::shared_ptr<RouteList> r = routes.reader ();
2400
2401         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2402                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2403                 if (tr && !tr->is_auditioner()) {
2404                         in  += tr->n_inputs();
2405                         out += tr->n_outputs();
2406                 }
2407         }
2408 }
2409
2410 string
2411 Session::default_track_name_pattern (DataType t)
2412 {
2413         switch (t) {
2414         case DataType::AUDIO:
2415                 if (Profile->get_trx()) {
2416                         return _("Track ");
2417                 } else {
2418                         return _("Audio ");
2419                 }
2420                 break;
2421
2422         case DataType::MIDI:
2423                 return _("MIDI ");
2424         }
2425
2426         return "";
2427 }
2428
2429 /** Caller must not hold process lock
2430  *  @param name_template string to use for the start of the name, or "" to use "MIDI".
2431  *  @param instrument plugin info for the instrument to insert pre-fader, if any
2432  */
2433 list<boost::shared_ptr<MidiTrack> >
2434 Session::new_midi_track (const ChanCount& input, const ChanCount& output,
2435                          boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2436                          RouteGroup* route_group, uint32_t how_many, string name_template, PresentationInfo::order_t order,
2437                          TrackMode mode)
2438 {
2439         string track_name;
2440         uint32_t track_id = 0;
2441         string port;
2442         RouteList new_routes;
2443         list<boost::shared_ptr<MidiTrack> > ret;
2444
2445         const string name_pattern = default_track_name_pattern (DataType::MIDI);
2446         bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2447
2448         while (how_many) {
2449                 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2450                         error << "cannot find name for new midi track" << endmsg;
2451                         goto failed;
2452                 }
2453
2454                 boost::shared_ptr<MidiTrack> track;
2455
2456                 try {
2457                         track.reset (new MidiTrack (*this, track_name, mode));
2458
2459                         if (track->init ()) {
2460                                 goto failed;
2461                         }
2462
2463                         if (Profile->get_mixbus ()) {
2464                                 track->set_strict_io (true);
2465                         }
2466
2467                         track->use_new_diskstream();
2468
2469                         BOOST_MARK_TRACK (track);
2470
2471                         {
2472                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2473                                 if (track->input()->ensure_io (input, false, this)) {
2474                                         error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2475                                         goto failed;
2476                                 }
2477
2478                                 if (track->output()->ensure_io (output, false, this)) {
2479                                         error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2480                                         goto failed;
2481                                 }
2482                         }
2483
2484                         track->non_realtime_input_change();
2485
2486                         if (route_group) {
2487                                 route_group->add (track);
2488                         }
2489
2490                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2491
2492                         new_routes.push_back (track);
2493                         ret.push_back (track);
2494                 }
2495
2496                 catch (failed_constructor &err) {
2497                         error << _("Session: could not create new midi track.") << endmsg;
2498                         goto failed;
2499                 }
2500
2501                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2502
2503                         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;
2504                         goto failed;
2505                 }
2506
2507                 --how_many;
2508         }
2509
2510   failed:
2511         if (!new_routes.empty()) {
2512                 StateProtector sp (this);
2513                 if (Profile->get_trx()) {
2514                         add_routes (new_routes, false, false, false, order);
2515                 } else {
2516                         add_routes (new_routes, true, true, false, order);
2517                 }
2518
2519                 if (instrument) {
2520                         for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2521                                 PluginPtr plugin = instrument->load (*this);
2522                                 if (pset) {
2523                                         plugin->load_preset (*pset);
2524                                 }
2525                                 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2526                                 (*r)->add_processor (p, PreFader);
2527
2528                         }
2529                 }
2530         }
2531
2532         return ret;
2533 }
2534
2535 RouteList
2536 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2537                          PresentationInfo::Flag flag, PresentationInfo::order_t order)
2538 {
2539         string bus_name;
2540         uint32_t bus_id = 0;
2541         string port;
2542         RouteList ret;
2543
2544         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2545
2546         while (how_many) {
2547                 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2548                         error << "cannot find name for new midi bus" << endmsg;
2549                         goto failure;
2550                 }
2551
2552                 try {
2553                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2554
2555                         if (bus->init ()) {
2556                                 goto failure;
2557                         }
2558
2559                         if (Profile->get_mixbus ()) {
2560                                 bus->set_strict_io (true);
2561                         }
2562
2563                         BOOST_MARK_ROUTE(bus);
2564
2565                         {
2566                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2567
2568                                 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2569                                         error << _("cannot configure new midi bus input") << endmsg;
2570                                         goto failure;
2571                                 }
2572
2573
2574                                 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2575                                         error << _("cannot configure new midi bus output") << endmsg;
2576                                         goto failure;
2577                                 }
2578                         }
2579
2580                         if (route_group) {
2581                                 route_group->add (bus);
2582                         }
2583
2584                         bus->add_internal_return ();
2585                         ret.push_back (bus);
2586                 }
2587
2588                 catch (failed_constructor &err) {
2589                         error << _("Session: could not create new audio route.") << endmsg;
2590                         goto failure;
2591                 }
2592
2593                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2594                         error << pfe.what() << endmsg;
2595                         goto failure;
2596                 }
2597
2598
2599                 --how_many;
2600         }
2601
2602   failure:
2603         if (!ret.empty()) {
2604                 StateProtector sp (this);
2605                 add_routes (ret, false, false, false, order);
2606
2607                 if (instrument) {
2608                         for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2609                                 PluginPtr plugin = instrument->load (*this);
2610                                 if (pset) {
2611                                         plugin->load_preset (*pset);
2612                                 }
2613                                 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2614                                 (*r)->add_processor (p, PreFader);
2615                         }
2616                 }
2617         }
2618
2619         return ret;
2620
2621 }
2622
2623
2624 void
2625 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2626 {
2627         boost::shared_ptr<Route> midi_track (wmt.lock());
2628
2629         if (!midi_track) {
2630                 return;
2631         }
2632
2633         if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2634
2635                 if (change.after.n_audio() <= change.before.n_audio()) {
2636                         return;
2637                 }
2638
2639                 /* new audio ports: make sure the audio goes somewhere useful,
2640                  * unless the user has no-auto-connect selected.
2641                  *
2642                  * The existing ChanCounts don't matter for this call as they are only
2643                  * to do with matching input and output indices, and we are only changing
2644                  * outputs here.
2645                  */
2646                 auto_connect_route (midi_track, false, ChanCount(), change.before);
2647         }
2648 }
2649
2650 #ifdef USE_TRACKS_CODE_FEATURES
2651
2652 static bool
2653 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2654 {
2655         return route1->remote_control_id() < route2->remote_control_id();
2656 }
2657
2658 void
2659 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2660 {
2661         // it is not allowed to perform connection
2662         if (!IO::connecting_legal) {
2663                 return;
2664         }
2665
2666         // if we are deleting routes we will call this once at the end
2667         if (_route_deletion_in_progress) {
2668                 return;
2669         }
2670
2671         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2672
2673         if (withLock) {
2674                 lm.acquire ();
2675         }
2676
2677         // We need to disconnect the route's inputs and outputs first
2678         // basing on autoconnect configuration
2679         bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2680         bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2681
2682         ChanCount existing_inputs;
2683         ChanCount existing_outputs;
2684         count_existing_track_channels (existing_inputs, existing_outputs);
2685
2686         //ChanCount inputs = ChanCount::ZERO;
2687         //ChanCount outputs = ChanCount::ZERO;
2688
2689         RouteList existing_routes = *routes.reader ();
2690         existing_routes.sort (compare_routes_by_remote_id);
2691
2692         {
2693                 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2694
2695                 vector<string> physinputs;
2696                 vector<string> physoutputs;
2697
2698                 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2699                 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2700
2701                 uint32_t input_n = 0;
2702                 uint32_t output_n = 0;
2703                 RouteList::iterator rIter = existing_routes.begin();
2704                 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2705                 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2706                 for (; rIter != existing_routes.end(); ++rIter) {
2707                         if (*rIter == _master_out || *rIter == _monitor_out ) {
2708                                 continue;
2709                         }
2710
2711                         if (current_output_auto_connection == AutoConnectPhysical) {
2712                                 (*rIter)->amp()->deactivate();
2713                         } else if (current_output_auto_connection == AutoConnectMaster) {
2714                                 (*rIter)->amp()->activate();
2715                         }
2716
2717                         if (reconnectIputs) {
2718                                 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2719
2720                                 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2721
2722                                         if (current_input_auto_connection & AutoConnectPhysical) {
2723
2724                                                 if ( input_n == physinputs.size() ) {
2725                                                         break;
2726                                                 }
2727
2728                                                 string port = physinputs[input_n];
2729
2730                                                 if (port.empty() ) {
2731                                                         error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2732                                                 }
2733
2734                                                 //GZ: check this; could be heavy
2735                                                 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2736                                                 ++input_n;
2737                                         }
2738                                 }
2739                         }
2740
2741                         if (reconnectOutputs) {
2742
2743                                 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2744                                 if (current_output_auto_connection & AutoConnectPhysical) {
2745
2746                                         //GZ: check this; could be heavy
2747                                         (*rIter)->output()->disconnect (this);
2748                                         size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2749
2750                                         //GZ: check this; could be heavy
2751                                         (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2752
2753                                 } else if (current_output_auto_connection & AutoConnectMaster){
2754
2755                                         if (!reconnect_master) {
2756                                                 continue;
2757                                         }
2758
2759                                         //GZ: check this; could be heavy
2760                                         (*rIter)->output()->disconnect (this);
2761
2762                                         if (_master_out) {
2763                                                 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2764                                                 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2765                                         } else {
2766                                                 error << error << "Master bus is not available" << endmsg;
2767                                                 break;
2768                                         }
2769                                 }
2770
2771                                 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2772                                         if (current_output_auto_connection & AutoConnectPhysical) {
2773
2774                                                 if ( output_n == physoutputs.size() ) {
2775                                                         break;
2776                                                 }
2777
2778                                                 string port = physoutputs[output_n];
2779
2780                                                 if (port.empty() ) {
2781                                                         error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2782                                                 }
2783
2784                                                 //GZ: check this; could be heavy
2785                                                 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2786                                                 ++output_n;
2787
2788                                         } else if (current_output_auto_connection & AutoConnectMaster) {
2789
2790                                                 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2791                                                         break;
2792                                                 }
2793
2794                                                 // connect to master bus
2795                                                 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2796
2797                                                 if (port.empty() ) {
2798                                                         error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2799                                                 }
2800
2801
2802                                                 //GZ: check this; could be heavy
2803                                                 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2804
2805                                         }
2806                                 }
2807                         }
2808                 }
2809
2810                 _master_out->output()->disconnect (this);
2811                 auto_connect_master_bus ();
2812         }
2813
2814         graph_reordered ();
2815
2816         session_routes_reconnected (); /* EMIT SIGNAL */
2817 }
2818
2819 void
2820 Session::reconnect_midi_scene_ports(bool inputs)
2821 {
2822     if (inputs ) {
2823
2824         boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2825         if (scene_in_ptr) {
2826             scene_in_ptr->disconnect_all ();
2827
2828             std::vector<EngineStateController::MidiPortState> midi_port_states;
2829             EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2830
2831             std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2832
2833             for (; state_iter != midi_port_states.end(); ++state_iter) {
2834                 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2835                     scene_in_ptr->connect (state_iter->name);
2836                 }
2837             }
2838         }
2839
2840     } else {
2841
2842         boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2843
2844         if (scene_out_ptr ) {
2845             scene_out_ptr->disconnect_all ();
2846
2847             std::vector<EngineStateController::MidiPortState> midi_port_states;
2848             EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2849
2850             std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2851
2852             for (; state_iter != midi_port_states.end(); ++state_iter) {
2853                 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2854                     scene_out_ptr->connect (state_iter->name);
2855                 }
2856             }
2857         }
2858     }
2859 }
2860
2861 void
2862 Session::reconnect_mtc_ports ()
2863 {
2864         boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2865
2866         if (!mtc_in_ptr) {
2867                 return;
2868         }
2869
2870         mtc_in_ptr->disconnect_all ();
2871
2872         std::vector<EngineStateController::MidiPortState> midi_port_states;
2873         EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2874
2875         std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2876
2877         for (; state_iter != midi_port_states.end(); ++state_iter) {
2878                 if (state_iter->available && state_iter->mtc_in) {
2879                         mtc_in_ptr->connect (state_iter->name);
2880                 }
2881         }
2882
2883         if (!_midi_ports->mtc_input_port ()->connected () &&
2884             config.get_external_sync () &&
2885             (Config->get_sync_source () == MTC) ) {
2886                 config.set_external_sync (false);
2887         }
2888
2889         if ( ARDOUR::Profile->get_trx () ) {
2890                 // Tracks need this signal to update timecode_source_dropdown
2891                 MtcOrLtcInputPortChanged (); //emit signal
2892         }
2893 }
2894
2895 void
2896 Session::reconnect_mmc_ports(bool inputs)
2897 {
2898         if (inputs ) { // get all enabled midi input ports
2899
2900                 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2901                 if (mmc_in_ptr) {
2902                         mmc_in_ptr->disconnect_all ();
2903                         std::vector<std::string> enabled_midi_inputs;
2904                         EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2905
2906                         std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2907
2908                         for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2909                                 mmc_in_ptr->connect (*port_iter);
2910                         }
2911
2912                 }
2913         } else { // get all enabled midi output ports
2914
2915                 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2916                 if (mmc_out_ptr ) {
2917                         mmc_out_ptr->disconnect_all ();
2918                         std::vector<std::string> enabled_midi_outputs;
2919                         EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2920
2921                         std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2922
2923                         for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2924                                 mmc_out_ptr->connect (*port_iter);
2925                         }
2926                 }
2927         }
2928 }
2929
2930 #endif
2931
2932 void
2933 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
2934 {
2935         if (first_new_order == PresentationInfo::max_order) {
2936                 /* adding at end, no worries */
2937                 return;
2938         }
2939
2940         /* create a gap in the presentation info to accomodate @param how_many
2941          * new objects.
2942          */
2943         StripableList sl;
2944         get_stripables (sl);
2945
2946         for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
2947                 boost::shared_ptr<Stripable> s (*si);
2948
2949                 if (s->is_monitor() || s->is_auditioner()) {
2950                         continue;
2951                 }
2952
2953                 if (s->presentation_info().order () >= first_new_order) {
2954                         s->set_presentation_order (s->presentation_info().order () + how_many);
2955                 }
2956         }
2957 }
2958
2959 /** Caller must not hold process lock
2960  *  @param name_template string to use for the start of the name, or "" to use "Audio".
2961  */
2962 list< boost::shared_ptr<AudioTrack> >
2963 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
2964                           uint32_t how_many, string name_template, PresentationInfo::order_t order,
2965                           TrackMode mode)
2966 {
2967         string track_name;
2968         uint32_t track_id = 0;
2969         string port;
2970         RouteList new_routes;
2971         list<boost::shared_ptr<AudioTrack> > ret;
2972
2973         const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2974         bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2975
2976         while (how_many) {
2977
2978                 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2979                         error << "cannot find name for new audio track" << endmsg;
2980                         goto failed;
2981                 }
2982
2983                 boost::shared_ptr<AudioTrack> track;
2984
2985                 try {
2986                         track.reset (new AudioTrack (*this, track_name, mode));
2987
2988                         if (track->init ()) {
2989                                 goto failed;
2990                         }
2991
2992                         if (Profile->get_mixbus ()) {
2993                                 track->set_strict_io (true);
2994                         }
2995
2996                         if (ARDOUR::Profile->get_trx ()) {
2997                                 // TRACKS considers it's not a USE CASE, it's
2998                                 // a piece of behavior of the session model:
2999                                 //
3000                                 // Gain for a newly created route depends on
3001                                 // the current output_auto_connect mode:
3002                                 //
3003                                 //  0 for Stereo Out mode
3004                                 //  0 Multi Out mode
3005                                 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3006                                         track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3007                                 }
3008                         }
3009
3010                         track->use_new_diskstream();
3011
3012                         BOOST_MARK_TRACK (track);
3013
3014                         {
3015                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3016
3017                                 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3018                                         error << string_compose (
3019                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
3020                                                 input_channels, output_channels)
3021                                               << endmsg;
3022                                         goto failed;
3023                                 }
3024
3025                                 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3026                                         error << string_compose (
3027                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
3028                                                 input_channels, output_channels)
3029                                               << endmsg;
3030                                         goto failed;
3031                                 }
3032                         }
3033
3034                         if (route_group) {
3035                                 route_group->add (track);
3036                         }
3037
3038                         track->non_realtime_input_change();
3039
3040                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3041
3042                         new_routes.push_back (track);
3043                         ret.push_back (track);
3044                 }
3045
3046                 catch (failed_constructor &err) {
3047                         error << _("Session: could not create new audio track.") << endmsg;
3048                         goto failed;
3049                 }
3050
3051                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3052
3053                         error << pfe.what() << endmsg;
3054                         goto failed;
3055                 }
3056
3057                 --how_many;
3058         }
3059
3060   failed:
3061         if (!new_routes.empty()) {
3062                 StateProtector sp (this);
3063                 if (Profile->get_trx()) {
3064                         add_routes (new_routes, false, false, false, order);
3065                 } else {
3066                         add_routes (new_routes, true, true, false, order);
3067                 }
3068         }
3069
3070         return ret;
3071 }
3072
3073 /** Caller must not hold process lock.
3074  *  @param name_template string to use for the start of the name, or "" to use "Bus".
3075  */
3076 RouteList
3077 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3078                           PresentationInfo::Flag flags, PresentationInfo::order_t order)
3079 {
3080         string bus_name;
3081         uint32_t bus_id = 0;
3082         string port;
3083         RouteList ret;
3084
3085         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3086
3087         while (how_many) {
3088                 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3089                         error << "cannot find name for new audio bus" << endmsg;
3090                         goto failure;
3091                 }
3092
3093                 try {
3094                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3095
3096                         if (bus->init ()) {
3097                                 goto failure;
3098                         }
3099
3100                         if (Profile->get_mixbus ()) {
3101                                 bus->set_strict_io (true);
3102                         }
3103
3104                         BOOST_MARK_ROUTE(bus);
3105
3106                         {
3107                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3108
3109                                 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3110                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3111                                                                  input_channels, output_channels)
3112                                               << endmsg;
3113                                         goto failure;
3114                                 }
3115
3116
3117                                 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3118                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3119                                                                  input_channels, output_channels)
3120                                               << endmsg;
3121                                         goto failure;
3122                                 }
3123                         }
3124
3125                         if (route_group) {
3126                                 route_group->add (bus);
3127                         }
3128
3129                         bus->add_internal_return ();
3130                         ret.push_back (bus);
3131                 }
3132
3133                 catch (failed_constructor &err) {
3134                         error << _("Session: could not create new audio route.") << endmsg;
3135                         goto failure;
3136                 }
3137
3138                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3139                         error << pfe.what() << endmsg;
3140                         goto failure;
3141                 }
3142
3143
3144                 --how_many;
3145         }
3146
3147   failure:
3148         if (!ret.empty()) {
3149                 StateProtector sp (this);
3150                 if (Profile->get_trx()) {
3151                         add_routes (ret, false, false, false, order);
3152                 } else {
3153                         add_routes (ret, false, true, true, order); // autoconnect // outputs only
3154                 }
3155         }
3156
3157         return ret;
3158
3159 }
3160
3161 RouteList
3162 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3163 {
3164         XMLTree tree;
3165
3166         if (!tree.read (template_path.c_str())) {
3167                 return RouteList();
3168         }
3169
3170         return new_route_from_template (how_many, *tree.root(), name_base, pd);
3171 }
3172
3173 RouteList
3174 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3175 {
3176         RouteList ret;
3177         uint32_t number = 0;
3178         const uint32_t being_added = how_many;
3179         /* This will prevent the use of any existing XML-provided PBD::ID
3180            values by Stateful.
3181         */
3182         Stateful::ForceIDRegeneration force_ids;
3183         IO::disable_connecting ();
3184
3185         while (how_many) {
3186
3187                 /* We're going to modify the node contents a bit so take a
3188                  * copy. The node may be re-used when duplicating more than once.
3189                  */
3190
3191                 XMLNode node_copy (node);
3192
3193                 try {
3194                         string name;
3195
3196                         if (!name_base.empty()) {
3197
3198                                 /* if we're adding more than one routes, force
3199                                  * all the names of the new routes to be
3200                                  * numbered, via the final parameter.
3201                                  */
3202
3203                                 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3204                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3205                                         /*NOTREACHDE*/
3206                                 }
3207
3208                         } else {
3209
3210                                 string const route_name  = node_copy.property(X_("name"))->value ();
3211
3212                                 /* generate a new name by adding a number to the end of the template name */
3213                                 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3214                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3215                                         abort(); /*NOTREACHED*/
3216                                 }
3217                         }
3218
3219                         /* set this name in the XML description that we are about to use */
3220
3221                         bool rename_playlist;
3222                         switch (pd) {
3223                         case NewPlaylist:
3224                                 rename_playlist = true;
3225                                 break;
3226                         default:
3227                         case CopyPlaylist:
3228                         case SharePlaylist:
3229                                 rename_playlist = false;
3230                         }
3231
3232                         Route::set_name_in_state (node_copy, name, rename_playlist);
3233
3234                         /* trim bitslots from listen sends so that new ones are used */
3235                         XMLNodeList children = node_copy.children ();
3236                         for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3237                                 if ((*i)->name() == X_("Processor")) {
3238                                         /* ForceIDRegeneration does not catch the following */
3239                                         XMLProperty const * role = (*i)->property (X_("role"));
3240                                         XMLProperty const * type = (*i)->property (X_("type"));
3241                                         if (role && role->value() == X_("Aux")) {
3242                                                 /* check if the target bus exists.
3243                                                  * we should not save aux-sends in templates.
3244                                                  */
3245                                                 XMLProperty const * target = (*i)->property (X_("target"));
3246                                                 if (!target) {
3247                                                         (*i)->add_property ("type", "dangling-aux-send");
3248                                                         continue;
3249                                                 }
3250                                                 boost::shared_ptr<Route> r = route_by_id (target->value());
3251                                                 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3252                                                         (*i)->add_property ("type", "dangling-aux-send");
3253                                                         continue;
3254                                                 }
3255                                         }
3256                                         if (role && role->value() == X_("Listen")) {
3257                                                 (*i)->remove_property (X_("bitslot"));
3258                                         }
3259                                         else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3260                                                 char buf[32];
3261                                                 Delivery::Role xrole;
3262                                                 uint32_t bitslot = 0;
3263                                                 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3264                                                 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3265                                                 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3266                                                 (*i)->remove_property (X_("bitslot"));
3267                                                 (*i)->remove_property (X_("name"));
3268                                                 (*i)->add_property ("bitslot", buf);
3269                                                 (*i)->add_property ("name", name);
3270                                         }
3271                                         else if (type && type->value() == X_("intreturn")) {
3272                                                 (*i)->remove_property (X_("bitslot"));
3273                                                 (*i)->add_property ("ignore-bitslot", "1");
3274                                         }
3275                                         else if (type && type->value() == X_("return")) {
3276                                                 // Return::set_state() generates a new one
3277                                                 (*i)->remove_property (X_("bitslot"));
3278                                         }
3279                                         else if (type && type->value() == X_("port")) {
3280                                                 // PortInsert::set_state() handles the bitslot
3281                                                 (*i)->remove_property (X_("bitslot"));
3282                                                 (*i)->add_property ("ignore-name", "1");
3283                                         }
3284                                 }
3285                         }
3286
3287                         boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3288
3289                         if (route == 0) {
3290                                 error << _("Session: cannot create track/bus from template description") << endmsg;
3291                                 goto out;
3292                         }
3293
3294                         if (boost::dynamic_pointer_cast<Track>(route)) {
3295                                 /* force input/output change signals so that the new diskstream
3296                                    picks up the configuration of the route. During session
3297                                    loading this normally happens in a different way.
3298                                 */
3299
3300                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3301
3302                                 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3303                                 change.after = route->input()->n_ports();
3304                                 route->input()->changed (change, this);
3305                                 change.after = route->output()->n_ports();
3306                                 route->output()->changed (change, this);
3307                         }
3308
3309                         boost::shared_ptr<Track> track;
3310
3311                         if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3312                                 switch (pd) {
3313                                 case NewPlaylist:
3314                                         track->use_new_playlist ();
3315                                         break;
3316                                 case CopyPlaylist:
3317                                         track->use_copy_playlist ();
3318                                         break;
3319                                 case SharePlaylist:
3320                                         break;
3321                                 }
3322                         };
3323
3324                         ret.push_back (route);
3325                 }
3326
3327                 catch (failed_constructor &err) {
3328                         error << _("Session: could not create new route from template") << endmsg;
3329                         goto out;
3330                 }
3331
3332                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3333                         error << pfe.what() << endmsg;
3334                         goto out;
3335                 }
3336
3337                 --how_many;
3338         }
3339
3340   out:
3341         if (!ret.empty()) {
3342                 StateProtector sp (this);
3343                 if (Profile->get_trx()) {
3344                         add_routes (ret, false, false, false, PresentationInfo::max_order);
3345                 } else {
3346                         add_routes (ret, true, true, false, PresentationInfo::max_order);
3347                 }
3348                 IO::enable_connecting ();
3349         }
3350
3351         return ret;
3352 }
3353
3354 void
3355 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3356 {
3357         try {
3358                 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3359                 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3360
3361         } catch (...) {
3362                 error << _("Adding new tracks/busses failed") << endmsg;
3363         }
3364
3365         graph_reordered ();
3366
3367         update_latency (true);
3368         update_latency (false);
3369
3370         set_dirty();
3371
3372         if (save) {
3373                 save_state (_current_snapshot_name);
3374         }
3375
3376         update_route_record_state ();
3377
3378         RouteAdded (new_routes); /* EMIT SIGNAL */
3379 }
3380
3381 void
3382 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3383 {
3384         ChanCount existing_inputs;
3385         ChanCount existing_outputs;
3386         uint32_t n_routes;
3387         uint32_t added = 0;
3388
3389         count_existing_track_channels (existing_inputs, existing_outputs);
3390
3391         {
3392                 RCUWriter<RouteList> writer (routes);
3393                 boost::shared_ptr<RouteList> r = writer.get_copy ();
3394                 r->insert (r->end(), new_routes.begin(), new_routes.end());
3395                 n_routes = r->size();
3396
3397                 /* if there is no control out and we're not in the middle of loading,
3398                  * resort the graph here. if there is a control out, we will resort
3399                  * toward the end of this method. if we are in the middle of loading,
3400                  * we will resort when done.
3401                  */
3402
3403                 if (!_monitor_out && IO::connecting_legal) {
3404                         resort_routes_using (r);
3405                 }
3406         }
3407
3408         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3409         ensure_route_presentation_info_gap (order, new_routes.size());
3410
3411         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3412
3413                 boost::weak_ptr<Route> wpr (*x);
3414                 boost::shared_ptr<Route> r (*x);
3415
3416                 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3417                 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3418                 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3419
3420                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3421                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3422                 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3423
3424                 if (r->is_master()) {
3425                         _master_out = r;
3426                 }
3427
3428                 if (r->is_monitor()) {
3429                         _monitor_out = r;
3430                 }
3431
3432                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3433                 if (tr) {
3434                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3435                         track_playlist_changed (boost::weak_ptr<Track> (tr));
3436                         tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3437
3438                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3439                         if (mt) {
3440                                 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3441                                 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3442                         }
3443                 }
3444
3445                 if (!r->presentation_info().special()) {
3446
3447                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3448
3449                         /* presentation info order may already have been set from XML */
3450
3451                         if (!r->presentation_info().order_set()) {
3452
3453                                 if (order == PresentationInfo::max_order) {
3454                                         /* just add to the end */
3455                                         r->set_presentation_order_explicit (n_routes + added);
3456                                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3457                                 } else {
3458                                         r->set_presentation_order (order + added);
3459                                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3460                                 }
3461                         } else {
3462                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3463                         }
3464                 }
3465
3466 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3467                 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3468                  * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3469                  */
3470                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3471                                                                r->name(),
3472                                                                r->presentation_info().order(),
3473                                                                enum_2_string (r->presentation_info().flags()),
3474                                                                r->presentation_info()));
3475 #endif
3476
3477
3478                 if (input_auto_connect || output_auto_connect) {
3479                         auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3480                         existing_inputs += r->n_inputs();
3481                         existing_outputs += r->n_outputs();
3482                 }
3483
3484                 ARDOUR::GUIIdle ();
3485         }
3486
3487         if (_monitor_out && IO::connecting_legal) {
3488                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3489
3490                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3491                         if ((*x)->is_monitor()) {
3492                                 /* relax */
3493                         } else if ((*x)->is_master()) {
3494                                 /* relax */
3495                         } else {
3496                                 (*x)->enable_monitor_send ();
3497                         }
3498                 }
3499         }
3500
3501         reassign_track_numbers ();
3502 }
3503
3504 void
3505 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3506 {
3507         boost::shared_ptr<RouteList> r = routes.reader ();
3508         boost::shared_ptr<Send> s;
3509
3510         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3511                 if ((s = (*i)->internal_send_for (dest)) != 0) {
3512                         s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3513                 }
3514         }
3515 }
3516
3517 void
3518 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3519 {
3520         boost::shared_ptr<RouteList> r = routes.reader ();
3521         boost::shared_ptr<Send> s;
3522
3523         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3524                 if ((s = (*i)->internal_send_for (dest)) != 0) {
3525                         s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3526                 }
3527         }
3528 }
3529
3530 void
3531 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3532 {
3533         boost::shared_ptr<RouteList> r = routes.reader ();
3534         boost::shared_ptr<Send> s;
3535
3536         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3537                 if ((s = (*i)->internal_send_for (dest)) != 0) {
3538                         s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3539                 }
3540         }
3541 }
3542
3543 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3544 void
3545 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3546 {
3547         boost::shared_ptr<RouteList> r = routes.reader ();
3548         boost::shared_ptr<RouteList> t (new RouteList);
3549
3550         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3551                 /* no MIDI sends because there are no MIDI busses yet */
3552                 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3553                         t->push_back (*i);
3554                 }
3555         }
3556
3557         add_internal_sends (dest, p, t);
3558 }
3559
3560 void
3561 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3562 {
3563         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3564                 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3565         }
3566 }
3567
3568 void
3569 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3570 {
3571         add_internal_send (dest, sender->before_processor_for_index (index), sender);
3572 }
3573
3574 void
3575 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3576 {
3577         if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3578                 return;
3579         }
3580
3581         if (!dest->internal_return()) {
3582                 dest->add_internal_return ();
3583         }
3584
3585         sender->add_aux_send (dest, before);
3586
3587         graph_reordered ();
3588 }
3589
3590 void
3591 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3592 {
3593         { // RCU Writer scope
3594                 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3595                 RCUWriter<RouteList> writer (routes);
3596                 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3597
3598
3599                 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3600
3601                         if (*iter == _master_out) {
3602                                 continue;
3603                         }
3604
3605                         (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3606
3607                         rs->remove (*iter);
3608
3609                         /* deleting the master out seems like a dumb
3610                            idea, but its more of a UI policy issue
3611                            than our concern.
3612                         */
3613
3614                         if (*iter == _master_out) {
3615                                 _master_out = boost::shared_ptr<Route> ();
3616                         }
3617
3618                         if (*iter == _monitor_out) {
3619                                 _monitor_out.reset ();
3620                         }
3621
3622                         // We need to disconnect the route's inputs and outputs
3623
3624                         (*iter)->input()->disconnect (0);
3625                         (*iter)->output()->disconnect (0);
3626
3627                         /* if the route had internal sends sending to it, remove them */
3628                         if ((*iter)->internal_return()) {
3629
3630                                 boost::shared_ptr<RouteList> r = routes.reader ();
3631                                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3632                                         boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3633                                         if (s) {
3634                                                 (*i)->remove_processor (s);
3635                                         }
3636                                 }
3637                         }
3638
3639                         /* if the monitoring section had a pointer to this route, remove it */
3640                         if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3641                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3642                                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3643                                 (*iter)->remove_aux_or_listen (_monitor_out);
3644                         }
3645
3646                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3647                         if (mt && mt->step_editing()) {
3648                                 if (_step_editors > 0) {
3649                                         _step_editors--;
3650                                 }
3651                         }
3652                 }
3653
3654                 /* writer goes out of scope, forces route list update */
3655
3656         } // end of RCU Writer scope
3657
3658         update_route_solo_state ();
3659         update_latency_compensation ();
3660         set_dirty();
3661
3662         /* Re-sort routes to remove the graph's current references to the one that is
3663          * going away, then flush old references out of the graph.
3664          * Wave Tracks: reconnect routes
3665          */
3666
3667 #ifdef USE_TRACKS_CODE_FEATURES
3668                 reconnect_existing_routes(true, false);
3669 #else
3670                 routes.flush (); // maybe unsafe, see below.
3671                 resort_routes ();
3672 #endif
3673
3674         if (_process_graph && !(_state_of_the_state & Deletion)) {
3675                 _process_graph->clear_other_chain ();
3676         }
3677
3678         /* get rid of it from the dead wood collection in the route list manager */
3679         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3680
3681         routes.flush ();
3682
3683         /* try to cause everyone to drop their references
3684          * and unregister ports from the backend
3685          */
3686
3687         for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3688                 (*iter)->drop_references ();
3689         }
3690
3691         if (_state_of_the_state & Deletion) {
3692                 return;
3693         }
3694
3695         PresentationInfo::Change(); /* EMIT SIGNAL */
3696
3697         /* save the new state of the world */
3698
3699         if (save_state (_current_snapshot_name)) {
3700                 save_history (_current_snapshot_name);
3701         }
3702
3703         update_route_record_state ();
3704 }
3705
3706 void
3707 Session::remove_route (boost::shared_ptr<Route> route)
3708 {
3709         boost::shared_ptr<RouteList> rl (new RouteList);
3710         rl->push_back (route);
3711         remove_routes (rl);
3712 }
3713
3714 void
3715 Session::route_mute_changed ()
3716 {
3717         set_dirty ();
3718 }
3719
3720 void
3721 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3722 {
3723         boost::shared_ptr<Route> route (wpr.lock());
3724
3725         if (!route) {
3726                 return;
3727         }
3728
3729         assert (Config->get_solo_control_is_listen_control());
3730
3731         if (route->solo_control()->soloed_by_self_or_masters()) {
3732
3733                 if (Config->get_exclusive_solo()) {
3734
3735                         RouteGroup* rg = route->route_group ();
3736                         const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3737
3738                         boost::shared_ptr<RouteList> r = routes.reader ();
3739
3740                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3741                                 if ((*i) == route) {
3742                                         /* already changed */
3743                                         continue;
3744                                 }
3745
3746                                 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3747                                         /* route does not get solo propagated to it */
3748                                         continue;
3749                                 }
3750
3751                                 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3752                                         /* this route is a part of the same solo group as the route
3753                                          * that was changed. Changing that route did change or will
3754                                          * change all group members appropriately, so we can ignore it
3755                                          * here
3756                                          */
3757                                         continue;
3758                                 }
3759                                 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3760                         }
3761                 }
3762
3763                 _listen_cnt++;
3764
3765         } else if (_listen_cnt > 0) {
3766
3767                 _listen_cnt--;
3768         }
3769
3770         update_route_solo_state ();
3771 }
3772
3773 void
3774 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3775 {
3776         boost::shared_ptr<Route> route (wpr.lock());
3777
3778         if (!route) {
3779                 return;
3780         }
3781
3782         bool send_changed = false;
3783
3784         if (route->solo_isolate_control()->solo_isolated()) {
3785                 if (_solo_isolated_cnt == 0) {
3786                         send_changed = true;
3787                 }
3788                 _solo_isolated_cnt++;
3789         } else if (_solo_isolated_cnt > 0) {
3790                 _solo_isolated_cnt--;
3791                 if (_solo_isolated_cnt == 0) {
3792                         send_changed = true;
3793                 }
3794         }
3795
3796         if (send_changed) {
3797                 IsolatedChanged (); /* EMIT SIGNAL */
3798         }
3799 }
3800
3801 void
3802 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override,  boost::weak_ptr<Route> wpr)
3803 {
3804         DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_changed));
3805
3806         boost::shared_ptr<Route> route (wpr.lock());
3807
3808         if (!route) {
3809                 return;
3810         }
3811
3812         if (Config->get_solo_control_is_listen_control()) {
3813                 route_listen_changed (group_override, wpr);
3814                 return;
3815         }
3816
3817         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: self %2 masters %3 transition %4\n", route->name(), route->self_soloed(), route->solo_control()->get_masters_value(), route->solo_control()->transitioned_into_solo()));
3818
3819         if (route->solo_control()->transitioned_into_solo() == 0) {
3820                 /* route solo changed by upstream/downstream; not interesting
3821                    to Session.
3822                 */
3823                 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 not self-soloed nor soloed by master (%2), ignoring\n", route->name(), route->solo_control()->get_masters_value()));
3824                 return;
3825         }
3826
3827         if (route->solo_control()->transitioned_into_solo() == 0) {
3828                 /* reason for being soloed changed (e.g. master went away, we
3829                  * took over the master state), but actual status did
3830                  * not. nothing to do.
3831                  */
3832                 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: solo change was change in reason, not status\n", route->name()));
3833         }
3834
3835         boost::shared_ptr<RouteList> r = routes.reader ();
3836         int32_t delta = route->solo_control()->transitioned_into_solo ();
3837
3838         /* the route may be a member of a group that has shared-solo
3839          * semantics. If so, then all members of that group should follow the
3840          * solo of the changed route. But ... this is optional, controlled by a
3841          * Controllable::GroupControlDisposition.
3842          *
3843          * The first argument to the signal that this method is connected to is the
3844          * GroupControlDisposition value that was used to change solo.
3845          *
3846          * If the solo change was done with group semantics (either InverseGroup
3847          * (force the entire group to change even if the group shared solo is
3848          * disabled) or UseGroup (use the group, which may or may not have the
3849          * shared solo property enabled)) then as we propagate the change to
3850          * the entire session we should IGNORE THE GROUP that the changed route
3851          * belongs to.
3852          */
3853
3854         RouteGroup* rg = route->route_group ();
3855         const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3856
3857         if (delta == 1 && Config->get_exclusive_solo()) {
3858
3859                 /* new solo: disable all other solos, but not the group if its solo-enabled */
3860
3861                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3862
3863                         if ((*i) == route) {
3864                                 /* already changed */
3865                                 continue;
3866                         }
3867
3868                         if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3869                                 /* route does not get solo propagated to it */
3870                                 continue;
3871                         }
3872
3873                         if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3874                                 /* this route is a part of the same solo group as the route
3875                                  * that was changed. Changing that route did change or will
3876                                  * change all group members appropriately, so we can ignore it
3877                                  * here
3878                                  */
3879                                 continue;
3880                         }
3881
3882                         (*i)->solo_control()->set_value (0.0, group_override);
3883                 }
3884         }
3885
3886         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3887
3888         RouteList uninvolved;
3889
3890         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3891
3892         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3893                 bool via_sends_only;
3894                 bool in_signal_flow;
3895
3896                 if ((*i) == route) {
3897                         /* already changed */
3898                         continue;
3899                 }
3900
3901                 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3902                         /* route does not get solo propagated to it */
3903                         continue;
3904                 }
3905
3906                 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3907                         /* this route is a part of the same solo group as the route
3908                          * that was changed. Changing that route did change or will
3909                          * change all group members appropriately, so we can ignore it
3910                          * here
3911                          */
3912                         continue;
3913                 }
3914
3915                 in_signal_flow = false;
3916
3917                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3918
3919                 if ((*i)->feeds (route, &via_sends_only)) {
3920                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3921                         if (!via_sends_only) {
3922                                 if (!route->soloed_by_others_upstream()) {
3923                                         (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3924                                 } else {
3925                                         DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3926                                 }
3927                         } else {
3928                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3929                         }
3930                         in_signal_flow = true;
3931                 } else {
3932                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3933                 }
3934
3935                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3936
3937                 if (route->feeds (*i, &via_sends_only)) {
3938                         /* propagate solo upstream only if routing other than
3939                            sends is involved, but do consider the other route
3940                            (*i) to be part of the signal flow even if only
3941                            sends are involved.
3942                         */
3943                         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3944                                                                   route->name(),
3945                                                                   (*i)->name(),
3946                                                                   via_sends_only,
3947                                                                   route->soloed_by_others_downstream(),
3948                                                                   route->soloed_by_others_upstream()));
3949                         if (!via_sends_only) {
3950                                 //NB. Triggers Invert Push, which handles soloed by downstream
3951                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3952                                 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3953                         } else {
3954                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3955                         }
3956                         in_signal_flow = true;
3957                 } else {
3958                         DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3959                 }
3960
3961                 if (!in_signal_flow) {
3962                         uninvolved.push_back (*i);
3963                 }
3964         }
3965
3966         DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3967
3968         update_route_solo_state (r);
3969
3970         /* now notify that the mute state of the routes not involved in the signal
3971            pathway of the just-solo-changed route may have altered.
3972         */
3973
3974         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3975                 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3976                 (*i)->act_on_mute ();
3977                 (*i)->mute_control()->Changed (false, Controllable::NoGroup);
3978         }
3979
3980         SoloChanged (); /* EMIT SIGNAL */
3981         set_dirty();
3982 }
3983
3984 void
3985 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3986 {
3987         /* now figure out if anything that matters is soloed (or is "listening")*/
3988
3989         bool something_soloed = false;
3990         bool something_listening = false;
3991         uint32_t listeners = 0;
3992         uint32_t isolated = 0;
3993
3994         if (!r) {
3995                 r = routes.reader();
3996         }
3997
3998         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3999                 if ((*i)->can_solo()) {
4000                         if (Config->get_solo_control_is_listen_control()) {
4001                                 if ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value()) {
4002                                         listeners++;
4003                                         something_listening = true;
4004                                 }
4005                         } else {
4006                                 (*i)->set_listen (false);
4007                                 if ((*i)->can_solo() && ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value())) {
4008                                         something_soloed = true;
4009                                 }
4010                         }
4011                 }
4012
4013                 if ((*i)->solo_isolate_control()->solo_isolated()) {
4014                         isolated++;
4015                 }
4016         }
4017
4018         if (something_soloed != _non_soloed_outs_muted) {
4019                 _non_soloed_outs_muted = something_soloed;
4020                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4021         }
4022
4023         if (something_listening != _listening) {
4024                 _listening = something_listening;
4025                 SoloActive (_listening);
4026         }
4027
4028         _listen_cnt = listeners;
4029
4030         if (isolated != _solo_isolated_cnt) {
4031                 _solo_isolated_cnt = isolated;
4032                 IsolatedChanged (); /* EMIT SIGNAL */
4033         }
4034
4035         DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4036                                                   something_soloed, listeners, isolated));
4037 }
4038
4039 void
4040 Session::get_stripables (StripableList& sl) const
4041 {
4042         boost::shared_ptr<RouteList> r = routes.reader ();
4043         sl.insert (sl.end(), r->begin(), r->end());
4044
4045         VCAList v = _vca_manager->vcas ();
4046         sl.insert (sl.end(), v.begin(), v.end());
4047 }
4048
4049 boost::shared_ptr<RouteList>
4050 Session::get_routes_with_internal_returns() const
4051 {
4052         boost::shared_ptr<RouteList> r = routes.reader ();
4053         boost::shared_ptr<RouteList> rl (new RouteList);
4054
4055         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4056                 if ((*i)->internal_return ()) {
4057                         rl->push_back (*i);
4058                 }
4059         }
4060         return rl;
4061 }
4062
4063 bool
4064 Session::io_name_is_legal (const std::string& name) const
4065 {
4066         boost::shared_ptr<RouteList> r = routes.reader ();
4067
4068         for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4069                 if (name == *reserved) {
4070                         if (!route_by_name (*reserved)) {
4071                                 /* first instance of a reserved name is allowed */
4072                                 return true;
4073                         }
4074                         /* all other instances of a reserved name are not allowed */
4075                         return false;
4076                 }
4077         }
4078
4079         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4080                 if ((*i)->name() == name) {
4081                         return false;
4082                 }
4083
4084                 if ((*i)->has_io_processor_named (name)) {
4085                         return false;
4086                 }
4087         }
4088
4089         return true;
4090 }
4091
4092 void
4093 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4094 {
4095         RouteList rl2;
4096         vector<string> connections;
4097
4098         /* if we are passed only a single route and we're not told to turn
4099          * others off, then just do the simple thing.
4100          */
4101
4102         if (flip_others == false && rl->size() == 1) {
4103                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4104                 if (mt) {
4105                         mt->set_input_active (onoff);
4106                         return;
4107                 }
4108         }
4109
4110         for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4111
4112                 PortSet& ps ((*rt)->input()->ports());
4113
4114                 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4115                         p->get_connections (connections);
4116                 }
4117
4118                 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4119                         routes_using_input_from (*s, rl2);
4120                 }
4121
4122                 /* scan all relevant routes to see if others are on or off */
4123
4124                 bool others_are_already_on = false;
4125
4126                 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4127
4128                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4129
4130                         if (!mt) {
4131                                 continue;
4132                         }
4133
4134                         if ((*r) != (*rt)) {
4135                                 if (mt->input_active()) {
4136                                         others_are_already_on = true;
4137                                 }
4138                         } else {
4139                                 /* this one needs changing */
4140                                 mt->set_input_active (onoff);
4141                         }
4142                 }
4143
4144                 if (flip_others) {
4145
4146                         /* globally reverse other routes */
4147
4148                         for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4149                                 if ((*r) != (*rt)) {
4150                                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4151                                         if (mt) {
4152                                                 mt->set_input_active (!others_are_already_on);
4153                                         }
4154                                 }
4155                         }
4156                 }
4157         }
4158 }
4159
4160 void
4161 Session::routes_using_input_from (const string& str, RouteList& rl)
4162 {
4163         boost::shared_ptr<RouteList> r = routes.reader();
4164
4165         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4166                 if ((*i)->input()->connected_to (str)) {
4167                         rl.push_back (*i);
4168                 }
4169         }
4170 }
4171
4172 boost::shared_ptr<Route>
4173 Session::route_by_name (string name) const
4174 {
4175         boost::shared_ptr<RouteList> r = routes.reader ();
4176
4177         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4178                 if ((*i)->name() == name) {
4179                         return *i;
4180                 }
4181         }
4182
4183         return boost::shared_ptr<Route> ((Route*) 0);
4184 }
4185
4186 boost::shared_ptr<Route>
4187 Session::route_by_id (PBD::ID id) const
4188 {
4189         boost::shared_ptr<RouteList> r = routes.reader ();
4190
4191         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4192                 if ((*i)->id() == id) {
4193                         return *i;
4194                 }
4195         }
4196
4197         return boost::shared_ptr<Route> ((Route*) 0);
4198 }
4199
4200 boost::shared_ptr<Processor>
4201 Session::processor_by_id (PBD::ID id) const
4202 {
4203         boost::shared_ptr<RouteList> r = routes.reader ();
4204
4205         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4206                 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4207                 if (p) {
4208                         return p;
4209                 }
4210         }
4211
4212         return boost::shared_ptr<Processor> ();
4213 }
4214
4215 boost::shared_ptr<Track>
4216 Session::track_by_diskstream_id (PBD::ID id) const
4217 {
4218         boost::shared_ptr<RouteList> r = routes.reader ();
4219
4220         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4221                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4222                 if (t && t->using_diskstream_id (id)) {
4223                         return t;
4224                 }
4225         }
4226
4227         return boost::shared_ptr<Track> ();
4228 }
4229
4230 boost::shared_ptr<Route>
4231 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4232 {
4233         return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4234 }
4235
4236 boost::shared_ptr<Stripable>
4237 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4238 {
4239         StripableList sl;
4240         PresentationInfo::order_t match_cnt = 0;
4241
4242         get_stripables (sl);
4243         sl.sort (Stripable::PresentationOrderSorter());
4244
4245         for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4246                 if ((*s)->presentation_info().flag_match (flags)) {
4247                         if (match_cnt++ == n) {
4248                                 return *s;
4249                         }
4250                 }
4251         }
4252
4253         /* there is no nth stripable that matches the given flags */
4254         return boost::shared_ptr<Stripable>();
4255 }
4256
4257 boost::shared_ptr<Route>
4258 Session::route_by_selected_count (uint32_t id) const
4259 {
4260         boost::shared_ptr<RouteList> r = routes.reader ();
4261
4262         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4263                 /* NOT IMPLEMENTED */
4264         }
4265
4266         return boost::shared_ptr<Route> ((Route*) 0);
4267 }
4268
4269 struct PresentationOrderSorter {
4270         bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4271                 if (a->presentation_info().special() && !b->presentation_info().special()) {
4272                         /* a is not ordered, b is; b comes before a */
4273                         return false;
4274                 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4275                         /* b is not ordered, a is; a comes before b */
4276                         return true;
4277                 } else {
4278                         return a->presentation_info().order() < b->presentation_info().order();
4279                 }
4280         }
4281 };
4282
4283 void
4284 Session::reassign_track_numbers ()
4285 {
4286         int64_t tn = 0;
4287         int64_t bn = 0;
4288         RouteList r (*(routes.reader ()));
4289         PresentationOrderSorter sorter;
4290         r.sort (sorter);
4291
4292         StateProtector sp (this);
4293
4294         for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4295                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4296                         (*i)->set_track_number(++tn);
4297                 }
4298                 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4299                         (*i)->set_track_number(--bn);
4300                 }
4301         }
4302         const uint32_t decimals = ceilf (log10f (tn + 1));
4303         const bool decimals_changed = _track_number_decimals != decimals;
4304         _track_number_decimals = decimals;
4305
4306         if (decimals_changed && config.get_track_name_number ()) {
4307                 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4308                         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4309                         if (t) {
4310                                 t->resync_track_name();
4311                         }
4312                 }
4313                 // trigger GUI re-layout
4314                 config.ParameterChanged("track-name-number");
4315         }
4316
4317 #ifndef NDEBUG
4318         if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4319                 boost::shared_ptr<RouteList> rl = routes.reader ();
4320                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4321                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4322                 }
4323         }
4324 #endif /* NDEBUG */
4325
4326 }
4327
4328 void
4329 Session::playlist_region_added (boost::weak_ptr<Region> w)
4330 {
4331         boost::shared_ptr<Region> r = w.lock ();
4332         if (!r) {
4333                 return;
4334         }
4335
4336         /* These are the operations that are currently in progress... */
4337         list<GQuark> curr = _current_trans_quarks;
4338         curr.sort ();
4339
4340         /* ...and these are the operations during which we want to update
4341            the session range location markers.
4342         */
4343         list<GQuark> ops;
4344         ops.push_back (Operations::capture);
4345         ops.push_back (Operations::paste);
4346         ops.push_back (Operations::duplicate_region);
4347         ops.push_back (Operations::insert_file);
4348         ops.push_back (Operations::insert_region);
4349         ops.push_back (Operations::drag_region_brush);
4350         ops.push_back (Operations::region_drag);
4351         ops.push_back (Operations::selection_grab);
4352         ops.push_back (Operations::region_fill);
4353         ops.push_back (Operations::fill_selection);
4354         ops.push_back (Operations::create_region);
4355         ops.push_back (Operations::region_copy);
4356         ops.push_back (Operations::fixed_time_region_copy);
4357         ops.sort ();
4358
4359         /* See if any of the current operations match the ones that we want */
4360         list<GQuark> in;
4361         set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4362
4363         /* If so, update the session range markers */
4364         if (!in.empty ()) {
4365                 maybe_update_session_range (r->position (), r->last_frame ());
4366         }
4367 }
4368
4369 /** Update the session range markers if a is before the current start or
4370  *  b is after the current end.
4371  */
4372 void
4373 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4374 {
4375         if (_state_of_the_state & Loading) {
4376                 return;
4377         }
4378
4379         framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4380
4381         if (_session_range_location == 0) {
4382
4383                 set_session_range_location (a, b + session_end_marker_shift_samples);
4384
4385         } else {
4386
4387                 if (a < _session_range_location->start()) {
4388                         _session_range_location->set_start (a);
4389                 }
4390
4391                 if (b > _session_range_location->end()) {
4392                         _session_range_location->set_end (b);
4393                 }
4394         }
4395 }
4396
4397 void
4398 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4399 {
4400         for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4401                 maybe_update_session_range (i->to, i->to + i->length);
4402         }
4403 }
4404
4405 void
4406 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4407 {
4408         for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4409                 maybe_update_session_range (i->from, i->to);
4410         }
4411 }
4412
4413 /* Region management */
4414
4415 boost::shared_ptr<Region>
4416 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4417 {
4418         const RegionFactory::RegionMap& regions (RegionFactory::regions());
4419         RegionFactory::RegionMap::const_iterator i;
4420         boost::shared_ptr<Region> region;
4421
4422         Glib::Threads::Mutex::Lock lm (region_lock);
4423
4424         for (i = regions.begin(); i != regions.end(); ++i) {
4425
4426                 region = i->second;
4427
4428                 if (region->whole_file()) {
4429
4430                         if (child->source_equivalent (region)) {
4431                                 return region;
4432                         }
4433                 }
4434         }
4435
4436         return boost::shared_ptr<Region> ();
4437 }
4438
4439 int
4440 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4441 {
4442         set<boost::shared_ptr<Region> > relevant_regions;
4443
4444         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4445                 RegionFactory::get_regions_using_source (*s, relevant_regions);
4446         }
4447
4448         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4449                 set<boost::shared_ptr<Region> >::iterator tmp;
4450
4451                 tmp = r;
4452                 ++tmp;
4453
4454                 playlists->destroy_region (*r);
4455                 RegionFactory::map_remove (*r);
4456
4457                 (*r)->drop_sources ();
4458                 (*r)->drop_references ();
4459
4460                 relevant_regions.erase (r);
4461
4462                 r = tmp;
4463         }
4464
4465         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4466
4467                 {
4468                         Glib::Threads::Mutex::Lock ls (source_lock);
4469                         /* remove from the main source list */
4470                         sources.erase ((*s)->id());
4471                 }
4472
4473                 (*s)->mark_for_remove ();
4474                 (*s)->drop_references ();
4475
4476                 s = srcs.erase (s);
4477         }
4478
4479         return 0;
4480 }
4481
4482 int
4483 Session::remove_last_capture ()
4484 {
4485         list<boost::shared_ptr<Source> > srcs;
4486
4487         boost::shared_ptr<RouteList> rl = routes.reader ();
4488         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4489                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4490                 if (!tr) {
4491                         continue;
4492                 }
4493
4494                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4495
4496                 if (!l.empty()) {
4497                         srcs.insert (srcs.end(), l.begin(), l.end());
4498                         l.clear ();
4499                 }
4500         }
4501
4502         destroy_sources (srcs);
4503
4504         save_state (_current_snapshot_name);
4505
4506         return 0;
4507 }
4508
4509 /* Source Management */
4510
4511 void
4512 Session::add_source (boost::shared_ptr<Source> source)
4513 {
4514         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4515         pair<SourceMap::iterator,bool> result;
4516
4517         entry.first = source->id();
4518         entry.second = source;
4519
4520         {
4521                 Glib::Threads::Mutex::Lock lm (source_lock);
4522                 result = sources.insert (entry);
4523         }
4524
4525         if (result.second) {
4526
4527                 /* yay, new source */
4528
4529                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4530
4531                 if (fs) {
4532                         if (!fs->within_session()) {
4533                                 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4534                         }
4535                 }
4536
4537                 set_dirty();
4538
4539                 boost::shared_ptr<AudioFileSource> afs;
4540
4541                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4542                         if (Config->get_auto_analyse_audio()) {
4543                                 Analyser::queue_source_for_analysis (source, false);
4544                         }
4545                 }
4546
4547                 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4548         }
4549 }
4550
4551 void
4552 Session::remove_source (boost::weak_ptr<Source> src)
4553 {
4554         if (_state_of_the_state & Deletion) {
4555                 return;
4556         }
4557
4558         SourceMap::iterator i;
4559         boost::shared_ptr<Source> source = src.lock();
4560
4561         if (!source) {
4562                 return;
4563         }
4564
4565         {
4566                 Glib::Threads::Mutex::Lock lm (source_lock);
4567
4568                 if ((i = sources.find (source->id())) != sources.end()) {
4569                         sources.erase (i);
4570                 }
4571         }
4572
4573         if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4574
4575                 /* save state so we don't end up with a session file
4576                    referring to non-existent sources.
4577                 */
4578
4579                 save_state (_current_snapshot_name);
4580         }
4581 }
4582
4583 boost::shared_ptr<Source>
4584 Session::source_by_id (const PBD::ID& id)
4585 {
4586         Glib::Threads::Mutex::Lock lm (source_lock);
4587         SourceMap::iterator i;
4588         boost::shared_ptr<Source> source;
4589
4590         if ((i = sources.find (id)) != sources.end()) {
4591                 source = i->second;
4592         }
4593
4594         return source;
4595 }
4596
4597 boost::shared_ptr<AudioFileSource>
4598 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4599 {
4600         /* Restricted to audio files because only audio sources have channel
4601            as a property.
4602         */
4603
4604         Glib::Threads::Mutex::Lock lm (source_lock);
4605
4606         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4607                 boost::shared_ptr<AudioFileSource> afs
4608                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4609
4610                 if (afs && afs->path() == path && chn == afs->channel()) {
4611                         return afs;
4612                 }
4613         }
4614
4615         return boost::shared_ptr<AudioFileSource>();
4616 }
4617
4618 boost::shared_ptr<MidiSource>
4619 Session::midi_source_by_path (const std::string& path) const
4620 {
4621         /* Restricted to MIDI files because audio sources require a channel
4622            for unique identification, in addition to a path.
4623         */
4624
4625         Glib::Threads::Mutex::Lock lm (source_lock);
4626
4627         for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4628                 boost::shared_ptr<MidiSource> ms
4629                         = boost::dynamic_pointer_cast<MidiSource>(s->second);
4630                 boost::shared_ptr<FileSource> fs
4631                         = boost::dynamic_pointer_cast<FileSource>(s->second);
4632
4633                 if (ms && fs && fs->path() == path) {
4634                         return ms;
4635                 }
4636         }
4637
4638         return boost::shared_ptr<MidiSource>();
4639 }
4640
4641 uint32_t
4642 Session::count_sources_by_origin (const string& path)
4643 {
4644         uint32_t cnt = 0;
4645         Glib::Threads::Mutex::Lock lm (source_lock);
4646
4647         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4648                 boost::shared_ptr<FileSource> fs
4649                         = boost::dynamic_pointer_cast<FileSource>(i->second);
4650
4651                 if (fs && fs->origin() == path) {
4652                         ++cnt;
4653                 }
4654         }
4655
4656         return cnt;
4657 }
4658
4659 static string
4660 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4661         if (hash) {
4662                 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4663                 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4664         } else {
4665                 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4666         }
4667 }
4668
4669 string
4670 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4671 {
4672         string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4673
4674         if (Glib::path_is_absolute (filepath)) {
4675
4676                 /* rip the session dir from the audiofile source */
4677
4678                 string session_path;
4679                 bool in_another_session = true;
4680
4681                 if (filepath.find (interchange_dir_string) != string::npos) {
4682
4683                         session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4684                         session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4685                         session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4686                         session_path = Glib::path_get_dirname (session_path); /* now has session path */
4687
4688                         /* see if it is within our session */
4689
4690                         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4691                                 if (i->path == session_path) {
4692                                         in_another_session = false;
4693                                         break;
4694                                 }
4695                         }
4696                 } else {
4697                         in_another_session = false;
4698                 }
4699
4700
4701                 if (in_another_session) {
4702                         SessionDirectory sd (session_path);
4703                         return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4704                 }
4705         }
4706
4707         /* 1) if file belongs to this session
4708          * it may be a relative path (interchange/...)
4709          * or just basename (session_state, remove source)
4710          * -> just use the basename
4711          */
4712         std::string filename = Glib::path_get_basename (filepath);
4713         std::string path;
4714
4715         /* 2) if the file is outside our session dir:
4716          * (imported but not copied) add the path for check-summming */
4717         if (!in_session) {
4718                 path = Glib::path_get_dirname (filepath);
4719         }
4720
4721         return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4722 }
4723
4724 string
4725 Session::new_audio_source_path_for_embedded (const std::string& path)
4726 {
4727         /* embedded source:
4728          *
4729          * we know that the filename is already unique because it exists
4730          * out in the filesystem.
4731          *
4732          * However, when we bring it into the session, we could get a
4733          * collision.
4734          *
4735          * Eg. two embedded files:
4736          *
4737          *          /foo/bar/baz.wav
4738          *          /frob/nic/baz.wav
4739          *
4740          * When merged into session, these collide.
4741          *
4742          * There will not be a conflict with in-memory sources
4743          * because when the source was created we already picked
4744          * a unique name for it.
4745          *
4746          * This collision is not likely to be common, but we have to guard
4747          * against it.  So, if there is a collision, take the md5 hash of the
4748          * the path, and use that as the filename instead.
4749          */
4750
4751         SessionDirectory sdir (get_best_session_directory_for_new_audio());
4752         string base = Glib::path_get_basename (path);
4753         string newpath = Glib::build_filename (sdir.sound_path(), base);
4754
4755         if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4756
4757                 MD5 md5;
4758
4759                 md5.digestString (path.c_str());
4760                 md5.writeToString ();
4761                 base = md5.digestChars;
4762
4763                 string ext = get_suffix (path);
4764
4765                 if (!ext.empty()) {
4766                         base += '.';
4767                         base += ext;
4768                 }
4769
4770                 newpath = Glib::build_filename (sdir.sound_path(), base);
4771
4772                 /* if this collides, we're screwed */
4773
4774                 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4775                         error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4776                         return string();
4777                 }
4778
4779         }
4780
4781         return newpath;
4782 }
4783
4784 /** Return true if there are no audio file sources that use @param name as
4785  * the filename component of their path.
4786  *
4787  * Return false otherwise.
4788  *
4789  * This method MUST ONLY be used to check in-session, mono files since it
4790  * hard-codes the channel of the audio file source we are looking for as zero.
4791  *
4792  * If/when Ardour supports native files in non-mono formats, the logic here
4793  * will need to be revisited.
4794  */
4795 bool
4796 Session::audio_source_name_is_unique (const string& name)
4797 {
4798         std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4799         vector<space_and_path>::iterator i;
4800         uint32_t existing = 0;
4801
4802         for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4803
4804                 /* note that we search *without* the extension so that
4805                    we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4806                    in the event that this new name is required for
4807                    a file format change.
4808                 */
4809
4810                 const string spath = *i;
4811
4812                 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4813                         existing++;
4814                         break;
4815                 }
4816
4817                 /* it is possible that we have the path already
4818                  * assigned to a source that has not yet been written
4819                  * (ie. the write source for a diskstream). we have to
4820                  * check this in order to make sure that our candidate
4821                  * path isn't used again, because that can lead to
4822                  * two Sources point to the same file with different
4823                  * notions of their removability.
4824                  */
4825
4826
4827                 string possible_path = Glib::build_filename (spath, name);
4828
4829                 if (audio_source_by_path_and_channel (possible_path, 0)) {
4830                         existing++;
4831                         break;
4832                 }
4833         }
4834
4835         return (existing == 0);
4836 }
4837
4838 string
4839 Session::format_audio_source_name (const string& legalized_base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required, uint32_t cnt, bool related_exists)
4840 {
4841         ostringstream sstr;
4842         const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4843
4844         if (Profile->get_trx() && destructive) {
4845                 sstr << 'T';
4846                 sstr << setfill ('0') << setw (4) << cnt;
4847                 sstr << legalized_base;
4848         } else {
4849                 sstr << legalized_base;
4850
4851                 if (take_required || related_exists) {
4852                         sstr << '-';
4853                         sstr << cnt;
4854                 }
4855         }
4856
4857         if (nchan == 2) {
4858                 if (chan == 0) {
4859                         sstr << "%L";
4860                 } else {
4861                         sstr << "%R";
4862                 }
4863         } else if (nchan > 2) {
4864                 if (nchan < 26) {
4865                         sstr << '%';
4866                         sstr << 'a' + chan;
4867                 } else {
4868                         /* XXX what? more than 26 channels! */
4869                         sstr << '%';
4870                         sstr << chan+1;
4871                 }
4872         }
4873
4874         sstr << ext;
4875
4876         return sstr.str();
4877 }
4878
4879 /** Return a unique name based on \a base for a new internal audio source */
4880 string
4881 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4882 {
4883         uint32_t cnt;
4884         string possible_name;
4885         const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4886         string legalized;
4887         bool some_related_source_name_exists = false;
4888
4889         legalized = legalize_for_path (base);
4890
4891         // Find a "version" of the base name that doesn't exist in any of the possible directories.
4892
4893         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4894
4895                 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4896
4897                 if (audio_source_name_is_unique (possible_name)) {
4898                         break;
4899                 }
4900
4901                 some_related_source_name_exists = true;
4902
4903                 if (cnt > limit) {
4904                         error << string_compose(
4905                                         _("There are already %1 recordings for %2, which I consider too many."),
4906                                         limit, base) << endmsg;
4907                         destroy ();
4908                         throw failed_constructor();
4909                 }
4910         }
4911
4912         /* We've established that the new name does not exist in any session
4913          * directory, so now find out which one we should use for this new
4914          * audio source.
4915          */
4916
4917         SessionDirectory sdir (get_best_session_directory_for_new_audio());
4918
4919         std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4920
4921         return s;
4922 }
4923
4924 /** Return a unique name based on `base` for a new internal MIDI source */
4925 string
4926 Session::new_midi_source_path (const string& base)
4927 {
4928         uint32_t cnt;
4929         char buf[PATH_MAX+1];
4930         const uint32_t limit = 10000;
4931         string legalized;
4932         string possible_path;
4933         string possible_name;
4934
4935         buf[0] = '\0';
4936         legalized = legalize_for_path (base);
4937
4938         // Find a "version" of the file name that doesn't exist in any of the possible directories.
4939         std::vector<string> sdirs = source_search_path(DataType::MIDI);
4940
4941         /* - the main session folder is the first in the vector.
4942          * - after checking all locations for file-name uniqueness,
4943          *   we keep the one from the last iteration as new file name
4944          * - midi files are small and should just be kept in the main session-folder
4945          *
4946          * -> reverse the array, check main session folder last and use that as location
4947          *    for MIDI files.
4948          */
4949         std::reverse(sdirs.begin(), sdirs.end());
4950
4951         for (cnt = 1; cnt <= limit; ++cnt) {
4952
4953                 vector<space_and_path>::iterator i;
4954                 uint32_t existing = 0;
4955
4956                 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4957
4958                         snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4959                         possible_name = buf;
4960
4961                         possible_path = Glib::build_filename (*i, possible_name);
4962
4963                         if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4964                                 existing++;
4965                         }
4966
4967                         if (midi_source_by_path (possible_path)) {
4968                                 existing++;
4969                         }
4970                 }
4971
4972                 if (existing == 0) {
4973                         break;
4974                 }
4975
4976                 if (cnt > limit) {
4977                         error << string_compose(
4978                                         _("There are already %1 recordings for %2, which I consider too many."),
4979                                         limit, base) << endmsg;
4980                         destroy ();
4981                         return 0;
4982                 }
4983         }
4984
4985         /* No need to "find best location" for software/app-based RAID, because
4986            MIDI is so small that we always put it in the same place.
4987         */
4988
4989         return possible_path;
4990 }
4991
4992
4993 /** Create a new within-session audio source */
4994 boost::shared_ptr<AudioFileSource>
4995 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4996 {
4997         const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4998
4999         if (!path.empty()) {
5000                 return boost::dynamic_pointer_cast<AudioFileSource> (
5001                         SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5002         } else {
5003                 throw failed_constructor ();
5004         }
5005 }
5006
5007 /** Create a new within-session MIDI source */
5008 boost::shared_ptr<MidiSource>
5009 Session::create_midi_source_for_session (string const & basic_name)
5010 {
5011         const string path = new_midi_source_path (basic_name);
5012
5013         if (!path.empty()) {
5014                 return boost::dynamic_pointer_cast<SMFSource> (
5015                         SourceFactory::createWritable (
5016                                 DataType::MIDI, *this, path, false, frame_rate()));
5017         } else {
5018                 throw failed_constructor ();
5019         }
5020 }
5021
5022 /** Create a new within-session MIDI source */
5023 boost::shared_ptr<MidiSource>
5024 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5025 {
5026         /* the caller passes in the track the source will be used in,
5027            so that we can keep the numbering sane.
5028
5029            Rationale: a track with the name "Foo" that has had N
5030            captures carried out so far will ALREADY have a write source
5031            named "Foo-N+1.mid" waiting to be used for the next capture.
5032
5033            If we call new_midi_source_name() we will get "Foo-N+2". But
5034            there is no region corresponding to "Foo-N+1", so when
5035            "Foo-N+2" appears in the track, the gap presents the user
5036            with odd behaviour - why did it skip past Foo-N+1?
5037
5038            We could explain this to the user in some odd way, but
5039            instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5040            use "Foo-N+1" here.
5041
5042            If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5043         */
5044
5045         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5046         assert (mt);
5047         std::string name = track->steal_write_source_name ();
5048
5049         if (name.empty()) {
5050                 return boost::shared_ptr<MidiSource>();
5051         }
5052
5053         /* MIDI files are small, just put them in the first location of the
5054            session source search path.
5055         */
5056
5057         const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5058
5059         return boost::dynamic_pointer_cast<SMFSource> (
5060                 SourceFactory::createWritable (
5061                         DataType::MIDI, *this, path, false, frame_rate()));
5062 }
5063
5064
5065 void
5066 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5067 {
5068         if (playlist->hidden()) {
5069                 return;
5070         }
5071
5072         playlists->add (playlist);
5073
5074         if (unused) {
5075                 playlist->release();
5076         }
5077
5078         set_dirty();
5079 }
5080
5081 void
5082 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5083 {
5084         if (_state_of_the_state & Deletion) {
5085                 return;
5086         }
5087
5088         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5089
5090         if (!playlist) {
5091                 return;
5092         }
5093
5094         playlists->remove (playlist);
5095
5096         set_dirty();
5097 }
5098
5099 void
5100 Session::set_audition (boost::shared_ptr<Region> r)
5101 {
5102         pending_audition_region = r;
5103         add_post_transport_work (PostTransportAudition);
5104         _butler->schedule_transport_work ();
5105 }
5106
5107 void
5108 Session::audition_playlist ()
5109 {
5110         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5111         ev->region.reset ();
5112         queue_event (ev);
5113 }
5114
5115
5116 void
5117 Session::register_lua_function (
5118                 const std::string& name,
5119                 const std::string& script,
5120                 const LuaScriptParamList& args
5121                 )
5122 {
5123         Glib::Threads::Mutex::Lock lm (lua_lock);
5124
5125         lua_State* L = lua.getState();
5126
5127         const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5128         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5129         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5130                 if ((*i)->optional && !(*i)->is_set) { continue; }
5131                 tbl_arg[(*i)->name] = (*i)->value;
5132         }
5133         (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5134         set_dirty();
5135 }
5136
5137 void
5138 Session::unregister_lua_function (const std::string& name)
5139 {
5140         Glib::Threads::Mutex::Lock lm (lua_lock);
5141         (*_lua_del)(name); // throws luabridge::LuaException
5142         lua.collect_garbage ();
5143         set_dirty();
5144 }
5145
5146 std::vector<std::string>
5147 Session::registered_lua_functions ()
5148 {
5149         Glib::Threads::Mutex::Lock lm (lua_lock);
5150         std::vector<std::string> rv;
5151
5152         try {
5153                 luabridge::LuaRef list ((*_lua_list)());
5154                 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5155                         if (!i.key ().isString ()) { assert(0); continue; }
5156                         rv.push_back (i.key ().cast<std::string> ());
5157                 }
5158         } catch (luabridge::LuaException const& e) { }
5159         return rv;
5160 }
5161
5162 #ifndef NDEBUG
5163 static void _lua_print (std::string s) {
5164         std::cout << "SessionLua: " << s << "\n";
5165 }
5166 #endif
5167
5168 void
5169 Session::try_run_lua (pframes_t nframes)
5170 {
5171         if (_n_lua_scripts == 0) return;
5172         Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5173         if (tm.locked ()) {
5174                 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5175                 lua.collect_garbage_step ();
5176         }
5177 }
5178
5179 void
5180 Session::setup_lua ()
5181 {
5182 #ifndef NDEBUG
5183         lua.Print.connect (&_lua_print);
5184 #endif
5185         lua.tweak_rt_gc ();
5186         lua.do_command (
5187                         "function ArdourSession ()"
5188                         "  local self = { scripts = {}, instances = {} }"
5189                         ""
5190                         "  local remove = function (n)"
5191                         "   self.scripts[n] = nil"
5192                         "   self.instances[n] = nil"
5193                         "   Session:scripts_changed()" // call back
5194                         "  end"
5195                         ""
5196                         "  local addinternal = function (n, f, a)"
5197                         "   assert(type(n) == 'string', 'function-name must be string')"
5198                         "   assert(type(f) == 'function', 'Given script is a not a function')"
5199                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5200                         "   assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5201                         "   self.scripts[n] = { ['f'] = f, ['a'] = a }"
5202                         "   local env = _ENV;  env.f = nil env.io = nil env.os = nil env.loadfile = nil env.require = nil env.dofile = nil env.package = nil env.debug = nil"
5203                         "   local env = { print = print, tostring = tostring, assert = assert, ipairs = ipairs, error = error, select = select, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall, Session = Session, PBD = PBD, Timecode = Timecode, Evoral = Evoral, C = C, ARDOUR = ARDOUR }"
5204                         "   self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5205                         "   Session:scripts_changed()" // call back
5206                         "  end"
5207                         ""
5208                         "  local add = function (n, b, a)"
5209                         "   assert(type(b) == 'string', 'ByteCode must be string')"
5210                         "   load (b)()" // assigns f
5211                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5212                         "   addinternal (n, load(f), a)"
5213                         "  end"
5214                         ""
5215                         "  local run = function (...)"
5216                         "   for n, s in pairs (self.instances) do"
5217                         "     local status, err = pcall (s, ...)"
5218                         "     if not status then"
5219                         "       print ('fn \"'.. n .. '\": ', err)"
5220                         "       remove (n)"
5221                         "      end"
5222                         "   end"
5223                         "   collectgarbage()"
5224                         "  end"
5225                         ""
5226                         "  local cleanup = function ()"
5227                         "   self.scripts = nil"
5228                         "   self.instances = nil"
5229                         "  end"
5230                         ""
5231                         "  local list = function ()"
5232                         "   local rv = {}"
5233                         "   for n, _ in pairs (self.scripts) do"
5234                         "     rv[n] = true"
5235                         "   end"
5236                         "   return rv"
5237                         "  end"
5238                         ""
5239                         "  local function basic_serialize (o)"
5240                         "    if type(o) == \"number\" then"
5241                         "     return tostring(o)"
5242                         "    else"
5243                         "     return string.format(\"%q\", o)"
5244                         "    end"
5245                         "  end"
5246                         ""
5247                         "  local function serialize (name, value)"
5248                         "   local rv = name .. ' = '"
5249                         "   collectgarbage()"
5250                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5251                         "    return rv .. basic_serialize(value) .. ' '"
5252                         "   elseif type(value) == \"table\" then"
5253                         "    rv = rv .. '{} '"
5254                         "    for k,v in pairs(value) do"
5255                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5256                         "     rv = rv .. serialize(fieldname, v) .. ' '"
5257                         "     collectgarbage()" // string concatenation allocates a new string :(
5258                         "    end"
5259                         "    return rv;"
5260                         "   elseif type(value) == \"function\" then"
5261                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
5262                         "   else"
5263                         "    error('cannot save a ' .. type(value))"
5264                         "   end"
5265                         "  end"
5266                         ""
5267                         ""
5268                         "  local save = function ()"
5269                         "   return (serialize('scripts', self.scripts))"
5270                         "  end"
5271                         ""
5272                         "  local restore = function (state)"
5273                         "   self.scripts = {}"
5274                         "   load (state)()"
5275                         "   for n, s in pairs (scripts) do"
5276                         "    addinternal (n, load(s['f']), s['a'])"
5277                         "   end"
5278                         "  end"
5279                         ""
5280                         " return { run = run, add = add, remove = remove,"
5281                   "          list = list, restore = restore, save = save, cleanup = cleanup}"
5282                         " end"
5283                         " "
5284                         " sess = ArdourSession ()"
5285                         " ArdourSession = nil"
5286                         " "
5287                         "function ardour () end"
5288                         );
5289
5290         lua_State* L = lua.getState();
5291
5292         try {
5293                 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5294                 lua.do_command ("sess = nil"); // hide it.
5295                 lua.do_command ("collectgarbage()");
5296
5297                 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5298                 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5299                 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5300                 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5301                 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5302                 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5303                 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5304         } catch (luabridge::LuaException const& e) {
5305                 fatal << string_compose (_("programming error: %1"),
5306                                 X_("Failed to setup Lua interpreter"))
5307                         << endmsg;
5308                 abort(); /*NOTREACHED*/
5309         }
5310
5311         LuaBindings::stddef (L);
5312         LuaBindings::common (L);
5313         LuaBindings::dsp (L);
5314         luabridge::push <Session *> (L, this);
5315         lua_setglobal (L, "Session");
5316 }
5317
5318 void
5319 Session::scripts_changed ()
5320 {
5321         assert (!lua_lock.trylock()); // must hold lua_lock
5322
5323         try {
5324                 luabridge::LuaRef list ((*_lua_list)());
5325                 int cnt = 0;
5326                 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5327                         if (!i.key ().isString ()) { assert(0); continue; }
5328                         ++cnt;
5329                 }
5330                 _n_lua_scripts = cnt;
5331         } catch (luabridge::LuaException const& e) {
5332                 fatal << string_compose (_("programming error: %1"),
5333                                 X_("Indexing Lua Session Scripts failed."))
5334                         << endmsg;
5335                 abort(); /*NOTREACHED*/
5336         }
5337 }
5338
5339 void
5340 Session::non_realtime_set_audition ()
5341 {
5342         assert (pending_audition_region);
5343         auditioner->audition_region (pending_audition_region);
5344         pending_audition_region.reset ();
5345         AuditionActive (true); /* EMIT SIGNAL */
5346 }
5347
5348 void
5349 Session::audition_region (boost::shared_ptr<Region> r)
5350 {
5351         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5352         ev->region = r;
5353         queue_event (ev);
5354 }
5355
5356 void
5357 Session::cancel_audition ()
5358 {
5359         if (!auditioner) {
5360                 return;
5361         }
5362         if (auditioner->auditioning()) {
5363                 auditioner->cancel_audition ();
5364                 AuditionActive (false); /* EMIT SIGNAL */
5365         }
5366 }
5367
5368 bool
5369 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5370 {
5371         if (a->is_monitor()) {
5372                 return true;
5373         }
5374         if (b->is_monitor()) {
5375                 return false;
5376         }
5377         return a->presentation_info().order() < b->presentation_info().order();
5378 }
5379
5380 bool
5381 Session::is_auditioning () const
5382 {
5383         /* can be called before we have an auditioner object */
5384         if (auditioner) {
5385                 return auditioner->auditioning();
5386         } else {
5387                 return false;
5388         }
5389 }
5390
5391 void
5392 Session::graph_reordered ()
5393 {
5394         /* don't do this stuff if we are setting up connections
5395            from a set_state() call or creating new tracks. Ditto for deletion.
5396         */
5397
5398         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5399                 return;
5400         }
5401
5402         /* every track/bus asked for this to be handled but it was deferred because
5403            we were connecting. do it now.
5404         */
5405
5406         request_input_change_handling ();
5407
5408         resort_routes ();
5409
5410         /* force all diskstreams to update their capture offset values to
5411            reflect any changes in latencies within the graph.
5412         */
5413
5414         boost::shared_ptr<RouteList> rl = routes.reader ();
5415         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5416                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5417                 if (tr) {
5418                         tr->set_capture_offset ();
5419                 }
5420         }
5421 }
5422
5423 /** @return Number of frames that there is disk space available to write,
5424  *  if known.
5425  */
5426 boost::optional<framecnt_t>
5427 Session::available_capture_duration ()
5428 {
5429         Glib::Threads::Mutex::Lock lm (space_lock);
5430
5431         if (_total_free_4k_blocks_uncertain) {
5432                 return boost::optional<framecnt_t> ();
5433         }
5434
5435         float sample_bytes_on_disk = 4.0; // keep gcc happy
5436
5437         switch (config.get_native_file_data_format()) {
5438         case FormatFloat:
5439                 sample_bytes_on_disk = 4.0;
5440                 break;
5441
5442         case FormatInt24:
5443                 sample_bytes_on_disk = 3.0;
5444                 break;
5445
5446         case FormatInt16:
5447                 sample_bytes_on_disk = 2.0;
5448                 break;
5449
5450         default:
5451                 /* impossible, but keep some gcc versions happy */
5452                 fatal << string_compose (_("programming error: %1"),
5453                                          X_("illegal native file data format"))
5454                       << endmsg;
5455                 abort(); /*NOTREACHED*/
5456         }
5457
5458         double scale = 4096.0 / sample_bytes_on_disk;
5459
5460         if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5461                 return max_framecnt;
5462         }
5463
5464         return (framecnt_t) floor (_total_free_4k_blocks * scale);
5465 }
5466
5467 void
5468 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5469 {
5470         {
5471                 RCUWriter<BundleList> writer (_bundles);
5472                 boost::shared_ptr<BundleList> b = writer.get_copy ();
5473                 b->push_back (bundle);
5474         }
5475
5476         if (emit_signal) {
5477                 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5478         }
5479
5480         set_dirty();
5481 }
5482
5483 void
5484 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5485 {
5486         bool removed = false;
5487
5488         {
5489                 RCUWriter<BundleList> writer (_bundles);
5490                 boost::shared_ptr<BundleList> b = writer.get_copy ();
5491                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5492
5493                 if (i != b->end()) {
5494                         b->erase (i);
5495                         removed = true;
5496                 }
5497         }
5498
5499         if (removed) {
5500                  BundleAddedOrRemoved (); /* EMIT SIGNAL */
5501         }
5502
5503         set_dirty();
5504 }
5505
5506 boost::shared_ptr<Bundle>
5507 Session::bundle_by_name (string name) const
5508 {
5509         boost::shared_ptr<BundleList> b = _bundles.reader ();
5510
5511         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5512                 if ((*i)->name() == name) {
5513                         return* i;
5514                 }
5515         }
5516
5517         return boost::shared_ptr<Bundle> ();
5518 }
5519
5520 void
5521 Session::tempo_map_changed (const PropertyChange&)
5522 {
5523         clear_clicks ();
5524
5525         playlists->update_after_tempo_map_change ();
5526
5527         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5528
5529         set_dirty ();
5530 }
5531
5532 void
5533 Session::gui_tempo_map_changed ()
5534 {
5535         clear_clicks ();
5536
5537         playlists->update_after_tempo_map_change ();
5538
5539         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5540 }
5541
5542 void
5543 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5544 {
5545         for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5546                 (*i)->recompute_frames_from_bbt ();
5547         }
5548 }
5549
5550 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5551  * the given count with the current block size.
5552  */
5553 void
5554 Session::ensure_buffers (ChanCount howmany)
5555 {
5556         BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5557 }
5558
5559 void
5560 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5561 {
5562         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5563                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5564         }
5565 }
5566
5567 uint32_t
5568 Session::next_insert_id ()
5569 {
5570         /* this doesn't really loop forever. just think about it */
5571
5572         while (true) {
5573                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5574                         if (!insert_bitset[n]) {
5575                                 insert_bitset[n] = true;
5576                                 return n;
5577
5578                         }
5579                 }
5580
5581                 /* none available, so resize and try again */
5582
5583                 insert_bitset.resize (insert_bitset.size() + 16, false);
5584         }
5585 }
5586
5587 uint32_t
5588 Session::next_send_id ()
5589 {
5590         /* this doesn't really loop forever. just think about it */
5591
5592         while (true) {
5593                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5594                         if (!send_bitset[n]) {
5595                                 send_bitset[n] = true;
5596                                 return n;
5597
5598                         }
5599                 }
5600
5601                 /* none available, so resize and try again */
5602
5603                 send_bitset.resize (send_bitset.size() + 16, false);
5604         }
5605 }
5606
5607 uint32_t
5608 Session::next_aux_send_id ()
5609 {
5610         /* this doesn't really loop forever. just think about it */
5611
5612         while (true) {
5613                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5614                         if (!aux_send_bitset[n]) {
5615                                 aux_send_bitset[n] = true;
5616                                 return n;
5617
5618                         }
5619                 }
5620
5621                 /* none available, so resize and try again */
5622
5623                 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5624         }
5625 }
5626
5627 uint32_t
5628 Session::next_return_id ()
5629 {
5630         /* this doesn't really loop forever. just think about it */
5631
5632         while (true) {
5633                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5634                         if (!return_bitset[n]) {
5635                                 return_bitset[n] = true;
5636                                 return n;
5637
5638                         }
5639                 }
5640
5641                 /* none available, so resize and try again */
5642
5643                 return_bitset.resize (return_bitset.size() + 16, false);
5644         }
5645 }
5646
5647 void
5648 Session::mark_send_id (uint32_t id)
5649 {
5650         if (id >= send_bitset.size()) {
5651                 send_bitset.resize (id+16, false);
5652         }
5653         if (send_bitset[id]) {
5654                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5655         }
5656         send_bitset[id] = true;
5657 }
5658
5659 void
5660 Session::mark_aux_send_id (uint32_t id)
5661 {
5662         if (id >= aux_send_bitset.size()) {
5663                 aux_send_bitset.resize (id+16, false);
5664         }
5665         if (aux_send_bitset[id]) {
5666                 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5667         }
5668         aux_send_bitset[id] = true;
5669 }
5670
5671 void
5672 Session::mark_return_id (uint32_t id)
5673 {
5674         if (id >= return_bitset.size()) {
5675                 return_bitset.resize (id+16, false);
5676         }
5677         if (return_bitset[id]) {
5678                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5679         }
5680         return_bitset[id] = true;
5681 }
5682
5683 void
5684 Session::mark_insert_id (uint32_t id)
5685 {
5686         if (id >= insert_bitset.size()) {
5687                 insert_bitset.resize (id+16, false);
5688         }
5689         if (insert_bitset[id]) {
5690                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5691         }
5692         insert_bitset[id] = true;
5693 }
5694
5695 void
5696 Session::unmark_send_id (uint32_t id)
5697 {
5698         if (id < send_bitset.size()) {
5699                 send_bitset[id] = false;
5700         }
5701 }
5702
5703 void
5704 Session::unmark_aux_send_id (uint32_t id)
5705 {
5706         if (id < aux_send_bitset.size()) {
5707                 aux_send_bitset[id] = false;
5708         }
5709 }
5710
5711 void
5712 Session::unmark_return_id (uint32_t id)
5713 {
5714         if (_state_of_the_state & Deletion) { return; }
5715         if (id < return_bitset.size()) {
5716                 return_bitset[id] = false;
5717         }
5718 }
5719
5720 void
5721 Session::unmark_insert_id (uint32_t id)
5722 {
5723         if (id < insert_bitset.size()) {
5724                 insert_bitset[id] = false;
5725         }
5726 }
5727
5728 void
5729 Session::reset_native_file_format ()
5730 {
5731         boost::shared_ptr<RouteList> rl = routes.reader ();
5732
5733         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5734                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5735                 if (tr) {
5736                         /* don't save state as we do this, there's no point
5737                          */
5738                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5739                         tr->reset_write_sources (false);
5740                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5741                 }
5742         }
5743 }
5744
5745 bool
5746 Session::route_name_unique (string n) const
5747 {
5748         boost::shared_ptr<RouteList> r = routes.reader ();
5749
5750         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5751                 if ((*i)->name() == n) {
5752                         return false;
5753                 }
5754         }
5755
5756         return true;
5757 }
5758
5759 bool
5760 Session::route_name_internal (string n) const
5761 {
5762         if (auditioner && auditioner->name() == n) {
5763                 return true;
5764         }
5765
5766         if (_click_io && _click_io->name() == n) {
5767                 return true;
5768         }
5769
5770         return false;
5771 }
5772
5773 int
5774 Session::freeze_all (InterThreadInfo& itt)
5775 {
5776         boost::shared_ptr<RouteList> r = routes.reader ();
5777
5778         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5779
5780                 boost::shared_ptr<Track> t;
5781
5782                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5783                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
5784                            of every track.
5785                         */
5786                         t->freeze_me (itt);
5787                 }
5788         }
5789
5790         return 0;
5791 }
5792
5793 boost::shared_ptr<Region>
5794 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5795                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5796                           InterThreadInfo& itt,
5797                           boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5798                           bool for_export, bool for_freeze)
5799 {
5800         boost::shared_ptr<Region> result;
5801         boost::shared_ptr<Playlist> playlist;
5802         boost::shared_ptr<Source> source;
5803         ChanCount diskstream_channels (track.n_channels());
5804         framepos_t position;
5805         framecnt_t this_chunk;
5806         framepos_t to_do;
5807         framepos_t latency_skip;
5808         BufferSet buffers;
5809         framepos_t len = end - start;
5810         bool need_block_size_reset = false;
5811         ChanCount const max_proc = track.max_processor_streams ();
5812         string legal_playlist_name;
5813         string possible_path;
5814
5815         if (end <= start) {
5816                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5817                                          end, start) << endmsg;
5818                 return result;
5819         }
5820
5821         diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5822                         include_endpoint, for_export, for_freeze);
5823
5824         if (diskstream_channels.n(track.data_type()) < 1) {
5825                 error << _("Cannot write a range with no data.") << endmsg;
5826                 return result;
5827         }
5828
5829         // block all process callback handling
5830
5831         block_processing ();
5832
5833         {
5834                 // synchronize with AudioEngine::process_callback()
5835                 // make sure processing is not currently running
5836                 // and processing_blocked() is honored before
5837                 // acquiring thread buffers
5838                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5839         }
5840
5841         _bounce_processing_active = true;
5842
5843         /* call tree *MUST* hold route_lock */
5844
5845         if ((playlist = track.playlist()) == 0) {
5846                 goto out;
5847         }
5848
5849         legal_playlist_name = legalize_for_path (playlist->name());
5850
5851         for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5852
5853                 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5854                 string path = ((track.data_type() == DataType::AUDIO)
5855                                ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5856                                : new_midi_source_path (legal_playlist_name));
5857
5858                 if (path.empty()) {
5859                         goto out;
5860                 }
5861
5862                 try {
5863                         source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5864                 }
5865
5866                 catch (failed_constructor& err) {
5867                         error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5868                         goto out;
5869                 }
5870
5871                 srcs.push_back (source);
5872         }
5873
5874         /* tell redirects that care that we are about to use a much larger
5875          * blocksize. this will flush all plugins too, so that they are ready
5876          * to be used for this process.
5877          */
5878
5879         need_block_size_reset = true;
5880         track.set_block_size (bounce_chunk_size);
5881         _engine.main_thread()->get_buffers ();
5882
5883         position = start;
5884         to_do = len;
5885         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5886
5887         /* create a set of reasonably-sized buffers */
5888         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5889                 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5890         }
5891         buffers.set_count (max_proc);
5892
5893         for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5894                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5895                 boost::shared_ptr<MidiSource> ms;
5896                 if (afs) {
5897                         afs->prepare_for_peakfile_writes ();
5898                 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5899                         Source::Lock lock(ms->mutex());
5900                         ms->mark_streaming_write_started(lock);
5901                 }
5902         }
5903
5904         while (to_do && !itt.cancel) {
5905
5906                 this_chunk = min (to_do, bounce_chunk_size);
5907
5908                 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5909                         goto out;
5910                 }
5911
5912                 start += this_chunk;
5913                 to_do -= this_chunk;
5914                 itt.progress = (float) (1.0 - ((double) to_do / len));
5915
5916                 if (latency_skip >= bounce_chunk_size) {
5917                         latency_skip -= bounce_chunk_size;
5918                         continue;
5919                 }
5920
5921                 const framecnt_t current_chunk = this_chunk - latency_skip;
5922
5923                 uint32_t n = 0;
5924                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5925                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5926                         boost::shared_ptr<MidiSource> ms;
5927
5928                         if (afs) {
5929                                 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5930                                         goto out;
5931                                 }
5932                         } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5933                                 Source::Lock lock(ms->mutex());
5934
5935                                 const MidiBuffer& buf = buffers.get_midi(0);
5936                                 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5937                                         Evoral::Event<framepos_t> ev = *i;
5938                                         ev.set_time(ev.time() - position);
5939                                         ms->append_event_frames(lock, ev, ms->timeline_position());
5940                                 }
5941                         }
5942                 }
5943                 latency_skip = 0;
5944         }
5945
5946         /* post-roll, pick up delayed processor output */
5947         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5948
5949         while (latency_skip && !itt.cancel) {
5950                 this_chunk = min (latency_skip, bounce_chunk_size);
5951                 latency_skip -= this_chunk;
5952
5953                 buffers.silence (this_chunk, 0);
5954                 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5955
5956                 uint32_t n = 0;
5957                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5958                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5959
5960                         if (afs) {
5961                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5962                                         goto out;
5963                                 }
5964                         }
5965                 }
5966         }
5967
5968         if (!itt.cancel) {
5969
5970                 time_t now;
5971                 struct tm* xnow;
5972                 time (&now);
5973                 xnow = localtime (&now);
5974
5975                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5976                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5977                         boost::shared_ptr<MidiSource> ms;
5978
5979                         if (afs) {
5980                                 afs->update_header (position, *xnow, now);
5981                                 afs->flush_header ();
5982                         } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5983                                 Source::Lock lock(ms->mutex());
5984                                 ms->mark_streaming_write_completed(lock);
5985                         }
5986                 }
5987
5988                 /* construct a region to represent the bounced material */
5989
5990                 PropertyList plist;
5991
5992                 plist.add (Properties::start, 0);
5993                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5994                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5995
5996                 result = RegionFactory::create (srcs, plist);
5997
5998         }
5999
6000   out:
6001         if (!result) {
6002                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6003                         (*src)->mark_for_remove ();
6004                         (*src)->drop_references ();
6005                 }
6006
6007         } else {
6008                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6009                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6010
6011                         if (afs)
6012                                 afs->done_with_peakfile_writes ();
6013                 }
6014         }
6015
6016         _bounce_processing_active = false;
6017
6018         if (need_block_size_reset) {
6019                 _engine.main_thread()->drop_buffers ();
6020                 track.set_block_size (get_block_size());
6021         }
6022
6023         unblock_processing ();
6024
6025         return result;
6026 }
6027
6028 gain_t*
6029 Session::gain_automation_buffer() const
6030 {
6031         return ProcessThread::gain_automation_buffer ();
6032 }
6033
6034 gain_t*
6035 Session::trim_automation_buffer() const
6036 {
6037         return ProcessThread::trim_automation_buffer ();
6038 }
6039
6040 gain_t*
6041 Session::send_gain_automation_buffer() const
6042 {
6043         return ProcessThread::send_gain_automation_buffer ();
6044 }
6045
6046 pan_t**
6047 Session::pan_automation_buffer() const
6048 {
6049         return ProcessThread::pan_automation_buffer ();
6050 }
6051
6052 BufferSet&
6053 Session::get_silent_buffers (ChanCount count)
6054 {
6055         return ProcessThread::get_silent_buffers (count);
6056 }
6057
6058 BufferSet&
6059 Session::get_scratch_buffers (ChanCount count, bool silence)
6060 {
6061         return ProcessThread::get_scratch_buffers (count, silence);
6062 }
6063
6064 BufferSet&
6065 Session::get_noinplace_buffers (ChanCount count)
6066 {
6067         return ProcessThread::get_noinplace_buffers (count);
6068 }
6069
6070 BufferSet&
6071 Session::get_route_buffers (ChanCount count, bool silence)
6072 {
6073         return ProcessThread::get_route_buffers (count, silence);
6074 }
6075
6076
6077 BufferSet&
6078 Session::get_mix_buffers (ChanCount count)
6079 {
6080         return ProcessThread::get_mix_buffers (count);
6081 }
6082
6083 uint32_t
6084 Session::ntracks () const
6085 {
6086         uint32_t n = 0;
6087         boost::shared_ptr<RouteList> r = routes.reader ();
6088
6089         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6090                 if (boost::dynamic_pointer_cast<Track> (*i)) {
6091                         ++n;
6092                 }
6093         }
6094
6095         return n;
6096 }
6097
6098 uint32_t
6099 Session::nbusses () const
6100 {
6101         uint32_t n = 0;
6102         boost::shared_ptr<RouteList> r = routes.reader ();
6103
6104         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6105                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6106                         ++n;
6107                 }
6108         }
6109
6110         return n;
6111 }
6112
6113 void
6114 Session::add_automation_list(AutomationList *al)
6115 {
6116         automation_lists[al->id()] = al;
6117 }
6118
6119 /** @return true if there is at least one record-enabled track, otherwise false */
6120 bool
6121 Session::have_rec_enabled_track () const
6122 {
6123         return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6124 }
6125
6126 bool
6127 Session::have_rec_disabled_track () const
6128 {
6129     return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6130 }
6131
6132 /** Update the state of our rec-enabled tracks flag */
6133 void
6134 Session::update_route_record_state ()
6135 {
6136         boost::shared_ptr<RouteList> rl = routes.reader ();
6137         RouteList::iterator i = rl->begin();
6138         while (i != rl->end ()) {
6139
6140                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6141                                     if (tr && tr->rec_enable_control()->get_value()) {
6142                         break;
6143                 }
6144
6145                 ++i;
6146         }
6147
6148         int const old = g_atomic_int_get (&_have_rec_enabled_track);
6149
6150         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6151
6152         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6153                 RecordStateChanged (); /* EMIT SIGNAL */
6154         }
6155
6156         for (i = rl->begin(); i != rl->end (); ++i) {
6157                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6158                 if (tr && !tr->rec_enable_control()->get_value()) {
6159                         break;
6160                 }
6161         }
6162
6163         g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6164
6165         bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6166
6167         if (record_status() == Recording && record_arm_state_changed ) {
6168                 RecordArmStateChanged ();
6169         }
6170
6171 }
6172
6173 void
6174 Session::listen_position_changed ()
6175 {
6176         boost::shared_ptr<RouteList> r = routes.reader ();
6177
6178         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6179                 (*i)->listen_position_changed ();
6180         }
6181 }
6182
6183 void
6184 Session::solo_control_mode_changed ()
6185 {
6186         if (soloing() || listening()) {
6187                 /* We can't use ::clear_all_solo_state() here because during
6188                    session loading at program startup, that will queue a call
6189                    to rt_clear_all_solo_state() that will not execute until
6190                    AFTER solo states have been established (thus throwing away
6191                    the session's saved solo state). So just explicitly turn
6192                    them all off.
6193                 */
6194                 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6195         }
6196 }
6197
6198 /** Called when a property of one of our route groups changes */
6199 void
6200 Session::route_group_property_changed (RouteGroup* rg)
6201 {
6202         RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6203 }
6204
6205 /** Called when a route is added to one of our route groups */
6206 void
6207 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6208 {
6209         RouteAddedToRouteGroup (rg, r);
6210 }
6211
6212 /** Called when a route is removed from one of our route groups */
6213 void
6214 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6215 {
6216         update_route_record_state ();
6217         RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6218 }
6219
6220 boost::shared_ptr<RouteList>
6221 Session::get_tracks () const
6222 {
6223         boost::shared_ptr<RouteList> rl = routes.reader ();
6224         boost::shared_ptr<RouteList> tl (new RouteList);
6225
6226         for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6227                 if (boost::dynamic_pointer_cast<Track> (*r)) {
6228                         if (!(*r)->is_auditioner()) {
6229                                 tl->push_back (*r);
6230                         }
6231                 }
6232         }
6233         return tl;
6234 }
6235
6236 boost::shared_ptr<RouteList>
6237 Session::get_routes_with_regions_at (framepos_t const p) const
6238 {
6239         boost::shared_ptr<RouteList> r = routes.reader ();
6240         boost::shared_ptr<RouteList> rl (new RouteList);
6241
6242         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6243                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6244                 if (!tr) {
6245                         continue;
6246                 }
6247
6248                 boost::shared_ptr<Playlist> pl = tr->playlist ();
6249                 if (!pl) {
6250                         continue;
6251                 }
6252
6253                 if (pl->has_region_at (p)) {
6254                         rl->push_back (*i);
6255                 }
6256         }
6257
6258         return rl;
6259 }
6260
6261 void
6262 Session::goto_end ()
6263 {
6264         if (_session_range_location) {
6265                 request_locate (_session_range_location->end(), false);
6266         } else {
6267                 request_locate (0, false);
6268         }
6269 }
6270
6271 void
6272 Session::goto_start ()
6273 {
6274         if (_session_range_location) {
6275                 request_locate (_session_range_location->start(), false);
6276         } else {
6277                 request_locate (0, false);
6278         }
6279 }
6280
6281 framepos_t
6282 Session::current_start_frame () const
6283 {
6284         return _session_range_location ? _session_range_location->start() : 0;
6285 }
6286
6287 framepos_t
6288 Session::current_end_frame () const
6289 {
6290         return _session_range_location ? _session_range_location->end() : 0;
6291 }
6292
6293 void
6294 Session::set_session_range_location (framepos_t start, framepos_t end)
6295 {
6296         _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6297         _locations->add (_session_range_location);
6298 }
6299
6300 void
6301 Session::step_edit_status_change (bool yn)
6302 {
6303         bool send = false;
6304
6305         bool val = false;
6306         if (yn) {
6307                 send = (_step_editors == 0);
6308                 val = true;
6309
6310                 _step_editors++;
6311         } else {
6312                 send = (_step_editors == 1);
6313                 val = false;
6314
6315                 if (_step_editors > 0) {
6316                         _step_editors--;
6317                 }
6318         }
6319
6320         if (send) {
6321                 StepEditStatusChange (val);
6322         }
6323 }
6324
6325
6326 void
6327 Session::start_time_changed (framepos_t old)
6328 {
6329         /* Update the auto loop range to match the session range
6330            (unless the auto loop range has been changed by the user)
6331         */
6332
6333         Location* s = _locations->session_range_location ();
6334         if (s == 0) {
6335                 return;
6336         }
6337
6338         Location* l = _locations->auto_loop_location ();
6339
6340         if (l && l->start() == old) {
6341                 l->set_start (s->start(), true);
6342         }
6343 }
6344
6345 void
6346 Session::end_time_changed (framepos_t old)
6347 {
6348         /* Update the auto loop range to match the session range
6349            (unless the auto loop range has been changed by the user)
6350         */
6351
6352         Location* s = _locations->session_range_location ();
6353         if (s == 0) {
6354                 return;
6355         }
6356
6357         Location* l = _locations->auto_loop_location ();
6358
6359         if (l && l->end() == old) {
6360                 l->set_end (s->end(), true);
6361         }
6362 }
6363
6364 std::vector<std::string>
6365 Session::source_search_path (DataType type) const
6366 {
6367         Searchpath sp;
6368
6369         if (session_dirs.size() == 1) {
6370                 switch (type) {
6371                 case DataType::AUDIO:
6372                         sp.push_back (_session_dir->sound_path());
6373                         break;
6374                 case DataType::MIDI:
6375                         sp.push_back (_session_dir->midi_path());
6376                         break;
6377                 }
6378         } else {
6379                 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6380                         SessionDirectory sdir (i->path);
6381                         switch (type) {
6382                         case DataType::AUDIO:
6383                                 sp.push_back (sdir.sound_path());
6384                                 break;
6385                         case DataType::MIDI:
6386                                 sp.push_back (sdir.midi_path());
6387                                 break;
6388                         }
6389                 }
6390         }
6391
6392         if (type == DataType::AUDIO) {
6393                 const string sound_path_2X = _session_dir->sound_path_2X();
6394                 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6395                         if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6396                                 sp.push_back (sound_path_2X);
6397                         }
6398                 }
6399         }
6400
6401         // now check the explicit (possibly user-specified) search path
6402
6403         switch (type) {
6404         case DataType::AUDIO:
6405                 sp += Searchpath(config.get_audio_search_path ());
6406                 break;
6407         case DataType::MIDI:
6408                 sp += Searchpath(config.get_midi_search_path ());
6409                 break;
6410         }
6411
6412         return sp;
6413 }
6414
6415 void
6416 Session::ensure_search_path_includes (const string& path, DataType type)
6417 {
6418         Searchpath sp;
6419
6420         if (path == ".") {
6421                 return;
6422         }
6423
6424         switch (type) {
6425         case DataType::AUDIO:
6426                 sp += Searchpath(config.get_audio_search_path ());
6427                 break;
6428         case DataType::MIDI:
6429                 sp += Searchpath (config.get_midi_search_path ());
6430                 break;
6431         }
6432
6433         for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6434                 /* No need to add this new directory if it has the same inode as
6435                    an existing one; checking inode rather than name prevents duplicated
6436                    directories when we are using symlinks.
6437
6438                    On Windows, I think we could just do if (*i == path) here.
6439                 */
6440                 if (PBD::equivalent_paths (*i, path)) {
6441                         return;
6442                 }
6443         }
6444
6445         sp += path;
6446
6447         switch (type) {
6448         case DataType::AUDIO:
6449                 config.set_audio_search_path (sp.to_string());
6450                 break;
6451         case DataType::MIDI:
6452                 config.set_midi_search_path (sp.to_string());
6453                 break;
6454         }
6455 }
6456
6457 void
6458 Session::remove_dir_from_search_path (const string& dir, DataType type)
6459 {
6460         Searchpath sp;
6461
6462         switch (type) {
6463         case DataType::AUDIO:
6464                 sp = Searchpath(config.get_audio_search_path ());
6465                 break;
6466         case DataType::MIDI:
6467                 sp = Searchpath (config.get_midi_search_path ());
6468                 break;
6469         }
6470
6471         sp -= dir;
6472
6473         switch (type) {
6474         case DataType::AUDIO:
6475                 config.set_audio_search_path (sp.to_string());
6476                 break;
6477         case DataType::MIDI:
6478                 config.set_midi_search_path (sp.to_string());
6479                 break;
6480         }
6481
6482 }
6483
6484 boost::shared_ptr<Speakers>
6485 Session::get_speakers()
6486 {
6487         return _speakers;
6488 }
6489
6490 list<string>
6491 Session::unknown_processors () const
6492 {
6493         list<string> p;
6494
6495         boost::shared_ptr<RouteList> r = routes.reader ();
6496         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6497                 list<string> t = (*i)->unknown_processors ();
6498                 copy (t.begin(), t.end(), back_inserter (p));
6499         }
6500
6501         p.sort ();
6502         p.unique ();
6503
6504         return p;
6505 }
6506
6507 void
6508 Session::update_latency (bool playback)
6509 {
6510
6511         DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6512
6513         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6514                 return;
6515         }
6516
6517         boost::shared_ptr<RouteList> r = routes.reader ();
6518         framecnt_t max_latency = 0;
6519
6520         if (playback) {
6521                 /* reverse the list so that we work backwards from the last route to run to the first */
6522                 RouteList* rl = routes.reader().get();
6523                 r.reset (new RouteList (*rl));
6524                 reverse (r->begin(), r->end());
6525         }
6526
6527         /* compute actual latency values for the given direction and store them all in per-port
6528            structures. this will also publish the same values (to JACK) so that computation of latency
6529            for routes can consistently use public latency values.
6530         */
6531
6532         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6533                 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6534         }
6535
6536         /* because we latency compensate playback, our published playback latencies should
6537            be the same for all output ports - all material played back by ardour has
6538            the same latency, whether its caused by plugins or by latency compensation. since
6539            these may differ from the values computed above, reset all playback port latencies
6540            to the same value.
6541         */
6542
6543         DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6544
6545         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6546                 (*i)->set_public_port_latencies (max_latency, playback);
6547         }
6548
6549         if (playback) {
6550
6551                 post_playback_latency ();
6552
6553         } else {
6554
6555                 post_capture_latency ();
6556         }
6557
6558         DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6559 }
6560
6561 void
6562 Session::post_playback_latency ()
6563 {
6564         set_worst_playback_latency ();
6565
6566         boost::shared_ptr<RouteList> r = routes.reader ();
6567
6568         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6569                 if (!(*i)->is_auditioner() && ((*i)->active())) {
6570                         _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6571                 }
6572         }
6573
6574         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6575                 (*i)->set_latency_compensation (_worst_track_latency);
6576         }
6577 }
6578
6579 void
6580 Session::post_capture_latency ()
6581 {
6582         set_worst_capture_latency ();
6583
6584         /* reflect any changes in capture latencies into capture offsets
6585          */
6586
6587         boost::shared_ptr<RouteList> rl = routes.reader();
6588         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6589                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6590                 if (tr) {
6591                         tr->set_capture_offset ();
6592                 }
6593         }
6594 }
6595
6596 void
6597 Session::initialize_latencies ()
6598 {
6599         {
6600                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6601                 update_latency (false);
6602                 update_latency (true);
6603         }
6604
6605         set_worst_io_latencies ();
6606 }
6607
6608 void
6609 Session::set_worst_io_latencies ()
6610 {
6611         set_worst_playback_latency ();
6612         set_worst_capture_latency ();
6613 }
6614
6615 void
6616 Session::set_worst_playback_latency ()
6617 {
6618         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6619                 return;
6620         }
6621
6622         _worst_output_latency = 0;
6623
6624         if (!_engine.connected()) {
6625                 return;
6626         }
6627
6628         boost::shared_ptr<RouteList> r = routes.reader ();
6629
6630         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6631                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6632         }
6633
6634         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6635 }
6636
6637 void
6638 Session::set_worst_capture_latency ()
6639 {
6640         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6641                 return;
6642         }
6643
6644         _worst_input_latency = 0;
6645
6646         if (!_engine.connected()) {
6647                 return;
6648         }
6649
6650         boost::shared_ptr<RouteList> r = routes.reader ();
6651
6652         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6653                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6654         }
6655
6656         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6657 }
6658
6659 void
6660 Session::update_latency_compensation (bool force_whole_graph)
6661 {
6662         bool some_track_latency_changed = false;
6663
6664         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6665                 return;
6666         }
6667
6668         DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6669
6670         _worst_track_latency = 0;
6671
6672         boost::shared_ptr<RouteList> r = routes.reader ();
6673
6674         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6675                 if (!(*i)->is_auditioner() && ((*i)->active())) {
6676                         framecnt_t tl;
6677                         if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6678                                 some_track_latency_changed = true;
6679                         }
6680                         _worst_track_latency = max (tl, _worst_track_latency);
6681                 }
6682         }
6683
6684         DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6685                                                      (some_track_latency_changed ? "yes" : "no")));
6686
6687         DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6688
6689         if (some_track_latency_changed || force_whole_graph)  {
6690                 _engine.update_latencies ();
6691         }
6692
6693
6694         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6695                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6696                 if (!tr) {
6697                         continue;
6698                 }
6699                 tr->set_capture_offset ();
6700         }
6701 }
6702
6703 char
6704 Session::session_name_is_legal (const string& path)
6705 {
6706         char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6707
6708         for (int i = 0; illegal_chars[i]; ++i) {
6709                 if (path.find (illegal_chars[i]) != string::npos) {
6710                         return illegal_chars[i];
6711                 }
6712         }
6713
6714         return 0;
6715 }
6716
6717 void
6718 Session::notify_presentation_info_change ()
6719 {
6720         if (deletion_in_progress()) {
6721                 return;
6722         }
6723
6724         PresentationInfo::Change (); /* EMIT SIGNAL */
6725         reassign_track_numbers();
6726
6727 #ifdef USE_TRACKS_CODE_FEATURES
6728         /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6729          * if track order has been changed by user
6730          */
6731         reconnect_existing_routes(true, true);
6732 #endif
6733
6734 }
6735
6736 bool
6737 Session::operation_in_progress (GQuark op) const
6738 {
6739         return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6740 }
6741
6742 boost::shared_ptr<Port>
6743 Session::ltc_input_port () const
6744 {
6745         return _ltc_input->nth (0);
6746 }
6747
6748 boost::shared_ptr<Port>
6749 Session::ltc_output_port () const
6750 {
6751         return _ltc_output->nth (0);
6752 }
6753
6754 void
6755 Session::reconnect_ltc_input ()
6756 {
6757         if (_ltc_input) {
6758
6759                 string src = Config->get_ltc_source_port();
6760
6761                 _ltc_input->disconnect (this);
6762
6763                 if (src != _("None") && !src.empty())  {
6764                         _ltc_input->nth (0)->connect (src);
6765                 }
6766
6767                 if ( ARDOUR::Profile->get_trx () ) {
6768                         // Tracks need this signal to update timecode_source_dropdown
6769                         MtcOrLtcInputPortChanged (); //emit signal
6770                 }
6771         }
6772 }
6773
6774 void
6775 Session::reconnect_ltc_output ()
6776 {
6777         if (_ltc_output) {
6778
6779                 string src = Config->get_ltc_output_port();
6780
6781                 _ltc_output->disconnect (this);
6782
6783                 if (src != _("None") && !src.empty())  {
6784                         _ltc_output->nth (0)->connect (src);
6785                 }
6786         }
6787 }
6788
6789 void
6790 Session::set_range_selection (framepos_t start, framepos_t end)
6791 {
6792         _range_selection = Evoral::Range<framepos_t> (start, end);
6793 #ifdef USE_TRACKS_CODE_FEATURES
6794         follow_playhead_priority ();
6795 #endif
6796 }
6797
6798 void
6799 Session::set_object_selection (framepos_t start, framepos_t end)
6800 {
6801         _object_selection = Evoral::Range<framepos_t> (start, end);
6802 #ifdef USE_TRACKS_CODE_FEATURES
6803         follow_playhead_priority ();
6804 #endif
6805 }
6806
6807 void
6808 Session::clear_range_selection ()
6809 {
6810         _range_selection = Evoral::Range<framepos_t> (-1,-1);
6811 #ifdef USE_TRACKS_CODE_FEATURES
6812         follow_playhead_priority ();
6813 #endif
6814 }
6815
6816 void
6817 Session::clear_object_selection ()
6818 {
6819         _object_selection = Evoral::Range<framepos_t> (-1,-1);
6820 #ifdef USE_TRACKS_CODE_FEATURES
6821         follow_playhead_priority ();
6822 #endif
6823 }
6824
6825 void
6826 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6827                 const ChanCount& input_start,
6828                 const ChanCount& output_start,
6829                 const ChanCount& input_offset,
6830                 const ChanCount& output_offset)
6831 {
6832         Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6833         _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6834                                 input_start, output_start,
6835                                 input_offset, output_offset));
6836
6837         if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6838                 pthread_cond_signal (&_auto_connect_cond);
6839                 pthread_mutex_unlock (&_auto_connect_mutex);
6840         }
6841 }
6842
6843 void
6844 Session::queue_latency_recompute ()
6845 {
6846         g_atomic_int_inc (&_latency_recompute_pending);
6847         if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6848                 pthread_cond_signal (&_auto_connect_cond);
6849                 pthread_mutex_unlock (&_auto_connect_mutex);
6850         }
6851 }
6852
6853 void
6854 Session::auto_connect (const AutoConnectRequest& ar)
6855 {
6856         boost::shared_ptr<Route> route = ar.route.lock();
6857
6858         if (!route) { return; }
6859
6860         if (!IO::connecting_legal) {
6861                 return;
6862         }
6863
6864         /* If both inputs and outputs are auto-connected to physical ports,
6865          * use the max of input and output offsets to ensure auto-connected
6866          * port numbers always match up (e.g. the first audio input and the
6867          * first audio output of the route will have the same physical
6868          * port number).  Otherwise just use the lowest input or output
6869          * offset possible.
6870          */
6871
6872         const bool in_out_physical =
6873                 (Config->get_input_auto_connect() & AutoConnectPhysical)
6874                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6875                 && ar.connect_inputs;
6876
6877         const ChanCount in_offset = in_out_physical
6878                 ? ChanCount::max(ar.input_offset, ar.output_offset)
6879                 : ar.input_offset;
6880
6881         const ChanCount out_offset = in_out_physical
6882                 ? ChanCount::max(ar.input_offset, ar.output_offset)
6883                 : ar.output_offset;
6884
6885         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6886                 vector<string> physinputs;
6887                 vector<string> physoutputs;
6888
6889                 _engine.get_physical_outputs (*t, physoutputs);
6890                 _engine.get_physical_inputs (*t, physinputs);
6891
6892                 if (!physinputs.empty() && ar.connect_inputs) {
6893                         uint32_t nphysical_in = physinputs.size();
6894
6895                         for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6896                                 string port;
6897
6898                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6899                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6900                                 }
6901
6902                                 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6903                                         break;
6904                                 }
6905                         }
6906                 }
6907
6908                 if (!physoutputs.empty()) {
6909                         uint32_t nphysical_out = physoutputs.size();
6910                         for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6911                                 string port;
6912
6913                                 /* Waves Tracks:
6914                                  * do not create new connections if we reached the limit of physical outputs
6915                                  * in Multi Out mode
6916                                  */
6917                                 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6918                                                 ARDOUR::Profile->get_trx () &&
6919                                                 ar.output_offset.get(*t) == nphysical_out ) {
6920                                         break;
6921                                 }
6922
6923                                 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6924                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6925                                 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6926                                         /* master bus is audio only */
6927                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6928                                                 port = _master_out->input()->ports().port(*t,
6929                                                                 i % _master_out->input()->n_ports().get(*t))->name();
6930                                         }
6931                                 }
6932
6933                                 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6934                                         break;
6935                                 }
6936                         }
6937                 }
6938         }
6939 }
6940
6941 void
6942 Session::auto_connect_thread_start ()
6943 {
6944         if (_ac_thread_active) {
6945                 return;
6946         }
6947
6948         while (!_auto_connect_queue.empty ()) {
6949                 _auto_connect_queue.pop ();
6950         }
6951
6952         _ac_thread_active = true;
6953         if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6954                 _ac_thread_active = false;
6955         }
6956 }
6957
6958 void
6959 Session::auto_connect_thread_terminate ()
6960 {
6961         if (!_ac_thread_active) {
6962                 return;
6963         }
6964         _ac_thread_active = false;
6965
6966         {
6967                 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6968                 while (!_auto_connect_queue.empty ()) {
6969                         _auto_connect_queue.pop ();
6970                 }
6971         }
6972
6973         if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6974                 pthread_cond_signal (&_auto_connect_cond);
6975                 pthread_mutex_unlock (&_auto_connect_mutex);
6976         }
6977
6978         void *status;
6979         pthread_join (_auto_connect_thread, &status);
6980 }
6981
6982 void *
6983 Session::auto_connect_thread (void *arg)
6984 {
6985         Session *s = static_cast<Session *>(arg);
6986         s->auto_connect_thread_run ();
6987         pthread_exit (0);
6988         return 0;
6989 }
6990
6991 void
6992 Session::auto_connect_thread_run ()
6993 {
6994         pthread_set_name (X_("autoconnect"));
6995         SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6996         PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6997         pthread_mutex_lock (&_auto_connect_mutex);
6998         while (_ac_thread_active) {
6999
7000                 if (!_auto_connect_queue.empty ()) {
7001                         // Why would we need the process lock ??
7002                         // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7003                         //   graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7004                         //   All ardour-internal backends use a std::vector   xxxAudioBackend::find_port()
7005                         //   We have control over those, but what does jack do?
7006                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7007
7008                         Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7009                         while (!_auto_connect_queue.empty ()) {
7010                                 const AutoConnectRequest ar (_auto_connect_queue.front());
7011                                 _auto_connect_queue.pop ();
7012                                 lx.release ();
7013                                 auto_connect (ar);
7014                                 lx.acquire ();
7015                         }
7016                 }
7017
7018                 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7019                         update_latency_compensation ();
7020                 }
7021
7022                 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7023         }
7024         pthread_mutex_unlock (&_auto_connect_mutex);
7025 }