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