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