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