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