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