Increase mempool for session-scripts
[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 () const
2071 {
2072         framepos_t ret;
2073
2074         frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2075         offset *= transport_speed ();
2076
2077         if (synced_to_engine()) {
2078                 /* Note: this is basically just sync-to-JACK */
2079                 ret = _engine.transport_frame();
2080         } else {
2081                 ret = _transport_frame;
2082         }
2083
2084         if (transport_rolling()) {
2085                 ret -= offset;
2086
2087                 /* Check to see if we have passed the first guaranteed
2088                  * audible frame past our last start position. if not,
2089                  * return that last start point because in terms
2090                  * of audible frames, we have not moved yet.
2091                  *
2092                  * `Start position' in this context means the time we last
2093                  * either started, located, or changed transport direction.
2094                  */
2095
2096                 if (_transport_speed > 0.0f) {
2097
2098                         if (!play_loop || !have_looped) {
2099                                 if (ret < _last_roll_or_reversal_location) {
2100                                         return _last_roll_or_reversal_location;
2101                                 }
2102                         } else {
2103                                 // latent loops
2104                                 Location *location = _locations->auto_loop_location();
2105                                 frameoffset_t lo = location->start() - ret;
2106                                 if (lo > 0) {
2107                                         ret = location->end () - lo;
2108                                 }
2109                         }
2110
2111                 } else if (_transport_speed < 0.0f) {
2112
2113                         /* XXX wot? no backward looping? */
2114
2115                         if (ret > _last_roll_or_reversal_location) {
2116                                 return _last_roll_or_reversal_location;
2117                         }
2118                 }
2119         }
2120
2121         return std::max ((framepos_t)0, ret);
2122 }
2123
2124
2125 framecnt_t
2126 Session::preroll_samples (framepos_t pos) const
2127 {
2128         const float pr = Config->get_preroll_seconds();
2129         if (pos >= 0 && pr < 0) {
2130                 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2131                 const Meter& meter = _tempo_map->meter_at_frame (pos);
2132                 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2133         }
2134         if (pr < 0) {
2135                 return 0;
2136         }
2137         return pr * frame_rate();
2138 }
2139
2140 void
2141 Session::set_frame_rate (framecnt_t frames_per_second)
2142 {
2143         /** \fn void Session::set_frame_size(framecnt_t)
2144                 the AudioEngine object that calls this guarantees
2145                 that it will not be called while we are also in
2146                 ::process(). Its fine to do things that block
2147                 here.
2148         */
2149
2150         if (_base_frame_rate == 0) {
2151                 _base_frame_rate = frames_per_second;
2152         }
2153         else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2154                 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2155         }
2156         _nominal_frame_rate = frames_per_second;
2157
2158         sync_time_vars();
2159
2160         clear_clicks ();
2161         reset_write_sources (false);
2162
2163         // XXX we need some equivalent to this, somehow
2164         // SndFileSource::setup_standard_crossfades (frames_per_second);
2165
2166         set_dirty();
2167
2168         /* XXX need to reset/reinstantiate all LADSPA plugins */
2169 }
2170
2171 void
2172 Session::set_block_size (pframes_t nframes)
2173 {
2174         /* the AudioEngine guarantees
2175            that it will not be called while we are also in
2176            ::process(). It is therefore fine to do things that block
2177            here.
2178         */
2179
2180         {
2181                 current_block_size = nframes;
2182
2183                 ensure_buffers ();
2184
2185                 boost::shared_ptr<RouteList> r = routes.reader ();
2186
2187                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2188                         (*i)->set_block_size (nframes);
2189                 }
2190
2191                 boost::shared_ptr<RouteList> rl = routes.reader ();
2192                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2193                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2194                         if (tr) {
2195                                 tr->set_block_size (nframes);
2196                         }
2197                 }
2198
2199                 set_worst_io_latencies ();
2200         }
2201 }
2202
2203
2204 static void
2205 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2206 {
2207         boost::shared_ptr<Route> r2;
2208
2209         if (r1->feeds (rbase) && rbase->feeds (r1)) {
2210                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2211                 return;
2212         }
2213
2214         /* make a copy of the existing list of routes that feed r1 */
2215
2216         Route::FedBy existing (r1->fed_by());
2217
2218         /* for each route that feeds r1, recurse, marking it as feeding
2219            rbase as well.
2220         */
2221
2222         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2223                 if (!(r2 = i->r.lock ())) {
2224                         /* (*i) went away, ignore it */
2225                         continue;
2226                 }
2227
2228                 /* r2 is a route that feeds r1 which somehow feeds base. mark
2229                    base as being fed by r2
2230                 */
2231
2232                 rbase->add_fed_by (r2, i->sends_only);
2233
2234                 if (r2 != rbase) {
2235
2236                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2237                            stop here.
2238                         */
2239
2240                         if (r1->feeds (r2) && r2->feeds (r1)) {
2241                                 continue;
2242                         }
2243
2244                         /* now recurse, so that we can mark base as being fed by
2245                            all routes that feed r2
2246                         */
2247
2248                         trace_terminal (r2, rbase);
2249                 }
2250
2251         }
2252 }
2253
2254 void
2255 Session::resort_routes ()
2256 {
2257         /* don't do anything here with signals emitted
2258            by Routes during initial setup or while we
2259            are being destroyed.
2260         */
2261
2262         if (_state_of_the_state & (InitialConnecting | Deletion)) {
2263                 return;
2264         }
2265
2266         if (_route_deletion_in_progress) {
2267                 return;
2268         }
2269
2270         {
2271                 RCUWriter<RouteList> writer (routes);
2272                 boost::shared_ptr<RouteList> r = writer.get_copy ();
2273                 resort_routes_using (r);
2274                 /* writer goes out of scope and forces update */
2275         }
2276
2277 #ifndef NDEBUG
2278         if (DEBUG_ENABLED(DEBUG::Graph)) {
2279                 boost::shared_ptr<RouteList> rl = routes.reader ();
2280                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2281                         DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2282
2283                         const Route::FedBy& fb ((*i)->fed_by());
2284
2285                         for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2286                                 boost::shared_ptr<Route> sf = f->r.lock();
2287                                 if (sf) {
2288                                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2289                                 }
2290                         }
2291                 }
2292         }
2293 #endif
2294
2295 }
2296
2297 /** This is called whenever we need to rebuild the graph of how we will process
2298  *  routes.
2299  *  @param r List of routes, in any order.
2300  */
2301
2302 void
2303 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2304 {
2305         /* We are going to build a directed graph of our routes;
2306            this is where the edges of that graph are put.
2307         */
2308
2309         GraphEdges edges;
2310
2311         /* Go through all routes doing two things:
2312          *
2313          * 1. Collect the edges of the route graph.  Each of these edges
2314          *    is a pair of routes, one of which directly feeds the other
2315          *    either by a JACK connection or by an internal send.
2316          *
2317          * 2. Begin the process of making routes aware of which other
2318          *    routes directly or indirectly feed them.  This information
2319          *    is used by the solo code.
2320          */
2321
2322         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2323
2324                 /* Clear out the route's list of direct or indirect feeds */
2325                 (*i)->clear_fed_by ();
2326
2327                 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2328
2329                         bool via_sends_only;
2330
2331                         /* See if this *j feeds *i according to the current state of the JACK
2332                            connections and internal sends.
2333                         */
2334                         if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2335                                 /* add the edge to the graph (part #1) */
2336                                 edges.add (*j, *i, via_sends_only);
2337                                 /* tell the route (for part #2) */
2338                                 (*i)->add_fed_by (*j, via_sends_only);
2339                         }
2340                 }
2341         }
2342
2343         /* Attempt a topological sort of the route graph */
2344         boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2345
2346         if (sorted_routes) {
2347                 /* We got a satisfactory topological sort, so there is no feedback;
2348                    use this new graph.
2349
2350                    Note: the process graph rechain does not require a
2351                    topologically-sorted list, but hey ho.
2352                 */
2353                 if (_process_graph) {
2354                         _process_graph->rechain (sorted_routes, edges);
2355                 }
2356
2357                 _current_route_graph = edges;
2358
2359                 /* Complete the building of the routes' lists of what directly
2360                    or indirectly feeds them.
2361                 */
2362                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2363                         trace_terminal (*i, *i);
2364                 }
2365
2366                 *r = *sorted_routes;
2367
2368 #ifndef NDEBUG
2369                 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2370                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2372                 }
2373 #endif
2374
2375                 SuccessfulGraphSort (); /* EMIT SIGNAL */
2376
2377         } else {
2378                 /* The topological sort failed, so we have a problem.  Tell everyone
2379                    and stick to the old graph; this will continue to be processed, so
2380                    until the feedback is fixed, what is played back will not quite
2381                    reflect what is actually connected.  Note also that we do not
2382                    do trace_terminal here, as it would fail due to an endless recursion,
2383                    so the solo code will think that everything is still connected
2384                    as it was before.
2385                 */
2386
2387                 FeedbackDetected (); /* EMIT SIGNAL */
2388         }
2389
2390 }
2391
2392 /** Find a route name starting with \a base, maybe followed by the
2393  *  lowest \a id.  \a id will always be added if \a definitely_add_number
2394  *  is true on entry; otherwise it will only be added if required
2395  *  to make the name unique.
2396  *
2397  *  Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2398  *  The available route name with the lowest ID will be used, and \a id
2399  *  will be set to the ID.
2400  *
2401  *  \return false if a route name could not be found, and \a track_name
2402  *  and \a id do not reflect a free route name.
2403  */
2404 bool
2405 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2406 {
2407         /* the base may conflict with ports that do not belong to existing
2408            routes, but hidden objects like the click track. So check port names
2409            before anything else.
2410         */
2411
2412         for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2413                 if (base == reserved->first) {
2414                         /* Check if this reserved name already exists, and if
2415                            so, disallow it without a numeric suffix.
2416                         */
2417                         if (!reserved->second || route_by_name (reserved->first)) {
2418                                 definitely_add_number = true;
2419                                 if (id < 1) {
2420                                         id = 1;
2421                                 }
2422                         }
2423                         break;
2424                 }
2425         }
2426
2427         /* if we have "base 1" already, it doesn't make sense to add "base"
2428          * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2429          */
2430         if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2431                 /* just use the base */
2432                 name = base;
2433                 return true;
2434         }
2435
2436         do {
2437                 name = string_compose ("%1 %2", base, id);
2438
2439                 if (route_by_name (name) == 0) {
2440                         return true;
2441                 }
2442
2443                 ++id;
2444
2445         } while (id < (UINT_MAX-1));
2446
2447         return false;
2448 }
2449
2450 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2451 void
2452 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2453 {
2454         in  = ChanCount::ZERO;
2455         out = ChanCount::ZERO;
2456
2457         boost::shared_ptr<RouteList> r = routes.reader ();
2458
2459         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2460                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2461                 if (tr && !tr->is_auditioner()) {
2462                         in  += tr->n_inputs();
2463                         out += tr->n_outputs();
2464                 }
2465         }
2466 }
2467
2468 string
2469 Session::default_track_name_pattern (DataType t)
2470 {
2471         switch (t) {
2472         case DataType::AUDIO:
2473                 if (Profile->get_trx()) {
2474                         return _("Track ");
2475                 } else {
2476                         return _("Audio ");
2477                 }
2478                 break;
2479
2480         case DataType::MIDI:
2481                 return _("MIDI ");
2482         }
2483
2484         return "";
2485 }
2486
2487 /** Caller must not hold process lock
2488  *  @param name_template string to use for the start of the name, or "" to use "MIDI".
2489  *  @param instrument plugin info for the instrument to insert pre-fader, if any
2490  */
2491 list<boost::shared_ptr<MidiTrack> >
2492 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2493                          boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2494                          RouteGroup* route_group, uint32_t how_many,
2495                          string name_template, PresentationInfo::order_t order,
2496                          TrackMode mode)
2497 {
2498         string track_name;
2499         uint32_t track_id = 0;
2500         string port;
2501         RouteList new_routes;
2502         list<boost::shared_ptr<MidiTrack> > ret;
2503
2504         const string name_pattern = default_track_name_pattern (DataType::MIDI);
2505         bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2506
2507         while (how_many) {
2508                 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2509                         error << "cannot find name for new midi track" << endmsg;
2510                         goto failed;
2511                 }
2512
2513                 boost::shared_ptr<MidiTrack> track;
2514
2515                 try {
2516                         track.reset (new MidiTrack (*this, track_name, mode));
2517
2518                         if (track->init ()) {
2519                                 goto failed;
2520                         }
2521
2522                         if (strict_io) {
2523                                 track->set_strict_io (true);
2524                         }
2525
2526                         track->use_new_diskstream();
2527
2528                         BOOST_MARK_TRACK (track);
2529
2530                         {
2531                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2532                                 if (track->input()->ensure_io (input, false, this)) {
2533                                         error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2534                                         goto failed;
2535                                 }
2536
2537                                 if (track->output()->ensure_io (output, false, this)) {
2538                                         error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2539                                         goto failed;
2540                                 }
2541                         }
2542
2543                         track->non_realtime_input_change();
2544
2545                         if (route_group) {
2546                                 route_group->add (track);
2547                         }
2548
2549                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2550
2551                         new_routes.push_back (track);
2552                         ret.push_back (track);
2553                 }
2554
2555                 catch (failed_constructor &err) {
2556                         error << _("Session: could not create new midi track.") << endmsg;
2557                         goto failed;
2558                 }
2559
2560                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2561
2562                         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;
2563                         goto failed;
2564                 }
2565
2566                 --how_many;
2567         }
2568
2569   failed:
2570         if (!new_routes.empty()) {
2571                 StateProtector sp (this);
2572                 if (Profile->get_trx()) {
2573                         add_routes (new_routes, false, false, false, order);
2574                 } else {
2575                         add_routes (new_routes, true, true, false, order);
2576                 }
2577
2578                 if (instrument) {
2579                         for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2580                                 PluginPtr plugin = instrument->load (*this);
2581                                 if (!plugin) {
2582                                         warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2583                                         continue;
2584                                 }
2585                                 if (pset) {
2586                                         plugin->load_preset (*pset);
2587                                 }
2588                                 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2589                                 if (strict_io) {
2590                                         pi->set_strict_io (true);
2591                                 }
2592
2593                                 (*r)->add_processor (pi, PreFader);
2594
2595                                 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2596                                         (*r)->move_instrument_down (false);
2597                                 }
2598                         }
2599                 }
2600         }
2601
2602         return ret;
2603 }
2604
2605 RouteList
2606 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2607                          boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2608                          PresentationInfo::Flag flag, PresentationInfo::order_t order)
2609 {
2610         string bus_name;
2611         uint32_t bus_id = 0;
2612         string port;
2613         RouteList ret;
2614
2615         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2616
2617         while (how_many) {
2618                 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2619                         error << "cannot find name for new midi bus" << endmsg;
2620                         goto failure;
2621                 }
2622
2623                 try {
2624                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2625
2626                         if (bus->init ()) {
2627                                 goto failure;
2628                         }
2629
2630                         if (strict_io) {
2631                                 bus->set_strict_io (true);
2632                         }
2633
2634                         BOOST_MARK_ROUTE(bus);
2635
2636                         {
2637                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2638
2639                                 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2640                                         error << _("cannot configure new midi bus input") << endmsg;
2641                                         goto failure;
2642                                 }
2643
2644
2645                                 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2646                                         error << _("cannot configure new midi bus output") << endmsg;
2647                                         goto failure;
2648                                 }
2649                         }
2650
2651                         if (route_group) {
2652                                 route_group->add (bus);
2653                         }
2654
2655                         bus->add_internal_return ();
2656                         ret.push_back (bus);
2657                 }
2658
2659                 catch (failed_constructor &err) {
2660                         error << _("Session: could not create new audio route.") << endmsg;
2661                         goto failure;
2662                 }
2663
2664                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2665                         error << pfe.what() << endmsg;
2666                         goto failure;
2667                 }
2668
2669
2670                 --how_many;
2671         }
2672
2673   failure:
2674         if (!ret.empty()) {
2675                 StateProtector sp (this);
2676                 add_routes (ret, false, false, false, order);
2677
2678                 if (instrument) {
2679                         for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2680                                 PluginPtr plugin = instrument->load (*this);
2681                                 if (!plugin) {
2682                                         warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2683                                         continue;
2684                                 }
2685                                 if (pset) {
2686                                         plugin->load_preset (*pset);
2687                                 }
2688                                 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2689                                 if (strict_io) {
2690                                         pi->set_strict_io (true);
2691                                 }
2692
2693                                 (*r)->add_processor (pi, PreFader);
2694
2695                                 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2696                                         (*r)->move_instrument_down (false);
2697                                 }
2698                         }
2699                 }
2700         }
2701
2702         return ret;
2703
2704 }
2705
2706
2707 void
2708 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2709 {
2710         boost::shared_ptr<Route> midi_track (wmt.lock());
2711
2712         if (!midi_track) {
2713                 return;
2714         }
2715
2716         if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2717
2718                 if (change.after.n_audio() <= change.before.n_audio()) {
2719                         return;
2720                 }
2721
2722                 /* new audio ports: make sure the audio goes somewhere useful,
2723                  * unless the user has no-auto-connect selected.
2724                  *
2725                  * The existing ChanCounts don't matter for this call as they are only
2726                  * to do with matching input and output indices, and we are only changing
2727                  * outputs here.
2728                  */
2729                 auto_connect_route (midi_track, false, ChanCount(), change.before);
2730         }
2731 }
2732
2733 #ifdef USE_TRACKS_CODE_FEATURES
2734
2735 static bool
2736 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2737 {
2738         return route1->remote_control_id() < route2->remote_control_id();
2739 }
2740
2741 void
2742 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2743 {
2744         // it is not allowed to perform connection
2745         if (!IO::connecting_legal) {
2746                 return;
2747         }
2748
2749         // if we are deleting routes we will call this once at the end
2750         if (_route_deletion_in_progress) {
2751                 return;
2752         }
2753
2754         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2755
2756         if (withLock) {
2757                 lm.acquire ();
2758         }
2759
2760         // We need to disconnect the route's inputs and outputs first
2761         // basing on autoconnect configuration
2762         bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2763         bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2764
2765         ChanCount existing_inputs;
2766         ChanCount existing_outputs;
2767         count_existing_track_channels (existing_inputs, existing_outputs);
2768
2769         //ChanCount inputs = ChanCount::ZERO;
2770         //ChanCount outputs = ChanCount::ZERO;
2771
2772         RouteList existing_routes = *routes.reader ();
2773         existing_routes.sort (compare_routes_by_remote_id);
2774
2775         {
2776                 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2777
2778                 vector<string> physinputs;
2779                 vector<string> physoutputs;
2780
2781                 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2782                 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2783
2784                 uint32_t input_n = 0;
2785                 uint32_t output_n = 0;
2786                 RouteList::iterator rIter = existing_routes.begin();
2787                 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2788                 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2789                 for (; rIter != existing_routes.end(); ++rIter) {
2790                         if (*rIter == _master_out || *rIter == _monitor_out ) {
2791                                 continue;
2792                         }
2793
2794                         if (current_output_auto_connection == AutoConnectPhysical) {
2795                                 (*rIter)->amp()->deactivate();
2796                         } else if (current_output_auto_connection == AutoConnectMaster) {
2797                                 (*rIter)->amp()->activate();
2798                         }
2799
2800                         if (reconnectIputs) {
2801                                 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2802
2803                                 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2804
2805                                         if (current_input_auto_connection & AutoConnectPhysical) {
2806
2807                                                 if ( input_n == physinputs.size() ) {
2808                                                         break;
2809                                                 }
2810
2811                                                 string port = physinputs[input_n];
2812
2813                                                 if (port.empty() ) {
2814                                                         error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2815                                                 }
2816
2817                                                 //GZ: check this; could be heavy
2818                                                 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2819                                                 ++input_n;
2820                                         }
2821                                 }
2822                         }
2823
2824                         if (reconnectOutputs) {
2825
2826                                 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2827                                 if (current_output_auto_connection & AutoConnectPhysical) {
2828
2829                                         //GZ: check this; could be heavy
2830                                         (*rIter)->output()->disconnect (this);
2831                                         size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2832
2833                                         //GZ: check this; could be heavy
2834                                         (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2835
2836                                 } else if (current_output_auto_connection & AutoConnectMaster){
2837
2838                                         if (!reconnect_master) {
2839                                                 continue;
2840                                         }
2841
2842                                         //GZ: check this; could be heavy
2843                                         (*rIter)->output()->disconnect (this);
2844
2845                                         if (_master_out) {
2846                                                 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2847                                                 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2848                                         } else {
2849                                                 error << error << "Master bus is not available" << endmsg;
2850                                                 break;
2851                                         }
2852                                 }
2853
2854                                 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2855                                         if (current_output_auto_connection & AutoConnectPhysical) {
2856
2857                                                 if ( output_n == physoutputs.size() ) {
2858                                                         break;
2859                                                 }
2860
2861                                                 string port = physoutputs[output_n];
2862
2863                                                 if (port.empty() ) {
2864                                                         error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2865                                                 }
2866
2867                                                 //GZ: check this; could be heavy
2868                                                 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2869                                                 ++output_n;
2870
2871                                         } else if (current_output_auto_connection & AutoConnectMaster) {
2872
2873                                                 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2874                                                         break;
2875                                                 }
2876
2877                                                 // connect to master bus
2878                                                 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2879
2880                                                 if (port.empty() ) {
2881                                                         error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2882                                                 }
2883
2884
2885                                                 //GZ: check this; could be heavy
2886                                                 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2887
2888                                         }
2889                                 }
2890                         }
2891                 }
2892
2893                 _master_out->output()->disconnect (this);
2894                 auto_connect_master_bus ();
2895         }
2896
2897         graph_reordered ();
2898
2899         session_routes_reconnected (); /* EMIT SIGNAL */
2900 }
2901
2902 void
2903 Session::reconnect_midi_scene_ports(bool inputs)
2904 {
2905     if (inputs ) {
2906
2907         boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2908         if (scene_in_ptr) {
2909             scene_in_ptr->disconnect_all ();
2910
2911             std::vector<EngineStateController::MidiPortState> midi_port_states;
2912             EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2913
2914             std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2915
2916             for (; state_iter != midi_port_states.end(); ++state_iter) {
2917                 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2918                     scene_in_ptr->connect (state_iter->name);
2919                 }
2920             }
2921         }
2922
2923     } else {
2924
2925         boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2926
2927         if (scene_out_ptr ) {
2928             scene_out_ptr->disconnect_all ();
2929
2930             std::vector<EngineStateController::MidiPortState> midi_port_states;
2931             EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2932
2933             std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2934
2935             for (; state_iter != midi_port_states.end(); ++state_iter) {
2936                 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2937                     scene_out_ptr->connect (state_iter->name);
2938                 }
2939             }
2940         }
2941     }
2942 }
2943
2944 void
2945 Session::reconnect_mtc_ports ()
2946 {
2947         boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2948
2949         if (!mtc_in_ptr) {
2950                 return;
2951         }
2952
2953         mtc_in_ptr->disconnect_all ();
2954
2955         std::vector<EngineStateController::MidiPortState> midi_port_states;
2956         EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2957
2958         std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2959
2960         for (; state_iter != midi_port_states.end(); ++state_iter) {
2961                 if (state_iter->available && state_iter->mtc_in) {
2962                         mtc_in_ptr->connect (state_iter->name);
2963                 }
2964         }
2965
2966         if (!_midi_ports->mtc_input_port ()->connected () &&
2967             config.get_external_sync () &&
2968             (Config->get_sync_source () == MTC) ) {
2969                 config.set_external_sync (false);
2970         }
2971
2972         if ( ARDOUR::Profile->get_trx () ) {
2973                 // Tracks need this signal to update timecode_source_dropdown
2974                 MtcOrLtcInputPortChanged (); //emit signal
2975         }
2976 }
2977
2978 void
2979 Session::reconnect_mmc_ports(bool inputs)
2980 {
2981         if (inputs ) { // get all enabled midi input ports
2982
2983                 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2984                 if (mmc_in_ptr) {
2985                         mmc_in_ptr->disconnect_all ();
2986                         std::vector<std::string> enabled_midi_inputs;
2987                         EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2988
2989                         std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2990
2991                         for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2992                                 mmc_in_ptr->connect (*port_iter);
2993                         }
2994
2995                 }
2996         } else { // get all enabled midi output ports
2997
2998                 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2999                 if (mmc_out_ptr ) {
3000                         mmc_out_ptr->disconnect_all ();
3001                         std::vector<std::string> enabled_midi_outputs;
3002                         EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3003
3004                         std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3005
3006                         for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3007                                 mmc_out_ptr->connect (*port_iter);
3008                         }
3009                 }
3010         }
3011 }
3012
3013 #endif
3014
3015 void
3016 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3017 {
3018         if (first_new_order == PresentationInfo::max_order) {
3019                 /* adding at end, no worries */
3020                 return;
3021         }
3022
3023         /* create a gap in the presentation info to accomodate @param how_many
3024          * new objects.
3025          */
3026         StripableList sl;
3027         get_stripables (sl);
3028
3029         for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3030                 boost::shared_ptr<Stripable> s (*si);
3031
3032                 if (s->is_monitor() || s->is_auditioner()) {
3033                         continue;
3034                 }
3035
3036                 if (s->presentation_info().order () >= first_new_order) {
3037                         s->set_presentation_order (s->presentation_info().order () + how_many);
3038                 }
3039         }
3040 }
3041
3042 /** Caller must not hold process lock
3043  *  @param name_template string to use for the start of the name, or "" to use "Audio".
3044  */
3045 list< boost::shared_ptr<AudioTrack> >
3046 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3047                           uint32_t how_many, string name_template, PresentationInfo::order_t order,
3048                           TrackMode mode)
3049 {
3050         string track_name;
3051         uint32_t track_id = 0;
3052         string port;
3053         RouteList new_routes;
3054         list<boost::shared_ptr<AudioTrack> > ret;
3055
3056         const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3057         bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3058
3059         while (how_many) {
3060
3061                 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3062                         error << "cannot find name for new audio track" << endmsg;
3063                         goto failed;
3064                 }
3065
3066                 boost::shared_ptr<AudioTrack> track;
3067
3068                 try {
3069                         track.reset (new AudioTrack (*this, track_name, mode));
3070
3071                         if (track->init ()) {
3072                                 goto failed;
3073                         }
3074
3075                         if (Profile->get_mixbus ()) {
3076                                 track->set_strict_io (true);
3077                         }
3078
3079                         if (ARDOUR::Profile->get_trx ()) {
3080                                 // TRACKS considers it's not a USE CASE, it's
3081                                 // a piece of behavior of the session model:
3082                                 //
3083                                 // Gain for a newly created route depends on
3084                                 // the current output_auto_connect mode:
3085                                 //
3086                                 //  0 for Stereo Out mode
3087                                 //  0 Multi Out mode
3088                                 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3089                                         track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3090                                 }
3091                         }
3092
3093                         track->use_new_diskstream();
3094
3095                         BOOST_MARK_TRACK (track);
3096
3097                         {
3098                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3099
3100                                 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3101                                         error << string_compose (
3102                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
3103                                                 input_channels, output_channels)
3104                                               << endmsg;
3105                                         goto failed;
3106                                 }
3107
3108                                 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3109                                         error << string_compose (
3110                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
3111                                                 input_channels, output_channels)
3112                                               << endmsg;
3113                                         goto failed;
3114                                 }
3115                         }
3116
3117                         if (route_group) {
3118                                 route_group->add (track);
3119                         }
3120
3121                         track->non_realtime_input_change();
3122
3123                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3124
3125                         new_routes.push_back (track);
3126                         ret.push_back (track);
3127                 }
3128
3129                 catch (failed_constructor &err) {
3130                         error << _("Session: could not create new audio track.") << endmsg;
3131                         goto failed;
3132                 }
3133
3134                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3135
3136                         error << pfe.what() << endmsg;
3137                         goto failed;
3138                 }
3139
3140                 --how_many;
3141         }
3142
3143   failed:
3144         if (!new_routes.empty()) {
3145                 StateProtector sp (this);
3146                 if (Profile->get_trx()) {
3147                         add_routes (new_routes, false, false, false, order);
3148                 } else {
3149                         add_routes (new_routes, true, true, false, order);
3150                 }
3151         }
3152
3153         return ret;
3154 }
3155
3156 /** Caller must not hold process lock.
3157  *  @param name_template string to use for the start of the name, or "" to use "Bus".
3158  */
3159 RouteList
3160 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3161                           PresentationInfo::Flag flags, PresentationInfo::order_t order)
3162 {
3163         string bus_name;
3164         uint32_t bus_id = 0;
3165         string port;
3166         RouteList ret;
3167
3168         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3169
3170         while (how_many) {
3171                 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3172                         error << "cannot find name for new audio bus" << endmsg;
3173                         goto failure;
3174                 }
3175
3176                 try {
3177                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3178
3179                         if (bus->init ()) {
3180                                 goto failure;
3181                         }
3182
3183                         if (Profile->get_mixbus ()) {
3184                                 bus->set_strict_io (true);
3185                         }
3186
3187                         BOOST_MARK_ROUTE(bus);
3188
3189                         {
3190                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3191
3192                                 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3193                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3194                                                                  input_channels, output_channels)
3195                                               << endmsg;
3196                                         goto failure;
3197                                 }
3198
3199
3200                                 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3201                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3202                                                                  input_channels, output_channels)
3203                                               << endmsg;
3204                                         goto failure;
3205                                 }
3206                         }
3207
3208                         if (route_group) {
3209                                 route_group->add (bus);
3210                         }
3211
3212                         bus->add_internal_return ();
3213                         ret.push_back (bus);
3214                 }
3215
3216                 catch (failed_constructor &err) {
3217                         error << _("Session: could not create new audio route.") << endmsg;
3218                         goto failure;
3219                 }
3220
3221                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3222                         error << pfe.what() << endmsg;
3223                         goto failure;
3224                 }
3225
3226
3227                 --how_many;
3228         }
3229
3230   failure:
3231         if (!ret.empty()) {
3232                 StateProtector sp (this);
3233                 if (Profile->get_trx()) {
3234                         add_routes (ret, false, false, false, order);
3235                 } else {
3236                         add_routes (ret, false, true, true, order); // autoconnect // outputs only
3237                 }
3238         }
3239
3240         return ret;
3241
3242 }
3243
3244 RouteList
3245 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3246                                   PlaylistDisposition pd)
3247 {
3248         XMLTree tree;
3249
3250         if (!tree.read (template_path.c_str())) {
3251                 return RouteList();
3252         }
3253
3254         return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3255 }
3256
3257 RouteList
3258 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3259 {
3260         RouteList ret;
3261         uint32_t number = 0;
3262         const uint32_t being_added = how_many;
3263         /* This will prevent the use of any existing XML-provided PBD::ID
3264            values by Stateful.
3265         */
3266         Stateful::ForceIDRegeneration force_ids;
3267         IO::disable_connecting ();
3268
3269         while (how_many) {
3270
3271                 /* We're going to modify the node contents a bit so take a
3272                  * copy. The node may be re-used when duplicating more than once.
3273                  */
3274
3275                 XMLNode node_copy (node);
3276
3277                 try {
3278                         string name;
3279
3280                         if (!name_base.empty()) {
3281
3282                                 /* if we're adding more than one routes, force
3283                                  * all the names of the new routes to be
3284                                  * numbered, via the final parameter.
3285                                  */
3286
3287                                 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3288                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3289                                         /*NOTREACHDE*/
3290                                 }
3291
3292                         } else {
3293
3294                                 string const route_name  = node_copy.property(X_("name"))->value ();
3295
3296                                 /* generate a new name by adding a number to the end of the template name */
3297                                 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3298                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3299                                         abort(); /*NOTREACHED*/
3300                                 }
3301                         }
3302
3303                         /* set this name in the XML description that we are about to use */
3304
3305                         if (pd == CopyPlaylist) {
3306                                 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3307                                 if (ds_node) {
3308                                         const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3309                                         boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3310                                         // Use same name as Route::set_name_in_state so playlist copy
3311                                         // is picked up when creating the Route in XMLRouteFactory below
3312                                         playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3313                                         playlist->reset_shares ();
3314                                 }
3315                         } else if (pd == SharePlaylist) {
3316                                 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3317                                 if (ds_node) {
3318                                         const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3319                                         boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3320                                         playlist->share_with ((node_copy.property (X_("id")))->value());
3321                                 }
3322                         }
3323
3324                         bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3325
3326                         Route::set_name_in_state (node_copy, name, rename_playlist);
3327
3328                         /* trim bitslots from listen sends so that new ones are used */
3329                         XMLNodeList children = node_copy.children ();
3330                         for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3331                                 if ((*i)->name() == X_("Processor")) {
3332                                         /* ForceIDRegeneration does not catch the following */
3333                                         XMLProperty const * role = (*i)->property (X_("role"));
3334                                         XMLProperty const * type = (*i)->property (X_("type"));
3335                                         if (role && role->value() == X_("Aux")) {
3336                                                 /* check if the target bus exists.
3337                                                  * we should not save aux-sends in templates.
3338                                                  */
3339                                                 XMLProperty const * target = (*i)->property (X_("target"));
3340                                                 if (!target) {
3341                                                         (*i)->add_property ("type", "dangling-aux-send");
3342                                                         continue;
3343                                                 }
3344                                                 boost::shared_ptr<Route> r = route_by_id (target->value());
3345                                                 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3346                                                         (*i)->add_property ("type", "dangling-aux-send");
3347                                                         continue;
3348                                                 }
3349                                         }
3350                                         if (role && role->value() == X_("Listen")) {
3351                                                 (*i)->remove_property (X_("bitslot"));
3352                                         }
3353                                         else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3354                                                 char buf[32];
3355                                                 Delivery::Role xrole;
3356                                                 uint32_t bitslot = 0;
3357                                                 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3358                                                 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3359                                                 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3360                                                 (*i)->remove_property (X_("bitslot"));
3361                                                 (*i)->remove_property (X_("name"));
3362                                                 (*i)->add_property ("bitslot", buf);
3363                                                 (*i)->add_property ("name", name);
3364                                         }
3365                                         else if (type && type->value() == X_("intreturn")) {
3366                                                 (*i)->remove_property (X_("bitslot"));
3367                                                 (*i)->add_property ("ignore-bitslot", "1");
3368                                         }
3369                                         else if (type && type->value() == X_("return")) {
3370                                                 // Return::set_state() generates a new one
3371                                                 (*i)->remove_property (X_("bitslot"));
3372                                         }
3373                                         else if (type && type->value() == X_("port")) {
3374                                                 // PortInsert::set_state() handles the bitslot
3375                                                 (*i)->remove_property (X_("bitslot"));
3376                                                 (*i)->add_property ("ignore-name", "1");
3377                                         }
3378                                 }
3379                         }
3380
3381                         boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3382
3383                         if (route == 0) {
3384                                 error << _("Session: cannot create track/bus from template description") << endmsg;
3385                                 goto out;
3386                         }
3387
3388                         if (boost::dynamic_pointer_cast<Track>(route)) {
3389                                 /* force input/output change signals so that the new diskstream
3390                                    picks up the configuration of the route. During session
3391                                    loading this normally happens in a different way.
3392                                 */
3393
3394                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3395
3396                                 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3397                                 change.after = route->input()->n_ports();
3398                                 route->input()->changed (change, this);
3399                                 change.after = route->output()->n_ports();
3400                                 route->output()->changed (change, this);
3401                         }
3402
3403                         ret.push_back (route);
3404                 }
3405
3406                 catch (failed_constructor &err) {
3407                         error << _("Session: could not create new route from template") << endmsg;
3408                         goto out;
3409                 }
3410
3411                 catch (AudioEngine::PortRegistrationFailure& pfe) {
3412                         error << pfe.what() << endmsg;
3413                         goto out;
3414                 }
3415
3416                 --how_many;
3417         }
3418
3419   out:
3420         if (!ret.empty()) {
3421                 StateProtector sp (this);
3422                 if (Profile->get_trx()) {
3423                         add_routes (ret, false, false, false, insert_at);
3424                 } else {
3425                         add_routes (ret, true, true, false, insert_at);
3426                 }
3427                 IO::enable_connecting ();
3428         }
3429
3430         return ret;
3431 }
3432
3433 void
3434 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3435 {
3436         try {
3437                 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3438                 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3439
3440         } catch (...) {
3441                 error << _("Adding new tracks/busses failed") << endmsg;
3442         }
3443
3444         graph_reordered ();
3445
3446         update_latency (true);
3447         update_latency (false);
3448
3449         set_dirty();
3450
3451         if (save) {
3452                 save_state (_current_snapshot_name);
3453         }
3454
3455         update_route_record_state ();
3456
3457         RouteAdded (new_routes); /* EMIT SIGNAL */
3458 }
3459
3460 void
3461 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3462 {
3463         ChanCount existing_inputs;
3464         ChanCount existing_outputs;
3465         uint32_t n_routes;
3466         uint32_t added = 0;
3467
3468         count_existing_track_channels (existing_inputs, existing_outputs);
3469
3470         {
3471                 RCUWriter<RouteList> writer (routes);
3472                 boost::shared_ptr<RouteList> r = writer.get_copy ();
3473                 r->insert (r->end(), new_routes.begin(), new_routes.end());
3474                 n_routes = r->size();
3475
3476                 /* if there is no control out and we're not in the middle of loading,
3477                  * resort the graph here. if there is a control out, we will resort
3478                  * toward the end of this method. if we are in the middle of loading,
3479                  * we will resort when done.
3480                  */
3481
3482                 if (!_monitor_out && IO::connecting_legal) {
3483                         resort_routes_using (r);
3484                 }
3485         }
3486
3487         /* auditioner and monitor routes are not part of the order */
3488         if (auditioner) {
3489                 assert (n_routes > 0);
3490                 --n_routes;
3491         }
3492         if (_monitor_out) {
3493                 assert (n_routes > 0);
3494                 --n_routes;
3495         }
3496
3497         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3498         ensure_route_presentation_info_gap (order, new_routes.size());
3499
3500         {
3501                 PresentationInfo::ChangeSuspender cs;
3502
3503                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3504
3505                         boost::weak_ptr<Route> wpr (*x);
3506                         boost::shared_ptr<Route> r (*x);
3507
3508                         r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3509                         r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3510                         r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3511
3512                         r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3513                         r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3514                         r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3515
3516                         if (r->is_master()) {
3517                                 _master_out = r;
3518                         }
3519
3520                         if (r->is_monitor()) {
3521                                 _monitor_out = r;
3522                         }
3523
3524                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3525                         if (tr) {
3526                                 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3527                                 track_playlist_changed (boost::weak_ptr<Track> (tr));
3528                                 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3529
3530                                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3531                                 if (mt) {
3532                                         mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3533                                         mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3534                                         mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3535                                 }
3536                         }
3537
3538                         if (!r->presentation_info().special()) {
3539
3540                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3541
3542                                 /* presentation info order may already have been set from XML */
3543
3544                                 if (!r->presentation_info().order_set()) {
3545                                         /* this is only useful for headless sessions,
3546                                          * Editor::add_routes() and Mixer_UI::add_routes() will
3547                                          * override it following the RouteAdded signal.
3548                                          *
3549                                          * Also routes should be sorted before VCAs (like the GUI does).
3550                                          * Session::ensure_route_presentation_info_gap() does not special case VCAs either.
3551                                          *
3552                                          * ... but not to worry, the GUI's
3553                                          * gtk2_ardour/route_sorter.h and various ::sync_presentation_info_from_treeview()
3554                                          * handle this :)
3555                                          */
3556
3557                                         if (order == PresentationInfo::max_order) {
3558                                                 /* just add to the end */
3559                                                 r->set_presentation_order (n_routes + added);
3560                                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3561                                         } else {
3562                                                 r->set_presentation_order (order + added);
3563                                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3564                                         }
3565                                 } else {
3566                                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3567                                 }
3568                         }
3569
3570 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3571                         /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3572                          * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3573                          */
3574                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3575                                                                        r->name(),
3576                                                                        r->presentation_info().order(),
3577                                                                        enum_2_string (r->presentation_info().flags()),
3578                                                                        r->presentation_info()));
3579 #endif
3580
3581
3582                         if (input_auto_connect || output_auto_connect) {
3583                                 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3584                                 existing_inputs += r->n_inputs();
3585                                 existing_outputs += r->n_outputs();
3586                         }
3587
3588                         ARDOUR::GUIIdle ();
3589                 }
3590         }
3591
3592         if (_monitor_out && IO::connecting_legal) {
3593                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3594
3595                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3596                         if ((*x)->is_monitor()) {
3597                                 /* relax */
3598                         } else if ((*x)->is_master()) {
3599                                 /* relax */
3600                         } else {
3601                                 (*x)->enable_monitor_send ();
3602                         }
3603                 }
3604         }
3605
3606         reassign_track_numbers ();
3607 }
3608
3609 void
3610 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3611 {
3612         boost::shared_ptr<RouteList> r = routes.reader ();
3613         boost::shared_ptr<Send> s;
3614
3615         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3616                 if ((s = (*i)->internal_send_for (dest)) != 0) {
3617                         s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3618                 }
3619         }
3620 }
3621
3622 void
3623 Session::globally_set_send_gains_to_unity (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_UNITY, Controllable::NoGroup);
3631                 }
3632         }
3633 }
3634
3635 void
3636 Session::globally_set_send_gains_from_track(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 ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3644                 }
3645         }
3646 }
3647
3648 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3649 void
3650 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3651 {
3652         boost::shared_ptr<RouteList> r = routes.reader ();
3653         boost::shared_ptr<RouteList> t (new RouteList);
3654
3655         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3656                 /* no MIDI sends because there are no MIDI busses yet */
3657                 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3658                         t->push_back (*i);
3659                 }
3660         }
3661
3662         add_internal_sends (dest, p, t);
3663 }
3664
3665 void
3666 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3667 {
3668         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3669                 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3670         }
3671 }
3672
3673 void
3674 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3675 {
3676         add_internal_send (dest, sender->before_processor_for_index (index), sender);
3677 }
3678
3679 void
3680 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3681 {
3682         if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3683                 return;
3684         }
3685
3686         if (!dest->internal_return()) {
3687                 dest->add_internal_return ();
3688         }
3689
3690         sender->add_aux_send (dest, before);
3691
3692         graph_reordered ();
3693 }
3694
3695 void
3696 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3697 {
3698         { // RCU Writer scope
3699                 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3700                 RCUWriter<RouteList> writer (routes);
3701                 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3702
3703
3704                 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3705
3706                         if (*iter == _master_out) {
3707                                 continue;
3708                         }
3709
3710                         /* speed up session deletion, don't do the solo dance */
3711                         if (0 == (_state_of_the_state & Deletion)) {
3712                                 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3713                         }
3714
3715                         rs->remove (*iter);
3716
3717                         /* deleting the master out seems like a dumb
3718                            idea, but its more of a UI policy issue
3719                            than our concern.
3720                         */
3721
3722                         if (*iter == _master_out) {
3723                                 _master_out = boost::shared_ptr<Route> ();
3724                         }
3725
3726                         if (*iter == _monitor_out) {
3727                                 _monitor_out.reset ();
3728                         }
3729
3730                         // We need to disconnect the route's inputs and outputs
3731
3732                         (*iter)->input()->disconnect (0);
3733                         (*iter)->output()->disconnect (0);
3734
3735                         /* if the route had internal sends sending to it, remove them */
3736                         if ((*iter)->internal_return()) {
3737
3738                                 boost::shared_ptr<RouteList> r = routes.reader ();
3739                                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3740                                         boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3741                                         if (s) {
3742                                                 (*i)->remove_processor (s);
3743                                         }
3744                                 }
3745                         }
3746
3747                         /* if the monitoring section had a pointer to this route, remove it */
3748                         if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3749                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3750                                 ProcessorChangeBlocker pcb (this, false);
3751                                 (*iter)->remove_aux_or_listen (_monitor_out);
3752                         }
3753
3754                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3755                         if (mt && mt->step_editing()) {
3756                                 if (_step_editors > 0) {
3757                                         _step_editors--;
3758                                 }
3759                         }
3760                 }
3761
3762                 /* writer goes out of scope, forces route list update */
3763
3764         } // end of RCU Writer scope
3765
3766         update_route_solo_state ();
3767         update_latency_compensation ();
3768         set_dirty();
3769
3770         /* Re-sort routes to remove the graph's current references to the one that is
3771          * going away, then flush old references out of the graph.
3772          * Wave Tracks: reconnect routes
3773          */
3774
3775 #ifdef USE_TRACKS_CODE_FEATURES
3776                 reconnect_existing_routes(true, false);
3777 #else
3778                 routes.flush (); // maybe unsafe, see below.
3779                 resort_routes ();
3780 #endif
3781
3782         if (_process_graph && !(_state_of_the_state & Deletion)) {
3783                 _process_graph->clear_other_chain ();
3784         }
3785
3786         /* get rid of it from the dead wood collection in the route list manager */
3787         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3788
3789         routes.flush ();
3790
3791         /* try to cause everyone to drop their references
3792          * and unregister ports from the backend
3793          */
3794
3795         for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3796                 cerr << "Drop references to " << (*iter)->name() << endl;
3797                 (*iter)->drop_references ();
3798         }
3799
3800         if (_state_of_the_state & Deletion) {
3801                 return;
3802         }
3803
3804         PropertyChange so;
3805         so.add (Properties::selected);
3806         so.add (Properties::order);
3807         PresentationInfo::Change (PropertyChange (so));
3808
3809         /* save the new state of the world */
3810
3811         if (save_state (_current_snapshot_name)) {
3812                 save_history (_current_snapshot_name);
3813         }
3814
3815         update_route_record_state ();
3816 }
3817
3818 void
3819 Session::remove_route (boost::shared_ptr<Route> route)
3820 {
3821         boost::shared_ptr<RouteList> rl (new RouteList);
3822         rl->push_back (route);
3823         remove_routes (rl);
3824 }
3825
3826 void
3827 Session::route_mute_changed ()
3828 {
3829         set_dirty ();
3830 }
3831
3832 void
3833 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3834 {
3835         boost::shared_ptr<Route> route (wpr.lock());
3836
3837         if (!route) {
3838                 return;
3839         }
3840
3841         assert (Config->get_solo_control_is_listen_control());
3842
3843         if (route->solo_control()->soloed_by_self_or_masters()) {
3844
3845                 if (Config->get_exclusive_solo()) {
3846
3847                         RouteGroup* rg = route->route_group ();
3848                         const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3849
3850                         boost::shared_ptr<RouteList> r = routes.reader ();
3851
3852                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3853                                 if ((*i) == route) {
3854                                         /* already changed */
3855                                         continue;
3856                                 }
3857
3858                                 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3859                                         /* route does not get solo propagated to it */
3860                                         continue;
3861                                 }
3862
3863                                 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3864                                         /* this route is a part of the same solo group as the route
3865                                          * that was changed. Changing that route did change or will
3866                                          * change all group members appropriately, so we can ignore it
3867                                          * here
3868                                          */
3869                                         continue;
3870                                 }
3871                                 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3872                         }
3873                 }
3874
3875                 _listen_cnt++;
3876
3877         } else if (_listen_cnt > 0) {
3878
3879                 _listen_cnt--;
3880         }
3881 }
3882
3883 void
3884 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3885 {
3886         boost::shared_ptr<Route> route (wpr.lock());
3887
3888         if (!route) {
3889                 return;
3890         }
3891
3892         bool send_changed = false;
3893
3894         if (route->solo_isolate_control()->solo_isolated()) {
3895                 if (_solo_isolated_cnt == 0) {
3896                         send_changed = true;
3897                 }
3898                 _solo_isolated_cnt++;
3899         } else if (_solo_isolated_cnt > 0) {
3900                 _solo_isolated_cnt--;
3901                 if (_solo_isolated_cnt == 0) {
3902                         send_changed = true;
3903                 }
3904         }
3905
3906         if (send_changed) {
3907                 IsolatedChanged (); /* EMIT SIGNAL */
3908         }
3909 }
3910
3911 void
3912 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override,  boost::weak_ptr<Route> wpr)
3913 {
3914         DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3915
3916         boost::shared_ptr<Route> route (wpr.lock());
3917
3918         if (!route) {
3919                 return;
3920         }
3921
3922         if (Config->get_solo_control_is_listen_control()) {
3923                 route_listen_changed (group_override, wpr);
3924                 return;
3925         }
3926
3927         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()));
3928
3929         if (route->solo_control()->transitioned_into_solo() == 0) {
3930                 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3931                    to Session.
3932                 */
3933                 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()));
3934                 return;
3935         }
3936
3937         boost::shared_ptr<RouteList> r = routes.reader ();
3938         int32_t delta = route->solo_control()->transitioned_into_solo ();
3939
3940         /* the route may be a member of a group that has shared-solo
3941          * semantics. If so, then all members of that group should follow the
3942          * solo of the changed route. But ... this is optional, controlled by a
3943          * Controllable::GroupControlDisposition.
3944          *
3945          * The first argument to the signal that this method is connected to is the
3946          * GroupControlDisposition value that was used to change solo.
3947          *
3948          * If the solo change was done with group semantics (either InverseGroup
3949          * (force the entire group to change even if the group shared solo is
3950          * disabled) or UseGroup (use the group, which may or may not have the
3951          * shared solo property enabled)) then as we propagate the change to
3952          * the entire session we should IGNORE THE GROUP that the changed route
3953          * belongs to.
3954          */
3955
3956         RouteGroup* rg = route->route_group ();
3957         const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3958
3959         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
3960
3961         if (delta == 1 && Config->get_exclusive_solo()) {
3962
3963                 /* new solo: disable all other solos, but not the group if its solo-enabled */
3964
3965                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3966
3967                         if ((*i) == route) {
3968                                 /* already changed */
3969                                 continue;
3970                         }
3971
3972                         if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3973                                 /* route does not get solo propagated to it */
3974                                 continue;
3975                         }
3976
3977                         if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3978                                 /* this route is a part of the same solo group as the route
3979                                  * that was changed. Changing that route did change or will
3980                                  * change all group members appropriately, so we can ignore it
3981                                  * here
3982                                  */
3983                                 continue;
3984                         }
3985
3986                         (*i)->solo_control()->set_value (0.0, group_override);
3987                 }
3988         }
3989
3990         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3991
3992         RouteList uninvolved;
3993
3994         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3995
3996         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3997                 bool via_sends_only;
3998                 bool in_signal_flow;
3999
4000                 if ((*i) == route) {
4001                         /* already changed */
4002                         continue;
4003                 }
4004
4005                 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4006                         /* route does not get solo propagated to it */
4007                         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(),
4008                                                                   (*i)->can_solo()));
4009                         continue;
4010                 }
4011
4012                 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4013                         /* this route is a part of the same solo group as the route
4014                          * that was changed. Changing that route did change or will
4015                          * change all group members appropriately, so we can ignore it
4016                          * here
4017                          */
4018                         continue;
4019                 }
4020
4021                 in_signal_flow = false;
4022
4023                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4024
4025                 if ((*i)->feeds (route, &via_sends_only)) {
4026                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4027                         if (!via_sends_only) {
4028                                 if (!route->soloed_by_others_upstream()) {
4029                                         (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4030                                 } else {
4031                                         DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4032                                 }
4033                         } else {
4034                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4035                         }
4036                         in_signal_flow = true;
4037                 } else {
4038                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4039                 }
4040
4041                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4042
4043                 if (route->feeds (*i, &via_sends_only)) {
4044                         /* propagate solo upstream only if routing other than
4045                            sends is involved, but do consider the other route
4046                            (*i) to be part of the signal flow even if only
4047                            sends are involved.
4048                         */
4049                         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4050                                                                   route->name(),
4051                                                                   (*i)->name(),
4052                                                                   via_sends_only,
4053                                                                   route->soloed_by_others_downstream(),
4054                                                                   route->soloed_by_others_upstream()));
4055                         if (!via_sends_only) {
4056                                 //NB. Triggers Invert Push, which handles soloed by downstream
4057                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4058                                 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4059                         } else {
4060                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4061                         }
4062                         in_signal_flow = true;
4063                 } else {
4064                         DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4065                 }
4066
4067                 if (!in_signal_flow) {
4068                         uninvolved.push_back (*i);
4069                 }
4070         }
4071
4072         DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4073
4074         /* now notify that the mute state of the routes not involved in the signal
4075            pathway of the just-solo-changed route may have altered.
4076         */
4077
4078         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4079                 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4080                 (*i)->act_on_mute ();
4081                 /* Session will emit SoloChanged() after all solo changes are
4082                  * complete, which should be used by UIs to update mute status
4083                  */
4084         }
4085 }
4086
4087 void
4088 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4089 {
4090         /* now figure out if anything that matters is soloed (or is "listening")*/
4091
4092         bool something_soloed = false;
4093         bool something_listening = false;
4094         uint32_t listeners = 0;
4095         uint32_t isolated = 0;
4096
4097         if (!r) {
4098                 r = routes.reader();
4099         }
4100
4101         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4102                 if ((*i)->can_solo()) {
4103                         if (Config->get_solo_control_is_listen_control()) {
4104                                 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4105                                         listeners++;
4106                                         something_listening = true;
4107                                 }
4108                         } else {
4109                                 (*i)->set_listen (false);
4110                                 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4111                                         something_soloed = true;
4112                                 }
4113                         }
4114                 }
4115
4116                 if ((*i)->solo_isolate_control()->solo_isolated()) {
4117                         isolated++;
4118                 }
4119         }
4120
4121         if (something_soloed != _non_soloed_outs_muted) {
4122                 _non_soloed_outs_muted = something_soloed;
4123                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4124         }
4125
4126         if (something_listening != _listening) {
4127                 _listening = something_listening;
4128                 SoloActive (_listening);
4129         }
4130
4131         _listen_cnt = listeners;
4132
4133         if (isolated != _solo_isolated_cnt) {
4134                 _solo_isolated_cnt = isolated;
4135                 IsolatedChanged (); /* EMIT SIGNAL */
4136         }
4137
4138         DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4139                                                   something_soloed, listeners, isolated));
4140
4141
4142         SoloChanged (); /* EMIT SIGNAL */
4143         set_dirty();
4144 }
4145
4146 void
4147 Session::get_stripables (StripableList& sl) const
4148 {
4149         boost::shared_ptr<RouteList> r = routes.reader ();
4150         sl.insert (sl.end(), r->begin(), r->end());
4151
4152         VCAList v = _vca_manager->vcas ();
4153         sl.insert (sl.end(), v.begin(), v.end());
4154 }
4155
4156 boost::shared_ptr<RouteList>
4157 Session::get_routes_with_internal_returns() const
4158 {
4159         boost::shared_ptr<RouteList> r = routes.reader ();
4160         boost::shared_ptr<RouteList> rl (new RouteList);
4161
4162         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4163                 if ((*i)->internal_return ()) {
4164                         rl->push_back (*i);
4165                 }
4166         }
4167         return rl;
4168 }
4169
4170 bool
4171 Session::io_name_is_legal (const std::string& name) const
4172 {
4173         boost::shared_ptr<RouteList> r = routes.reader ();
4174
4175         for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4176                 if (name == reserved->first) {
4177                         if (!route_by_name (reserved->first)) {
4178                                 /* first instance of a reserved name is allowed */
4179                                 return true;
4180                         }
4181                         /* all other instances of a reserved name are not allowed */
4182                         return false;
4183                 }
4184         }
4185
4186         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4187                 if ((*i)->name() == name) {
4188                         return false;
4189                 }
4190
4191                 if ((*i)->has_io_processor_named (name)) {
4192                         return false;
4193                 }
4194         }
4195
4196         return true;
4197 }
4198
4199 void
4200 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4201 {
4202         RouteList rl2;
4203         vector<string> connections;
4204
4205         /* if we are passed only a single route and we're not told to turn
4206          * others off, then just do the simple thing.
4207          */
4208
4209         if (flip_others == false && rl->size() == 1) {
4210                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4211                 if (mt) {
4212                         mt->set_input_active (onoff);
4213                         return;
4214                 }
4215         }
4216
4217         for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4218
4219                 PortSet& ps ((*rt)->input()->ports());
4220
4221                 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4222                         p->get_connections (connections);
4223                 }
4224
4225                 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4226                         routes_using_input_from (*s, rl2);
4227                 }
4228
4229                 /* scan all relevant routes to see if others are on or off */
4230
4231                 bool others_are_already_on = false;
4232
4233                 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4234
4235                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4236
4237                         if (!mt) {
4238                                 continue;
4239                         }
4240
4241                         if ((*r) != (*rt)) {
4242                                 if (mt->input_active()) {
4243                                         others_are_already_on = true;
4244                                 }
4245                         } else {
4246                                 /* this one needs changing */
4247                                 mt->set_input_active (onoff);
4248                         }
4249                 }
4250
4251                 if (flip_others) {
4252
4253                         /* globally reverse other routes */
4254
4255                         for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4256                                 if ((*r) != (*rt)) {
4257                                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4258                                         if (mt) {
4259                                                 mt->set_input_active (!others_are_already_on);
4260                                         }
4261                                 }
4262                         }
4263                 }
4264         }
4265 }
4266
4267 void
4268 Session::routes_using_input_from (const string& str, RouteList& rl)
4269 {
4270         boost::shared_ptr<RouteList> r = routes.reader();
4271
4272         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4273                 if ((*i)->input()->connected_to (str)) {
4274                         rl.push_back (*i);
4275                 }
4276         }
4277 }
4278
4279 boost::shared_ptr<Route>
4280 Session::route_by_name (string name) const
4281 {
4282         boost::shared_ptr<RouteList> r = routes.reader ();
4283
4284         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4285                 if ((*i)->name() == name) {
4286                         return *i;
4287                 }
4288         }
4289
4290         return boost::shared_ptr<Route> ((Route*) 0);
4291 }
4292
4293 boost::shared_ptr<Route>
4294 Session::route_by_id (PBD::ID id) const
4295 {
4296         boost::shared_ptr<RouteList> r = routes.reader ();
4297
4298         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4299                 if ((*i)->id() == id) {
4300                         return *i;
4301                 }
4302         }
4303
4304         return boost::shared_ptr<Route> ((Route*) 0);
4305 }
4306
4307 boost::shared_ptr<Processor>
4308 Session::processor_by_id (PBD::ID id) const
4309 {
4310         boost::shared_ptr<RouteList> r = routes.reader ();
4311
4312         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4313                 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4314                 if (p) {
4315                         return p;
4316                 }
4317         }
4318
4319         return boost::shared_ptr<Processor> ();
4320 }
4321
4322 boost::shared_ptr<Track>
4323 Session::track_by_diskstream_id (PBD::ID id) const
4324 {
4325         boost::shared_ptr<RouteList> r = routes.reader ();
4326
4327         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4328                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4329                 if (t && t->using_diskstream_id (id)) {
4330                         return t;
4331                 }
4332         }
4333
4334         return boost::shared_ptr<Track> ();
4335 }
4336
4337 boost::shared_ptr<Route>
4338 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4339 {
4340         return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4341 }
4342
4343 boost::shared_ptr<Stripable>
4344 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4345 {
4346         StripableList sl;
4347         PresentationInfo::order_t match_cnt = 0;
4348
4349         get_stripables (sl);
4350         sl.sort (Stripable::PresentationOrderSorter());
4351
4352         for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4353
4354                 if ((*s)->presentation_info().hidden()) {
4355                         /* if the caller didn't explicitly ask for hidden
4356                            stripables, ignore hidden ones. This matches
4357                            the semantics of the pre-PresentationOrder
4358                            "get by RID" logic of Ardour 4.x and earlier.
4359
4360                            XXX at some point we should likely reverse
4361                            the logic of the flags, because asking for "the
4362                            hidden stripables" is not going to be common,
4363                            whereas asking for visible ones is normal.
4364                         */
4365
4366                         if (! (flags & PresentationInfo::Hidden)) {
4367                                 continue;
4368                         }
4369                 }
4370
4371                 if ((*s)->presentation_info().flag_match (flags)) {
4372                         if (match_cnt++ == n) {
4373                                 return *s;
4374                         }
4375                 }
4376         }
4377
4378         /* there is no nth stripable that matches the given flags */
4379         return boost::shared_ptr<Stripable>();
4380 }
4381
4382 struct PresentationOrderSorter {
4383         bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4384                 if (a->presentation_info().special() && !b->presentation_info().special()) {
4385                         /* a is not ordered, b is; b comes before a */
4386                         return false;
4387                 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4388                         /* b is not ordered, a is; a comes before b */
4389                         return true;
4390                 } else {
4391                         return a->presentation_info().order() < b->presentation_info().order();
4392                 }
4393         }
4394 };
4395
4396 boost::shared_ptr<Route>
4397 Session::route_by_selected_count (uint32_t id) const
4398 {
4399         RouteList r (*(routes.reader ()));
4400         PresentationOrderSorter sorter;
4401         r.sort (sorter);
4402
4403         RouteList::iterator i;
4404
4405         for (i = r.begin(); i != r.end(); ++i) {
4406                 if ((*i)->presentation_info().selected()) {
4407                         if (id == 0) {
4408                                 return *i;
4409                         }
4410                         --id;
4411                 }
4412         }
4413
4414         return boost::shared_ptr<Route> ();
4415 }
4416
4417 void
4418 Session::reassign_track_numbers ()
4419 {
4420         int64_t tn = 0;
4421         int64_t bn = 0;
4422         RouteList r (*(routes.reader ()));
4423         PresentationOrderSorter sorter;
4424         r.sort (sorter);
4425
4426         StateProtector sp (this);
4427
4428         for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4429                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4430                         (*i)->set_track_number(++tn);
4431                 }
4432                 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4433                         (*i)->set_track_number(--bn);
4434                 }
4435         }
4436         const uint32_t decimals = ceilf (log10f (tn + 1));
4437         const bool decimals_changed = _track_number_decimals != decimals;
4438         _track_number_decimals = decimals;
4439
4440         if (decimals_changed && config.get_track_name_number ()) {
4441                 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4442                         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4443                         if (t) {
4444                                 t->resync_track_name();
4445                         }
4446                 }
4447                 // trigger GUI re-layout
4448                 config.ParameterChanged("track-name-number");
4449         }
4450
4451 #ifndef NDEBUG
4452         if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4453                 boost::shared_ptr<RouteList> rl = routes.reader ();
4454                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4455                         DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4456                 }
4457         }
4458 #endif /* NDEBUG */
4459
4460 }
4461
4462 void
4463 Session::playlist_region_added (boost::weak_ptr<Region> w)
4464 {
4465         boost::shared_ptr<Region> r = w.lock ();
4466         if (!r) {
4467                 return;
4468         }
4469
4470         /* These are the operations that are currently in progress... */
4471         list<GQuark> curr = _current_trans_quarks;
4472         curr.sort ();
4473
4474         /* ...and these are the operations during which we want to update
4475            the session range location markers.
4476         */
4477         list<GQuark> ops;
4478         ops.push_back (Operations::capture);
4479         ops.push_back (Operations::paste);
4480         ops.push_back (Operations::duplicate_region);
4481         ops.push_back (Operations::insert_file);
4482         ops.push_back (Operations::insert_region);
4483         ops.push_back (Operations::drag_region_brush);
4484         ops.push_back (Operations::region_drag);
4485         ops.push_back (Operations::selection_grab);
4486         ops.push_back (Operations::region_fill);
4487         ops.push_back (Operations::fill_selection);
4488         ops.push_back (Operations::create_region);
4489         ops.push_back (Operations::region_copy);
4490         ops.push_back (Operations::fixed_time_region_copy);
4491         ops.sort ();
4492
4493         /* See if any of the current operations match the ones that we want */
4494         list<GQuark> in;
4495         set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4496
4497         /* If so, update the session range markers */
4498         if (!in.empty ()) {
4499                 maybe_update_session_range (r->position (), r->last_frame ());
4500         }
4501 }
4502
4503 /** Update the session range markers if a is before the current start or
4504  *  b is after the current end.
4505  */
4506 void
4507 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4508 {
4509         if (_state_of_the_state & Loading) {
4510                 return;
4511         }
4512
4513         framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4514
4515         if (_session_range_location == 0) {
4516
4517                 set_session_range_location (a, b + session_end_marker_shift_samples);
4518
4519         } else {
4520
4521                 if (a < _session_range_location->start()) {
4522                         _session_range_location->set_start (a);
4523                 }
4524
4525                 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4526                         _session_range_location->set_end (b);
4527                 }
4528         }
4529 }
4530
4531 void
4532 Session::set_end_is_free (bool yn)
4533 {
4534         _session_range_end_is_free = yn;
4535 }
4536
4537 void
4538 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4539 {
4540         for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4541                 maybe_update_session_range (i->to, i->to + i->length);
4542         }
4543 }
4544
4545 void
4546 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4547 {
4548         for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4549                 maybe_update_session_range (i->from, i->to);
4550         }
4551 }
4552
4553 /* Region management */
4554
4555 boost::shared_ptr<Region>
4556 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4557 {
4558         const RegionFactory::RegionMap& regions (RegionFactory::regions());
4559         RegionFactory::RegionMap::const_iterator i;
4560         boost::shared_ptr<Region> region;
4561
4562         Glib::Threads::Mutex::Lock lm (region_lock);
4563
4564         for (i = regions.begin(); i != regions.end(); ++i) {
4565
4566                 region = i->second;
4567
4568                 if (region->whole_file()) {
4569
4570                         if (child->source_equivalent (region)) {
4571                                 return region;
4572                         }
4573                 }
4574         }
4575
4576         return boost::shared_ptr<Region> ();
4577 }
4578
4579 int
4580 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4581 {
4582         set<boost::shared_ptr<Region> > relevant_regions;
4583
4584         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4585                 RegionFactory::get_regions_using_source (*s, relevant_regions);
4586         }
4587
4588         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4589                 set<boost::shared_ptr<Region> >::iterator tmp;
4590
4591                 tmp = r;
4592                 ++tmp;
4593
4594                 playlists->destroy_region (*r);
4595                 RegionFactory::map_remove (*r);
4596
4597                 (*r)->drop_sources ();
4598                 (*r)->drop_references ();
4599
4600                 relevant_regions.erase (r);
4601
4602                 r = tmp;
4603         }
4604
4605         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4606
4607                 {
4608                         Glib::Threads::Mutex::Lock ls (source_lock);
4609                         /* remove from the main source list */
4610                         sources.erase ((*s)->id());
4611                 }
4612
4613                 (*s)->mark_for_remove ();
4614                 (*s)->drop_references ();
4615
4616                 s = srcs.erase (s);
4617         }
4618
4619         return 0;
4620 }
4621
4622 int
4623 Session::remove_last_capture ()
4624 {
4625         list<boost::shared_ptr<Source> > srcs;
4626
4627         boost::shared_ptr<RouteList> rl = routes.reader ();
4628         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4629                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4630                 if (!tr) {
4631                         continue;
4632                 }
4633
4634                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4635
4636                 if (!l.empty()) {
4637                         srcs.insert (srcs.end(), l.begin(), l.end());
4638                         l.clear ();
4639                 }
4640         }
4641
4642         destroy_sources (srcs);
4643
4644         save_state (_current_snapshot_name);
4645
4646         return 0;
4647 }
4648
4649 /* Source Management */
4650
4651 void
4652 Session::add_source (boost::shared_ptr<Source> source)
4653 {
4654         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4655         pair<SourceMap::iterator,bool> result;
4656
4657         entry.first = source->id();
4658         entry.second = source;
4659
4660         {
4661                 Glib::Threads::Mutex::Lock lm (source_lock);
4662                 result = sources.insert (entry);
4663         }
4664
4665         if (result.second) {
4666
4667                 /* yay, new source */
4668
4669                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4670
4671                 if (fs) {
4672                         if (!fs->within_session()) {
4673                                 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4674                         }
4675                 }
4676
4677                 set_dirty();
4678
4679                 boost::shared_ptr<AudioFileSource> afs;
4680
4681                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4682                         if (Config->get_auto_analyse_audio()) {
4683                                 Analyser::queue_source_for_analysis (source, false);
4684                         }
4685                 }
4686
4687                 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4688         }
4689 }
4690
4691 void
4692 Session::remove_source (boost::weak_ptr<Source> src)
4693 {
4694         if (_state_of_the_state & Deletion) {
4695                 return;
4696         }
4697
4698         SourceMap::iterator i;
4699         boost::shared_ptr<Source> source = src.lock();
4700
4701         if (!source) {
4702                 return;
4703         }
4704
4705         {
4706                 Glib::Threads::Mutex::Lock lm (source_lock);
4707
4708                 if ((i = sources.find (source->id())) != sources.end()) {
4709                         sources.erase (i);
4710                 }
4711         }
4712
4713         if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4714
4715                 /* save state so we don't end up with a session file
4716                    referring to non-existent sources.
4717                 */
4718
4719                 save_state (_current_snapshot_name);
4720         }
4721 }
4722
4723 boost::shared_ptr<Source>
4724 Session::source_by_id (const PBD::ID& id)
4725 {
4726         Glib::Threads::Mutex::Lock lm (source_lock);
4727         SourceMap::iterator i;
4728         boost::shared_ptr<Source> source;
4729
4730         if ((i = sources.find (id)) != sources.end()) {
4731                 source = i->second;
4732         }
4733
4734         return source;
4735 }
4736
4737 boost::shared_ptr<AudioFileSource>
4738 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4739 {
4740         /* Restricted to audio files because only audio sources have channel
4741            as a property.
4742         */
4743
4744         Glib::Threads::Mutex::Lock lm (source_lock);
4745
4746         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4747                 boost::shared_ptr<AudioFileSource> afs
4748                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4749
4750                 if (afs && afs->path() == path && chn == afs->channel()) {
4751                         return afs;
4752                 }
4753         }
4754
4755         return boost::shared_ptr<AudioFileSource>();
4756 }
4757
4758 boost::shared_ptr<MidiSource>
4759 Session::midi_source_by_path (const std::string& path) const
4760 {
4761         /* Restricted to MIDI files because audio sources require a channel
4762            for unique identification, in addition to a path.
4763         */
4764
4765         Glib::Threads::Mutex::Lock lm (source_lock);
4766
4767         for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4768                 boost::shared_ptr<MidiSource> ms
4769                         = boost::dynamic_pointer_cast<MidiSource>(s->second);
4770                 boost::shared_ptr<FileSource> fs
4771                         = boost::dynamic_pointer_cast<FileSource>(s->second);
4772
4773                 if (ms && fs && fs->path() == path) {
4774                         return ms;
4775                 }
4776         }
4777
4778         return boost::shared_ptr<MidiSource>();
4779 }
4780
4781 uint32_t
4782 Session::count_sources_by_origin (const string& path)
4783 {
4784         uint32_t cnt = 0;
4785         Glib::Threads::Mutex::Lock lm (source_lock);
4786
4787         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4788                 boost::shared_ptr<FileSource> fs
4789                         = boost::dynamic_pointer_cast<FileSource>(i->second);
4790
4791                 if (fs && fs->origin() == path) {
4792                         ++cnt;
4793                 }
4794         }
4795
4796         return cnt;
4797 }
4798
4799 static string
4800 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4801         if (hash) {
4802                 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4803                 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4804         } else {
4805                 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4806         }
4807 }
4808
4809 string
4810 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4811 {
4812         string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4813
4814         if (Glib::path_is_absolute (filepath)) {
4815
4816                 /* rip the session dir from the audiofile source */
4817
4818                 string session_path;
4819                 bool in_another_session = true;
4820
4821                 if (filepath.find (interchange_dir_string) != string::npos) {
4822
4823                         session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4824                         session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4825                         session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4826                         session_path = Glib::path_get_dirname (session_path); /* now has session path */
4827
4828                         /* see if it is within our session */
4829
4830                         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4831                                 if (i->path == session_path) {
4832                                         in_another_session = false;
4833                                         break;
4834                                 }
4835                         }
4836                 } else {
4837                         in_another_session = false;
4838                 }
4839
4840
4841                 if (in_another_session) {
4842                         SessionDirectory sd (session_path);
4843                         return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4844                 }
4845         }
4846
4847         /* 1) if file belongs to this session
4848          * it may be a relative path (interchange/...)
4849          * or just basename (session_state, remove source)
4850          * -> just use the basename
4851          */
4852         std::string filename = Glib::path_get_basename (filepath);
4853         std::string path;
4854
4855         /* 2) if the file is outside our session dir:
4856          * (imported but not copied) add the path for check-summming */
4857         if (!in_session) {
4858                 path = Glib::path_get_dirname (filepath);
4859         }
4860
4861         return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4862 }
4863
4864 string
4865 Session::new_audio_source_path_for_embedded (const std::string& path)
4866 {
4867         /* embedded source:
4868          *
4869          * we know that the filename is already unique because it exists
4870          * out in the filesystem.
4871          *
4872          * However, when we bring it into the session, we could get a
4873          * collision.
4874          *
4875          * Eg. two embedded files:
4876          *
4877          *          /foo/bar/baz.wav
4878          *          /frob/nic/baz.wav
4879          *
4880          * When merged into session, these collide.
4881          *
4882          * There will not be a conflict with in-memory sources
4883          * because when the source was created we already picked
4884          * a unique name for it.
4885          *
4886          * This collision is not likely to be common, but we have to guard
4887          * against it.  So, if there is a collision, take the md5 hash of the
4888          * the path, and use that as the filename instead.
4889          */
4890
4891         SessionDirectory sdir (get_best_session_directory_for_new_audio());
4892         string base = Glib::path_get_basename (path);
4893         string newpath = Glib::build_filename (sdir.sound_path(), base);
4894
4895         if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4896
4897                 MD5 md5;
4898
4899                 md5.digestString (path.c_str());
4900                 md5.writeToString ();
4901                 base = md5.digestChars;
4902
4903                 string ext = get_suffix (path);
4904
4905                 if (!ext.empty()) {
4906                         base += '.';
4907                         base += ext;
4908                 }
4909
4910                 newpath = Glib::build_filename (sdir.sound_path(), base);
4911
4912                 /* if this collides, we're screwed */
4913
4914                 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4915                         error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4916                         return string();
4917                 }
4918
4919         }
4920
4921         return newpath;
4922 }
4923
4924 /** Return true if there are no audio file sources that use @param name as
4925  * the filename component of their path.
4926  *
4927  * Return false otherwise.
4928  *
4929  * This method MUST ONLY be used to check in-session, mono files since it
4930  * hard-codes the channel of the audio file source we are looking for as zero.
4931  *
4932  * If/when Ardour supports native files in non-mono formats, the logic here
4933  * will need to be revisited.
4934  */
4935 bool
4936 Session::audio_source_name_is_unique (const string& name)
4937 {
4938         std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4939         vector<space_and_path>::iterator i;
4940         uint32_t existing = 0;
4941
4942         for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4943
4944                 /* note that we search *without* the extension so that
4945                    we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4946                    in the event that this new name is required for
4947                    a file format change.
4948                 */
4949
4950                 const string spath = *i;
4951
4952                 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4953                         existing++;
4954                         break;
4955                 }
4956
4957                 /* it is possible that we have the path already
4958                  * assigned to a source that has not yet been written
4959                  * (ie. the write source for a diskstream). we have to
4960                  * check this in order to make sure that our candidate
4961                  * path isn't used again, because that can lead to
4962                  * two Sources point to the same file with different
4963                  * notions of their removability.
4964                  */
4965
4966
4967                 string possible_path = Glib::build_filename (spath, name);
4968
4969                 if (audio_source_by_path_and_channel (possible_path, 0)) {
4970                         existing++;
4971                         break;
4972                 }
4973         }
4974
4975         return (existing == 0);
4976 }
4977
4978 string
4979 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)
4980 {
4981         ostringstream sstr;
4982         const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4983
4984         if (Profile->get_trx() && destructive) {
4985                 sstr << 'T';
4986                 sstr << setfill ('0') << setw (4) << cnt;
4987                 sstr << legalized_base;
4988         } else {
4989                 sstr << legalized_base;
4990
4991                 if (take_required || related_exists) {
4992                         sstr << '-';
4993                         sstr << cnt;
4994                 }
4995         }
4996
4997         if (nchan == 2) {
4998                 if (chan == 0) {
4999                         sstr << "%L";
5000                 } else {
5001                         sstr << "%R";
5002                 }
5003         } else if (nchan > 2) {
5004                 if (nchan < 26) {
5005                         sstr << '%';
5006                         sstr << 'a' + chan;
5007                 } else {
5008                         /* XXX what? more than 26 channels! */
5009                         sstr << '%';
5010                         sstr << chan+1;
5011                 }
5012         }
5013
5014         sstr << ext;
5015
5016         return sstr.str();
5017 }
5018
5019 /** Return a unique name based on \a base for a new internal audio source */
5020 string
5021 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5022 {
5023         uint32_t cnt;
5024         string possible_name;
5025         const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5026         string legalized;
5027         bool some_related_source_name_exists = false;
5028
5029         legalized = legalize_for_path (base);
5030
5031         // Find a "version" of the base name that doesn't exist in any of the possible directories.
5032
5033         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5034
5035                 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5036
5037                 if (audio_source_name_is_unique (possible_name)) {
5038                         break;
5039                 }
5040
5041                 some_related_source_name_exists = true;
5042
5043                 if (cnt > limit) {
5044                         error << string_compose(
5045                                         _("There are already %1 recordings for %2, which I consider too many."),
5046                                         limit, base) << endmsg;
5047                         destroy ();
5048                         throw failed_constructor();
5049                 }
5050         }
5051
5052         /* We've established that the new name does not exist in any session
5053          * directory, so now find out which one we should use for this new
5054          * audio source.
5055          */
5056
5057         SessionDirectory sdir (get_best_session_directory_for_new_audio());
5058
5059         std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5060
5061         return s;
5062 }
5063
5064 /** Return a unique name based on `base` for a new internal MIDI source */
5065 string
5066 Session::new_midi_source_path (const string& base)
5067 {
5068         uint32_t cnt;
5069         char buf[PATH_MAX+1];
5070         const uint32_t limit = 10000;
5071         string legalized;
5072         string possible_path;
5073         string possible_name;
5074
5075         buf[0] = '\0';
5076         legalized = legalize_for_path (base);
5077
5078         // Find a "version" of the file name that doesn't exist in any of the possible directories.
5079         std::vector<string> sdirs = source_search_path(DataType::MIDI);
5080
5081         /* - the main session folder is the first in the vector.
5082          * - after checking all locations for file-name uniqueness,
5083          *   we keep the one from the last iteration as new file name
5084          * - midi files are small and should just be kept in the main session-folder
5085          *
5086          * -> reverse the array, check main session folder last and use that as location
5087          *    for MIDI files.
5088          */
5089         std::reverse(sdirs.begin(), sdirs.end());
5090
5091         for (cnt = 1; cnt <= limit; ++cnt) {
5092
5093                 vector<space_and_path>::iterator i;
5094                 uint32_t existing = 0;
5095
5096                 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5097
5098                         snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5099                         possible_name = buf;
5100
5101                         possible_path = Glib::build_filename (*i, possible_name);
5102
5103                         if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5104                                 existing++;
5105                         }
5106
5107                         if (midi_source_by_path (possible_path)) {
5108                                 existing++;
5109                         }
5110                 }
5111
5112                 if (existing == 0) {
5113                         break;
5114                 }
5115
5116                 if (cnt > limit) {
5117                         error << string_compose(
5118                                         _("There are already %1 recordings for %2, which I consider too many."),
5119                                         limit, base) << endmsg;
5120                         destroy ();
5121                         return 0;
5122                 }
5123         }
5124
5125         /* No need to "find best location" for software/app-based RAID, because
5126            MIDI is so small that we always put it in the same place.
5127         */
5128
5129         return possible_path;
5130 }
5131
5132
5133 /** Create a new within-session audio source */
5134 boost::shared_ptr<AudioFileSource>
5135 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5136 {
5137         const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5138
5139         if (!path.empty()) {
5140                 return boost::dynamic_pointer_cast<AudioFileSource> (
5141                         SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5142         } else {
5143                 throw failed_constructor ();
5144         }
5145 }
5146
5147 /** Create a new within-session MIDI source */
5148 boost::shared_ptr<MidiSource>
5149 Session::create_midi_source_for_session (string const & basic_name)
5150 {
5151         const string path = new_midi_source_path (basic_name);
5152
5153         if (!path.empty()) {
5154                 return boost::dynamic_pointer_cast<SMFSource> (
5155                         SourceFactory::createWritable (
5156                                 DataType::MIDI, *this, path, false, frame_rate()));
5157         } else {
5158                 throw failed_constructor ();
5159         }
5160 }
5161
5162 /** Create a new within-session MIDI source */
5163 boost::shared_ptr<MidiSource>
5164 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5165 {
5166         /* the caller passes in the track the source will be used in,
5167            so that we can keep the numbering sane.
5168
5169            Rationale: a track with the name "Foo" that has had N
5170            captures carried out so far will ALREADY have a write source
5171            named "Foo-N+1.mid" waiting to be used for the next capture.
5172
5173            If we call new_midi_source_name() we will get "Foo-N+2". But
5174            there is no region corresponding to "Foo-N+1", so when
5175            "Foo-N+2" appears in the track, the gap presents the user
5176            with odd behaviour - why did it skip past Foo-N+1?
5177
5178            We could explain this to the user in some odd way, but
5179            instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5180            use "Foo-N+1" here.
5181
5182            If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5183         */
5184
5185         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5186         assert (mt);
5187         std::string name = track->steal_write_source_name ();
5188
5189         if (name.empty()) {
5190                 return boost::shared_ptr<MidiSource>();
5191         }
5192
5193         /* MIDI files are small, just put them in the first location of the
5194            session source search path.
5195         */
5196
5197         const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5198
5199         return boost::dynamic_pointer_cast<SMFSource> (
5200                 SourceFactory::createWritable (
5201                         DataType::MIDI, *this, path, false, frame_rate()));
5202 }
5203
5204
5205 void
5206 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5207 {
5208         if (playlist->hidden()) {
5209                 return;
5210         }
5211
5212         playlists->add (playlist);
5213
5214         if (unused) {
5215                 playlist->release();
5216         }
5217
5218         set_dirty();
5219 }
5220
5221 void
5222 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5223 {
5224         if (_state_of_the_state & Deletion) {
5225                 return;
5226         }
5227
5228         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5229
5230         if (!playlist) {
5231                 return;
5232         }
5233
5234         playlists->remove (playlist);
5235
5236         set_dirty();
5237 }
5238
5239 void
5240 Session::set_audition (boost::shared_ptr<Region> r)
5241 {
5242         pending_audition_region = r;
5243         add_post_transport_work (PostTransportAudition);
5244         _butler->schedule_transport_work ();
5245 }
5246
5247 void
5248 Session::audition_playlist ()
5249 {
5250         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5251         ev->region.reset ();
5252         queue_event (ev);
5253 }
5254
5255
5256 void
5257 Session::register_lua_function (
5258                 const std::string& name,
5259                 const std::string& script,
5260                 const LuaScriptParamList& args
5261                 )
5262 {
5263         Glib::Threads::Mutex::Lock lm (lua_lock);
5264
5265         lua_State* L = lua.getState();
5266
5267         const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5268         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5269         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5270                 if ((*i)->optional && !(*i)->is_set) { continue; }
5271                 tbl_arg[(*i)->name] = (*i)->value;
5272         }
5273         (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5274         lm.release();
5275
5276         LuaScriptsChanged (); /* EMIT SIGNAL */
5277         set_dirty();
5278 }
5279
5280 void
5281 Session::unregister_lua_function (const std::string& name)
5282 {
5283         Glib::Threads::Mutex::Lock lm (lua_lock);
5284         (*_lua_del)(name); // throws luabridge::LuaException
5285         lua.collect_garbage ();
5286         lm.release();
5287
5288         LuaScriptsChanged (); /* EMIT SIGNAL */
5289         set_dirty();
5290 }
5291
5292 std::vector<std::string>
5293 Session::registered_lua_functions ()
5294 {
5295         Glib::Threads::Mutex::Lock lm (lua_lock);
5296         std::vector<std::string> rv;
5297
5298         try {
5299                 luabridge::LuaRef list ((*_lua_list)());
5300                 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5301                         if (!i.key ().isString ()) { assert(0); continue; }
5302                         rv.push_back (i.key ().cast<std::string> ());
5303                 }
5304         } catch (luabridge::LuaException const& e) { }
5305         return rv;
5306 }
5307
5308 #ifndef NDEBUG
5309 static void _lua_print (std::string s) {
5310         std::cout << "SessionLua: " << s << "\n";
5311 }
5312 #endif
5313
5314 void
5315 Session::try_run_lua (pframes_t nframes)
5316 {
5317         if (_n_lua_scripts == 0) return;
5318         Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5319         if (tm.locked ()) {
5320                 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5321                 lua.collect_garbage_step ();
5322         }
5323 }
5324
5325 void
5326 Session::setup_lua ()
5327 {
5328 #ifndef NDEBUG
5329         lua.Print.connect (&_lua_print);
5330 #endif
5331         lua.tweak_rt_gc ();
5332         lua.do_command (
5333                         "function ArdourSession ()"
5334                         "  local self = { scripts = {}, instances = {} }"
5335                         ""
5336                         "  local remove = function (n)"
5337                         "   self.scripts[n] = nil"
5338                         "   self.instances[n] = nil"
5339                         "   Session:scripts_changed()" // call back
5340                         "  end"
5341                         ""
5342                         "  local addinternal = function (n, f, a)"
5343                         "   assert(type(n) == 'string', 'function-name must be string')"
5344                         "   assert(type(f) == 'function', 'Given script is a not a function')"
5345                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5346                         "   assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5347                         "   self.scripts[n] = { ['f'] = f, ['a'] = a }"
5348                         "   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"
5349                         "   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 }"
5350                         "   self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5351                         "   Session:scripts_changed()" // call back
5352                         "  end"
5353                         ""
5354                         "  local add = function (n, b, a)"
5355                         "   assert(type(b) == 'string', 'ByteCode must be string')"
5356                         "   load (b)()" // assigns f
5357                         "   assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5358                         "   addinternal (n, load(f), a)"
5359                         "  end"
5360                         ""
5361                         "  local run = function (...)"
5362                         "   for n, s in pairs (self.instances) do"
5363                         "     local status, err = pcall (s, ...)"
5364                         "     if not status then"
5365                         "       print ('fn \"'.. n .. '\": ', err)"
5366                         "       remove (n)"
5367                         "      end"
5368                         "   end"
5369                         "   collectgarbage()"
5370                         "  end"
5371                         ""
5372                         "  local cleanup = function ()"
5373                         "   self.scripts = nil"
5374                         "   self.instances = nil"
5375                         "  end"
5376                         ""
5377                         "  local list = function ()"
5378                         "   local rv = {}"
5379                         "   for n, _ in pairs (self.scripts) do"
5380                         "     rv[n] = true"
5381                         "   end"
5382                         "   return rv"
5383                         "  end"
5384                         ""
5385                         "  local function basic_serialize (o)"
5386                         "    if type(o) == \"number\" then"
5387                         "     return tostring(o)"
5388                         "    else"
5389                         "     return string.format(\"%q\", o)"
5390                         "    end"
5391                         "  end"
5392                         ""
5393                         "  local function serialize (name, value)"
5394                         "   local rv = name .. ' = '"
5395                         "   collectgarbage()"
5396                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5397                         "    return rv .. basic_serialize(value) .. ' '"
5398                         "   elseif type(value) == \"table\" then"
5399                         "    rv = rv .. '{} '"
5400                         "    for k,v in pairs(value) do"
5401                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5402                         "     rv = rv .. serialize(fieldname, v) .. ' '"
5403                         "     collectgarbage()" // string concatenation allocates a new string :(
5404                         "    end"
5405                         "    return rv;"
5406                         "   elseif type(value) == \"function\" then"
5407                         "     return rv .. string.format(\"%q\", string.dump(value, true))"
5408                         "   else"
5409                         "    error('cannot save a ' .. type(value))"
5410                         "   end"
5411                         "  end"
5412                         ""
5413                         ""
5414                         "  local save = function ()"
5415                         "   return (serialize('scripts', self.scripts))"
5416                         "  end"
5417                         ""
5418                         "  local restore = function (state)"
5419                         "   self.scripts = {}"
5420                         "   load (state)()"
5421                         "   for n, s in pairs (scripts) do"
5422                         "    addinternal (n, load(s['f']), s['a'])"
5423                         "   end"
5424                         "  end"
5425                         ""
5426                         " return { run = run, add = add, remove = remove,"
5427                   "          list = list, restore = restore, save = save, cleanup = cleanup}"
5428                         " end"
5429                         " "
5430                         " sess = ArdourSession ()"
5431                         " ArdourSession = nil"
5432                         " "
5433                         "function ardour () end"
5434                         );
5435
5436         lua_State* L = lua.getState();
5437
5438         try {
5439                 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5440                 lua.do_command ("sess = nil"); // hide it.
5441                 lua.do_command ("collectgarbage()");
5442
5443                 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5444                 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5445                 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5446                 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5447                 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5448                 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5449                 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5450         } catch (luabridge::LuaException const& e) {
5451                 fatal << string_compose (_("programming error: %1"),
5452                                 X_("Failed to setup Lua interpreter"))
5453                         << endmsg;
5454                 abort(); /*NOTREACHED*/
5455         }
5456
5457         LuaBindings::stddef (L);
5458         LuaBindings::common (L);
5459         LuaBindings::dsp (L);
5460         luabridge::push <Session *> (L, this);
5461         lua_setglobal (L, "Session");
5462 }
5463
5464 void
5465 Session::scripts_changed ()
5466 {
5467         assert (!lua_lock.trylock()); // must hold lua_lock
5468
5469         try {
5470                 luabridge::LuaRef list ((*_lua_list)());
5471                 int cnt = 0;
5472                 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5473                         if (!i.key ().isString ()) { assert(0); continue; }
5474                         ++cnt;
5475                 }
5476                 _n_lua_scripts = cnt;
5477         } catch (luabridge::LuaException const& e) {
5478                 fatal << string_compose (_("programming error: %1"),
5479                                 X_("Indexing Lua Session Scripts failed."))
5480                         << endmsg;
5481                 abort(); /*NOTREACHED*/
5482         }
5483 }
5484
5485 void
5486 Session::non_realtime_set_audition ()
5487 {
5488         assert (pending_audition_region);
5489         auditioner->audition_region (pending_audition_region);
5490         pending_audition_region.reset ();
5491         AuditionActive (true); /* EMIT SIGNAL */
5492 }
5493
5494 void
5495 Session::audition_region (boost::shared_ptr<Region> r)
5496 {
5497         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5498         ev->region = r;
5499         queue_event (ev);
5500 }
5501
5502 void
5503 Session::cancel_audition ()
5504 {
5505         if (!auditioner) {
5506                 return;
5507         }
5508         if (auditioner->auditioning()) {
5509                 auditioner->cancel_audition ();
5510                 AuditionActive (false); /* EMIT SIGNAL */
5511         }
5512 }
5513
5514 bool
5515 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5516 {
5517         if (a->is_monitor()) {
5518                 return true;
5519         }
5520         if (b->is_monitor()) {
5521                 return false;
5522         }
5523         return a->presentation_info().order() < b->presentation_info().order();
5524 }
5525
5526 bool
5527 Session::is_auditioning () const
5528 {
5529         /* can be called before we have an auditioner object */
5530         if (auditioner) {
5531                 return auditioner->auditioning();
5532         } else {
5533                 return false;
5534         }
5535 }
5536
5537 void
5538 Session::graph_reordered ()
5539 {
5540         /* don't do this stuff if we are setting up connections
5541            from a set_state() call or creating new tracks. Ditto for deletion.
5542         */
5543
5544         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5545                 return;
5546         }
5547
5548         /* every track/bus asked for this to be handled but it was deferred because
5549            we were connecting. do it now.
5550         */
5551
5552         request_input_change_handling ();
5553
5554         resort_routes ();
5555
5556         /* force all diskstreams to update their capture offset values to
5557            reflect any changes in latencies within the graph.
5558         */
5559
5560         boost::shared_ptr<RouteList> rl = routes.reader ();
5561         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5562                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5563                 if (tr) {
5564                         tr->set_capture_offset ();
5565                 }
5566         }
5567 }
5568
5569 /** @return Number of frames that there is disk space available to write,
5570  *  if known.
5571  */
5572 boost::optional<framecnt_t>
5573 Session::available_capture_duration ()
5574 {
5575         Glib::Threads::Mutex::Lock lm (space_lock);
5576
5577         if (_total_free_4k_blocks_uncertain) {
5578                 return boost::optional<framecnt_t> ();
5579         }
5580
5581         float sample_bytes_on_disk = 4.0; // keep gcc happy
5582
5583         switch (config.get_native_file_data_format()) {
5584         case FormatFloat:
5585                 sample_bytes_on_disk = 4.0;
5586                 break;
5587
5588         case FormatInt24:
5589                 sample_bytes_on_disk = 3.0;
5590                 break;
5591
5592         case FormatInt16:
5593                 sample_bytes_on_disk = 2.0;
5594                 break;
5595
5596         default:
5597                 /* impossible, but keep some gcc versions happy */
5598                 fatal << string_compose (_("programming error: %1"),
5599                                          X_("illegal native file data format"))
5600                       << endmsg;
5601                 abort(); /*NOTREACHED*/
5602         }
5603
5604         double scale = 4096.0 / sample_bytes_on_disk;
5605
5606         if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5607                 return max_framecnt;
5608         }
5609
5610         return (framecnt_t) floor (_total_free_4k_blocks * scale);
5611 }
5612
5613 void
5614 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5615 {
5616         {
5617                 RCUWriter<BundleList> writer (_bundles);
5618                 boost::shared_ptr<BundleList> b = writer.get_copy ();
5619                 b->push_back (bundle);
5620         }
5621
5622         if (emit_signal) {
5623                 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5624         }
5625
5626         set_dirty();
5627 }
5628
5629 void
5630 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5631 {
5632         bool removed = false;
5633
5634         {
5635                 RCUWriter<BundleList> writer (_bundles);
5636                 boost::shared_ptr<BundleList> b = writer.get_copy ();
5637                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5638
5639                 if (i != b->end()) {
5640                         b->erase (i);
5641                         removed = true;
5642                 }
5643         }
5644
5645         if (removed) {
5646                  BundleAddedOrRemoved (); /* EMIT SIGNAL */
5647         }
5648
5649         set_dirty();
5650 }
5651
5652 boost::shared_ptr<Bundle>
5653 Session::bundle_by_name (string name) const
5654 {
5655         boost::shared_ptr<BundleList> b = _bundles.reader ();
5656
5657         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5658                 if ((*i)->name() == name) {
5659                         return* i;
5660                 }
5661         }
5662
5663         return boost::shared_ptr<Bundle> ();
5664 }
5665
5666 void
5667 Session::tempo_map_changed (const PropertyChange&)
5668 {
5669         clear_clicks ();
5670
5671         playlists->update_after_tempo_map_change ();
5672
5673         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5674
5675         set_dirty ();
5676 }
5677
5678 void
5679 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5680 {
5681         for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5682                 (*i)->recompute_frames_from_beat ();
5683         }
5684 }
5685
5686 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5687  * the given count with the current block size.
5688  */
5689 void
5690 Session::ensure_buffers (ChanCount howmany)
5691 {
5692         BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5693 }
5694
5695 void
5696 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5697 {
5698         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5699                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5700         }
5701 }
5702
5703 uint32_t
5704 Session::next_insert_id ()
5705 {
5706         /* this doesn't really loop forever. just think about it */
5707
5708         while (true) {
5709                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5710                         if (!insert_bitset[n]) {
5711                                 insert_bitset[n] = true;
5712                                 return n;
5713
5714                         }
5715                 }
5716
5717                 /* none available, so resize and try again */
5718
5719                 insert_bitset.resize (insert_bitset.size() + 16, false);
5720         }
5721 }
5722
5723 uint32_t
5724 Session::next_send_id ()
5725 {
5726         /* this doesn't really loop forever. just think about it */
5727
5728         while (true) {
5729                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5730                         if (!send_bitset[n]) {
5731                                 send_bitset[n] = true;
5732                                 return n;
5733
5734                         }
5735                 }
5736
5737                 /* none available, so resize and try again */
5738
5739                 send_bitset.resize (send_bitset.size() + 16, false);
5740         }
5741 }
5742
5743 uint32_t
5744 Session::next_aux_send_id ()
5745 {
5746         /* this doesn't really loop forever. just think about it */
5747
5748         while (true) {
5749                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5750                         if (!aux_send_bitset[n]) {
5751                                 aux_send_bitset[n] = true;
5752                                 return n;
5753
5754                         }
5755                 }
5756
5757                 /* none available, so resize and try again */
5758
5759                 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5760         }
5761 }
5762
5763 uint32_t
5764 Session::next_return_id ()
5765 {
5766         /* this doesn't really loop forever. just think about it */
5767
5768         while (true) {
5769                 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5770                         if (!return_bitset[n]) {
5771                                 return_bitset[n] = true;
5772                                 return n;
5773
5774                         }
5775                 }
5776
5777                 /* none available, so resize and try again */
5778
5779                 return_bitset.resize (return_bitset.size() + 16, false);
5780         }
5781 }
5782
5783 void
5784 Session::mark_send_id (uint32_t id)
5785 {
5786         if (id >= send_bitset.size()) {
5787                 send_bitset.resize (id+16, false);
5788         }
5789         if (send_bitset[id]) {
5790                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5791         }
5792         send_bitset[id] = true;
5793 }
5794
5795 void
5796 Session::mark_aux_send_id (uint32_t id)
5797 {
5798         if (id >= aux_send_bitset.size()) {
5799                 aux_send_bitset.resize (id+16, false);
5800         }
5801         if (aux_send_bitset[id]) {
5802                 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5803         }
5804         aux_send_bitset[id] = true;
5805 }
5806
5807 void
5808 Session::mark_return_id (uint32_t id)
5809 {
5810         if (id >= return_bitset.size()) {
5811                 return_bitset.resize (id+16, false);
5812         }
5813         if (return_bitset[id]) {
5814                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5815         }
5816         return_bitset[id] = true;
5817 }
5818
5819 void
5820 Session::mark_insert_id (uint32_t id)
5821 {
5822         if (id >= insert_bitset.size()) {
5823                 insert_bitset.resize (id+16, false);
5824         }
5825         if (insert_bitset[id]) {
5826                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5827         }
5828         insert_bitset[id] = true;
5829 }
5830
5831 void
5832 Session::unmark_send_id (uint32_t id)
5833 {
5834         if (id < send_bitset.size()) {
5835                 send_bitset[id] = false;
5836         }
5837 }
5838
5839 void
5840 Session::unmark_aux_send_id (uint32_t id)
5841 {
5842         if (id < aux_send_bitset.size()) {
5843                 aux_send_bitset[id] = false;
5844         }
5845 }
5846
5847 void
5848 Session::unmark_return_id (uint32_t id)
5849 {
5850         if (_state_of_the_state & Deletion) { return; }
5851         if (id < return_bitset.size()) {
5852                 return_bitset[id] = false;
5853         }
5854 }
5855
5856 void
5857 Session::unmark_insert_id (uint32_t id)
5858 {
5859         if (id < insert_bitset.size()) {
5860                 insert_bitset[id] = false;
5861         }
5862 }
5863
5864 void
5865 Session::reset_native_file_format ()
5866 {
5867         boost::shared_ptr<RouteList> rl = routes.reader ();
5868
5869         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5870                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5871                 if (tr) {
5872                         /* don't save state as we do this, there's no point
5873                          */
5874                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5875                         tr->reset_write_sources (false);
5876                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5877                 }
5878         }
5879 }
5880
5881 bool
5882 Session::route_name_unique (string n) const
5883 {
5884         boost::shared_ptr<RouteList> r = routes.reader ();
5885
5886         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5887                 if ((*i)->name() == n) {
5888                         return false;
5889                 }
5890         }
5891
5892         return true;
5893 }
5894
5895 bool
5896 Session::route_name_internal (string n) const
5897 {
5898         if (auditioner && auditioner->name() == n) {
5899                 return true;
5900         }
5901
5902         if (_click_io && _click_io->name() == n) {
5903                 return true;
5904         }
5905
5906         return false;
5907 }
5908
5909 int
5910 Session::freeze_all (InterThreadInfo& itt)
5911 {
5912         boost::shared_ptr<RouteList> r = routes.reader ();
5913
5914         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5915
5916                 boost::shared_ptr<Track> t;
5917
5918                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5919                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
5920                            of every track.
5921                         */
5922                         t->freeze_me (itt);
5923                 }
5924         }
5925
5926         return 0;
5927 }
5928
5929 boost::shared_ptr<Region>
5930 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5931                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5932                           InterThreadInfo& itt,
5933                           boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5934                           bool for_export, bool for_freeze)
5935 {
5936         boost::shared_ptr<Region> result;
5937         boost::shared_ptr<Playlist> playlist;
5938         boost::shared_ptr<Source> source;
5939         ChanCount diskstream_channels (track.n_channels());
5940         framepos_t position;
5941         framecnt_t this_chunk;
5942         framepos_t to_do;
5943         framepos_t latency_skip;
5944         BufferSet buffers;
5945         framepos_t len = end - start;
5946         bool need_block_size_reset = false;
5947         ChanCount const max_proc = track.max_processor_streams ();
5948         string legal_playlist_name;
5949         string possible_path;
5950
5951         if (end <= start) {
5952                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5953                                          end, start) << endmsg;
5954                 return result;
5955         }
5956
5957         diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5958                         include_endpoint, for_export, for_freeze);
5959
5960         if (diskstream_channels.n(track.data_type()) < 1) {
5961                 error << _("Cannot write a range with no data.") << endmsg;
5962                 return result;
5963         }
5964
5965         // block all process callback handling
5966
5967         block_processing ();
5968
5969         {
5970                 // synchronize with AudioEngine::process_callback()
5971                 // make sure processing is not currently running
5972                 // and processing_blocked() is honored before
5973                 // acquiring thread buffers
5974                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5975         }
5976
5977         _bounce_processing_active = true;
5978
5979         /* call tree *MUST* hold route_lock */
5980
5981         if ((playlist = track.playlist()) == 0) {
5982                 goto out;
5983         }
5984
5985         legal_playlist_name = legalize_for_path (playlist->name());
5986
5987         for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5988
5989                 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5990                 string path = ((track.data_type() == DataType::AUDIO)
5991                                ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5992                                : new_midi_source_path (legal_playlist_name));
5993
5994                 if (path.empty()) {
5995                         goto out;
5996                 }
5997
5998                 try {
5999                         source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6000                 }
6001
6002                 catch (failed_constructor& err) {
6003                         error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6004                         goto out;
6005                 }
6006
6007                 srcs.push_back (source);
6008         }
6009
6010         /* tell redirects that care that we are about to use a much larger
6011          * blocksize. this will flush all plugins too, so that they are ready
6012          * to be used for this process.
6013          */
6014
6015         need_block_size_reset = true;
6016         track.set_block_size (bounce_chunk_size);
6017         _engine.main_thread()->get_buffers ();
6018
6019         position = start;
6020         to_do = len;
6021         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6022
6023         /* create a set of reasonably-sized buffers */
6024         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6025                 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6026         }
6027         buffers.set_count (max_proc);
6028
6029         for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6030                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6031                 boost::shared_ptr<MidiSource> ms;
6032                 if (afs) {
6033                         afs->prepare_for_peakfile_writes ();
6034                 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6035                         Source::Lock lock(ms->mutex());
6036                         ms->mark_streaming_write_started(lock);
6037                 }
6038         }
6039
6040         while (to_do && !itt.cancel) {
6041
6042                 this_chunk = min (to_do, bounce_chunk_size);
6043
6044                 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6045                         goto out;
6046                 }
6047
6048                 start += this_chunk;
6049                 to_do -= this_chunk;
6050                 itt.progress = (float) (1.0 - ((double) to_do / len));
6051
6052                 if (latency_skip >= bounce_chunk_size) {
6053                         latency_skip -= bounce_chunk_size;
6054                         continue;
6055                 }
6056
6057                 const framecnt_t current_chunk = this_chunk - latency_skip;
6058
6059                 uint32_t n = 0;
6060                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6061                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6062                         boost::shared_ptr<MidiSource> ms;
6063
6064                         if (afs) {
6065                                 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6066                                         goto out;
6067                                 }
6068                         } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6069                                 Source::Lock lock(ms->mutex());
6070
6071                                 const MidiBuffer& buf = buffers.get_midi(0);
6072                                 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6073                                         Evoral::Event<framepos_t> ev = *i;
6074                                         ev.set_time(ev.time() - position);
6075                                         ms->append_event_frames(lock, ev, ms->timeline_position());
6076                                 }
6077                         }
6078                 }
6079                 latency_skip = 0;
6080         }
6081
6082         /* post-roll, pick up delayed processor output */
6083         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6084
6085         while (latency_skip && !itt.cancel) {
6086                 this_chunk = min (latency_skip, bounce_chunk_size);
6087                 latency_skip -= this_chunk;
6088
6089                 buffers.silence (this_chunk, 0);
6090                 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6091
6092                 uint32_t n = 0;
6093                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6094                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6095
6096                         if (afs) {
6097                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6098                                         goto out;
6099                                 }
6100                         }
6101                 }
6102         }
6103
6104         if (!itt.cancel) {
6105
6106                 time_t now;
6107                 struct tm* xnow;
6108                 time (&now);
6109                 xnow = localtime (&now);
6110
6111                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6112                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6113                         boost::shared_ptr<MidiSource> ms;
6114
6115                         if (afs) {
6116                                 afs->update_header (position, *xnow, now);
6117                                 afs->flush_header ();
6118                         } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6119                                 Source::Lock lock(ms->mutex());
6120                                 ms->mark_streaming_write_completed(lock);
6121                         }
6122                 }
6123
6124                 /* construct a region to represent the bounced material */
6125
6126                 PropertyList plist;
6127
6128                 plist.add (Properties::start, 0);
6129                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6130                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6131
6132                 result = RegionFactory::create (srcs, plist);
6133
6134         }
6135
6136   out:
6137         if (!result) {
6138                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6139                         (*src)->mark_for_remove ();
6140                         (*src)->drop_references ();
6141                 }
6142
6143         } else {
6144                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6145                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6146
6147                         if (afs)
6148                                 afs->done_with_peakfile_writes ();
6149                 }
6150         }
6151
6152         _bounce_processing_active = false;
6153
6154         if (need_block_size_reset) {
6155                 _engine.main_thread()->drop_buffers ();
6156                 track.set_block_size (get_block_size());
6157         }
6158
6159         unblock_processing ();
6160
6161         return result;
6162 }
6163
6164 gain_t*
6165 Session::gain_automation_buffer() const
6166 {
6167         return ProcessThread::gain_automation_buffer ();
6168 }
6169
6170 gain_t*
6171 Session::trim_automation_buffer() const
6172 {
6173         return ProcessThread::trim_automation_buffer ();
6174 }
6175
6176 gain_t*
6177 Session::send_gain_automation_buffer() const
6178 {
6179         return ProcessThread::send_gain_automation_buffer ();
6180 }
6181
6182 pan_t**
6183 Session::pan_automation_buffer() const
6184 {
6185         return ProcessThread::pan_automation_buffer ();
6186 }
6187
6188 BufferSet&
6189 Session::get_silent_buffers (ChanCount count)
6190 {
6191         return ProcessThread::get_silent_buffers (count);
6192 }
6193
6194 BufferSet&
6195 Session::get_scratch_buffers (ChanCount count, bool silence)
6196 {
6197         return ProcessThread::get_scratch_buffers (count, silence);
6198 }
6199
6200 BufferSet&
6201 Session::get_noinplace_buffers (ChanCount count)
6202 {
6203         return ProcessThread::get_noinplace_buffers (count);
6204 }
6205
6206 BufferSet&
6207 Session::get_route_buffers (ChanCount count, bool silence)
6208 {
6209         return ProcessThread::get_route_buffers (count, silence);
6210 }
6211
6212
6213 BufferSet&
6214 Session::get_mix_buffers (ChanCount count)
6215 {
6216         return ProcessThread::get_mix_buffers (count);
6217 }
6218
6219 uint32_t
6220 Session::ntracks () const
6221 {
6222         uint32_t n = 0;
6223         boost::shared_ptr<RouteList> r = routes.reader ();
6224
6225         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6226                 if (boost::dynamic_pointer_cast<Track> (*i)) {
6227                         ++n;
6228                 }
6229         }
6230
6231         return n;
6232 }
6233
6234 uint32_t
6235 Session::nbusses () const
6236 {
6237         uint32_t n = 0;
6238         boost::shared_ptr<RouteList> r = routes.reader ();
6239
6240         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6241                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6242                         ++n;
6243                 }
6244         }
6245
6246         return n;
6247 }
6248
6249 void
6250 Session::add_automation_list(AutomationList *al)
6251 {
6252         automation_lists[al->id()] = al;
6253 }
6254
6255 /** @return true if there is at least one record-enabled track, otherwise false */
6256 bool
6257 Session::have_rec_enabled_track () const
6258 {
6259         return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6260 }
6261
6262 bool
6263 Session::have_rec_disabled_track () const
6264 {
6265     return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6266 }
6267
6268 /** Update the state of our rec-enabled tracks flag */
6269 void
6270 Session::update_route_record_state ()
6271 {
6272         boost::shared_ptr<RouteList> rl = routes.reader ();
6273         RouteList::iterator i = rl->begin();
6274         while (i != rl->end ()) {
6275
6276                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6277                                     if (tr && tr->rec_enable_control()->get_value()) {
6278                         break;
6279                 }
6280
6281                 ++i;
6282         }
6283
6284         int const old = g_atomic_int_get (&_have_rec_enabled_track);
6285
6286         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6287
6288         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6289                 RecordStateChanged (); /* EMIT SIGNAL */
6290         }
6291
6292         for (i = rl->begin(); i != rl->end (); ++i) {
6293                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6294                 if (tr && !tr->rec_enable_control()->get_value()) {
6295                         break;
6296                 }
6297         }
6298
6299         g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6300
6301         bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6302
6303         if (record_status() == Recording && record_arm_state_changed ) {
6304                 RecordArmStateChanged ();
6305         }
6306
6307 }
6308
6309 void
6310 Session::listen_position_changed ()
6311 {
6312         ProcessorChangeBlocker pcb (this);
6313         boost::shared_ptr<RouteList> r = routes.reader ();
6314         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6315                 (*i)->listen_position_changed ();
6316         }
6317 }
6318
6319 void
6320 Session::solo_control_mode_changed ()
6321 {
6322         if (soloing() || listening()) {
6323                 if (loading()) {
6324                         /* We can't use ::clear_all_solo_state() here because during
6325                            session loading at program startup, that will queue a call
6326                            to rt_clear_all_solo_state() that will not execute until
6327                            AFTER solo states have been established (thus throwing away
6328                            the session's saved solo state). So just explicitly turn
6329                            them all off.
6330                         */
6331                         set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6332                 } else {
6333                         clear_all_solo_state (get_routes());
6334                 }
6335         }
6336 }
6337
6338 /** Called when a property of one of our route groups changes */
6339 void
6340 Session::route_group_property_changed (RouteGroup* rg)
6341 {
6342         RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6343 }
6344
6345 /** Called when a route is added to one of our route groups */
6346 void
6347 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6348 {
6349         RouteAddedToRouteGroup (rg, r);
6350 }
6351
6352 /** Called when a route is removed from one of our route groups */
6353 void
6354 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6355 {
6356         update_route_record_state ();
6357         RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6358
6359         if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6360                 remove_route_group (*rg);
6361         }
6362 }
6363
6364 boost::shared_ptr<RouteList>
6365 Session::get_tracks () const
6366 {
6367         boost::shared_ptr<RouteList> rl = routes.reader ();
6368         boost::shared_ptr<RouteList> tl (new RouteList);
6369
6370         for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6371                 if (boost::dynamic_pointer_cast<Track> (*r)) {
6372                         if (!(*r)->is_auditioner()) {
6373                                 tl->push_back (*r);
6374                         }
6375                 }
6376         }
6377         return tl;
6378 }
6379
6380 boost::shared_ptr<RouteList>
6381 Session::get_routes_with_regions_at (framepos_t const p) const
6382 {
6383         boost::shared_ptr<RouteList> r = routes.reader ();
6384         boost::shared_ptr<RouteList> rl (new RouteList);
6385
6386         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6387                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6388                 if (!tr) {
6389                         continue;
6390                 }
6391
6392                 boost::shared_ptr<Playlist> pl = tr->playlist ();
6393                 if (!pl) {
6394                         continue;
6395                 }
6396
6397                 if (pl->has_region_at (p)) {
6398                         rl->push_back (*i);
6399                 }
6400         }
6401
6402         return rl;
6403 }
6404
6405 void
6406 Session::goto_end ()
6407 {
6408         if (_session_range_location) {
6409                 request_locate (_session_range_location->end(), false);
6410         } else {
6411                 request_locate (0, false);
6412         }
6413 }
6414
6415 void
6416 Session::goto_start (bool and_roll)
6417 {
6418         if (_session_range_location) {
6419                 request_locate (_session_range_location->start(), and_roll);
6420         } else {
6421                 request_locate (0, and_roll);
6422         }
6423 }
6424
6425 framepos_t
6426 Session::current_start_frame () const
6427 {
6428         return _session_range_location ? _session_range_location->start() : 0;
6429 }
6430
6431 framepos_t
6432 Session::current_end_frame () const
6433 {
6434         return _session_range_location ? _session_range_location->end() : 0;
6435 }
6436
6437 void
6438 Session::set_session_range_location (framepos_t start, framepos_t end)
6439 {
6440         _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6441         _locations->add (_session_range_location);
6442 }
6443
6444 void
6445 Session::step_edit_status_change (bool yn)
6446 {
6447         bool send = false;
6448
6449         bool val = false;
6450         if (yn) {
6451                 send = (_step_editors == 0);
6452                 val = true;
6453
6454                 _step_editors++;
6455         } else {
6456                 send = (_step_editors == 1);
6457                 val = false;
6458
6459                 if (_step_editors > 0) {
6460                         _step_editors--;
6461                 }
6462         }
6463
6464         if (send) {
6465                 StepEditStatusChange (val);
6466         }
6467 }
6468
6469
6470 void
6471 Session::start_time_changed (framepos_t old)
6472 {
6473         /* Update the auto loop range to match the session range
6474            (unless the auto loop range has been changed by the user)
6475         */
6476
6477         Location* s = _locations->session_range_location ();
6478         if (s == 0) {
6479                 return;
6480         }
6481
6482         Location* l = _locations->auto_loop_location ();
6483
6484         if (l && l->start() == old) {
6485                 l->set_start (s->start(), true);
6486         }
6487         set_dirty ();
6488 }
6489
6490 void
6491 Session::end_time_changed (framepos_t old)
6492 {
6493         /* Update the auto loop range to match the session range
6494            (unless the auto loop range has been changed by the user)
6495         */
6496
6497         Location* s = _locations->session_range_location ();
6498         if (s == 0) {
6499                 return;
6500         }
6501
6502         Location* l = _locations->auto_loop_location ();
6503
6504         if (l && l->end() == old) {
6505                 l->set_end (s->end(), true);
6506         }
6507         set_dirty ();
6508 }
6509
6510 std::vector<std::string>
6511 Session::source_search_path (DataType type) const
6512 {
6513         Searchpath sp;
6514
6515         if (session_dirs.size() == 1) {
6516                 switch (type) {
6517                 case DataType::AUDIO:
6518                         sp.push_back (_session_dir->sound_path());
6519                         break;
6520                 case DataType::MIDI:
6521                         sp.push_back (_session_dir->midi_path());
6522                         break;
6523                 }
6524         } else {
6525                 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6526                         SessionDirectory sdir (i->path);
6527                         switch (type) {
6528                         case DataType::AUDIO:
6529                                 sp.push_back (sdir.sound_path());
6530                                 break;
6531                         case DataType::MIDI:
6532                                 sp.push_back (sdir.midi_path());
6533                                 break;
6534                         }
6535                 }
6536         }
6537
6538         if (type == DataType::AUDIO) {
6539                 const string sound_path_2X = _session_dir->sound_path_2X();
6540                 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6541                         if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6542                                 sp.push_back (sound_path_2X);
6543                         }
6544                 }
6545         }
6546
6547         // now check the explicit (possibly user-specified) search path
6548
6549         switch (type) {
6550         case DataType::AUDIO:
6551                 sp += Searchpath(config.get_audio_search_path ());
6552                 break;
6553         case DataType::MIDI:
6554                 sp += Searchpath(config.get_midi_search_path ());
6555                 break;
6556         }
6557
6558         return sp;
6559 }
6560
6561 void
6562 Session::ensure_search_path_includes (const string& path, DataType type)
6563 {
6564         Searchpath sp;
6565
6566         if (path == ".") {
6567                 return;
6568         }
6569
6570         switch (type) {
6571         case DataType::AUDIO:
6572                 sp += Searchpath(config.get_audio_search_path ());
6573                 break;
6574         case DataType::MIDI:
6575                 sp += Searchpath (config.get_midi_search_path ());
6576                 break;
6577         }
6578
6579         for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6580                 /* No need to add this new directory if it has the same inode as
6581                    an existing one; checking inode rather than name prevents duplicated
6582                    directories when we are using symlinks.
6583
6584                    On Windows, I think we could just do if (*i == path) here.
6585                 */
6586                 if (PBD::equivalent_paths (*i, path)) {
6587                         return;
6588                 }
6589         }
6590
6591         sp += path;
6592
6593         switch (type) {
6594         case DataType::AUDIO:
6595                 config.set_audio_search_path (sp.to_string());
6596                 break;
6597         case DataType::MIDI:
6598                 config.set_midi_search_path (sp.to_string());
6599                 break;
6600         }
6601 }
6602
6603 void
6604 Session::remove_dir_from_search_path (const string& dir, DataType type)
6605 {
6606         Searchpath sp;
6607
6608         switch (type) {
6609         case DataType::AUDIO:
6610                 sp = Searchpath(config.get_audio_search_path ());
6611                 break;
6612         case DataType::MIDI:
6613                 sp = Searchpath (config.get_midi_search_path ());
6614                 break;
6615         }
6616
6617         sp -= dir;
6618
6619         switch (type) {
6620         case DataType::AUDIO:
6621                 config.set_audio_search_path (sp.to_string());
6622                 break;
6623         case DataType::MIDI:
6624                 config.set_midi_search_path (sp.to_string());
6625                 break;
6626         }
6627
6628 }
6629
6630 boost::shared_ptr<Speakers>
6631 Session::get_speakers()
6632 {
6633         return _speakers;
6634 }
6635
6636 list<string>
6637 Session::unknown_processors () const
6638 {
6639         list<string> p;
6640
6641         boost::shared_ptr<RouteList> r = routes.reader ();
6642         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6643                 list<string> t = (*i)->unknown_processors ();
6644                 copy (t.begin(), t.end(), back_inserter (p));
6645         }
6646
6647         p.sort ();
6648         p.unique ();
6649
6650         return p;
6651 }
6652
6653 void
6654 Session::update_latency (bool playback)
6655 {
6656
6657         DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6658
6659         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6660                 return;
6661         }
6662
6663         boost::shared_ptr<RouteList> r = routes.reader ();
6664         framecnt_t max_latency = 0;
6665
6666         if (playback) {
6667                 /* reverse the list so that we work backwards from the last route to run to the first */
6668                 RouteList* rl = routes.reader().get();
6669                 r.reset (new RouteList (*rl));
6670                 reverse (r->begin(), r->end());
6671         }
6672
6673         /* compute actual latency values for the given direction and store them all in per-port
6674            structures. this will also publish the same values (to JACK) so that computation of latency
6675            for routes can consistently use public latency values.
6676         */
6677
6678         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6679                 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6680         }
6681
6682         /* because we latency compensate playback, our published playback latencies should
6683            be the same for all output ports - all material played back by ardour has
6684            the same latency, whether its caused by plugins or by latency compensation. since
6685            these may differ from the values computed above, reset all playback port latencies
6686            to the same value.
6687         */
6688
6689         DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6690
6691         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6692                 (*i)->set_public_port_latencies (max_latency, playback);
6693         }
6694
6695         if (playback) {
6696
6697                 post_playback_latency ();
6698
6699         } else {
6700
6701                 post_capture_latency ();
6702         }
6703
6704         DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6705 }
6706
6707 void
6708 Session::post_playback_latency ()
6709 {
6710         set_worst_playback_latency ();
6711
6712         boost::shared_ptr<RouteList> r = routes.reader ();
6713
6714         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6715                 if (!(*i)->is_auditioner() && ((*i)->active())) {
6716                         _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6717                 }
6718         }
6719
6720         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6721                 (*i)->set_latency_compensation (_worst_track_latency);
6722         }
6723 }
6724
6725 void
6726 Session::post_capture_latency ()
6727 {
6728         set_worst_capture_latency ();
6729
6730         /* reflect any changes in capture latencies into capture offsets
6731          */
6732
6733         boost::shared_ptr<RouteList> rl = routes.reader();
6734         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6735                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6736                 if (tr) {
6737                         tr->set_capture_offset ();
6738                 }
6739         }
6740 }
6741
6742 void
6743 Session::initialize_latencies ()
6744 {
6745         {
6746                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6747                 update_latency (false);
6748                 update_latency (true);
6749         }
6750
6751         set_worst_io_latencies ();
6752 }
6753
6754 void
6755 Session::set_worst_io_latencies ()
6756 {
6757         set_worst_playback_latency ();
6758         set_worst_capture_latency ();
6759 }
6760
6761 void
6762 Session::set_worst_playback_latency ()
6763 {
6764         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6765                 return;
6766         }
6767
6768         _worst_output_latency = 0;
6769
6770         if (!_engine.connected()) {
6771                 return;
6772         }
6773
6774         boost::shared_ptr<RouteList> r = routes.reader ();
6775
6776         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6777                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6778         }
6779
6780         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6781 }
6782
6783 void
6784 Session::set_worst_capture_latency ()
6785 {
6786         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6787                 return;
6788         }
6789
6790         _worst_input_latency = 0;
6791
6792         if (!_engine.connected()) {
6793                 return;
6794         }
6795
6796         boost::shared_ptr<RouteList> r = routes.reader ();
6797
6798         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6799                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6800         }
6801
6802         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6803 }
6804
6805 void
6806 Session::update_latency_compensation (bool force_whole_graph)
6807 {
6808         bool some_track_latency_changed = false;
6809
6810         if (_state_of_the_state & (InitialConnecting|Deletion)) {
6811                 return;
6812         }
6813
6814         DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6815
6816         _worst_track_latency = 0;
6817
6818         boost::shared_ptr<RouteList> r = routes.reader ();
6819
6820         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6821                 if (!(*i)->is_auditioner() && ((*i)->active())) {
6822                         framecnt_t tl;
6823                         if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6824                                 some_track_latency_changed = true;
6825                         }
6826                         _worst_track_latency = max (tl, _worst_track_latency);
6827                 }
6828         }
6829
6830         DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6831                                                      (some_track_latency_changed ? "yes" : "no")));
6832
6833         DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6834
6835         if (some_track_latency_changed || force_whole_graph)  {
6836                 _engine.update_latencies ();
6837         }
6838
6839
6840         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6841                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6842                 if (!tr) {
6843                         continue;
6844                 }
6845                 tr->set_capture_offset ();
6846         }
6847 }
6848
6849 char
6850 Session::session_name_is_legal (const string& path)
6851 {
6852         char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6853
6854         for (int i = 0; illegal_chars[i]; ++i) {
6855                 if (path.find (illegal_chars[i]) != string::npos) {
6856                         return illegal_chars[i];
6857                 }
6858         }
6859
6860         return 0;
6861 }
6862
6863 void
6864 Session::notify_presentation_info_change ()
6865 {
6866         if (deletion_in_progress()) {
6867                 return;
6868         }
6869
6870         reassign_track_numbers();
6871
6872 #ifdef USE_TRACKS_CODE_FEATURES
6873         /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6874          * if track order has been changed by user
6875          */
6876         reconnect_existing_routes(true, true);
6877 #endif
6878
6879 }
6880
6881 bool
6882 Session::operation_in_progress (GQuark op) const
6883 {
6884         return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6885 }
6886
6887 boost::shared_ptr<Port>
6888 Session::ltc_input_port () const
6889 {
6890         return _ltc_input->nth (0);
6891 }
6892
6893 boost::shared_ptr<Port>
6894 Session::ltc_output_port () const
6895 {
6896         return _ltc_output->nth (0);
6897 }
6898
6899 void
6900 Session::reconnect_ltc_input ()
6901 {
6902         if (_ltc_input) {
6903
6904                 string src = Config->get_ltc_source_port();
6905
6906                 _ltc_input->disconnect (this);
6907
6908                 if (src != _("None") && !src.empty())  {
6909                         _ltc_input->nth (0)->connect (src);
6910                 }
6911
6912                 if ( ARDOUR::Profile->get_trx () ) {
6913                         // Tracks need this signal to update timecode_source_dropdown
6914                         MtcOrLtcInputPortChanged (); //emit signal
6915                 }
6916         }
6917 }
6918
6919 void
6920 Session::reconnect_ltc_output ()
6921 {
6922         if (_ltc_output) {
6923
6924                 string src = Config->get_ltc_output_port();
6925
6926                 _ltc_output->disconnect (this);
6927
6928                 if (src != _("None") && !src.empty())  {
6929                         _ltc_output->nth (0)->connect (src);
6930                 }
6931         }
6932 }
6933
6934 void
6935 Session::set_range_selection (framepos_t start, framepos_t end)
6936 {
6937         _range_selection = Evoral::Range<framepos_t> (start, end);
6938 #ifdef USE_TRACKS_CODE_FEATURES
6939         follow_playhead_priority ();
6940 #endif
6941 }
6942
6943 void
6944 Session::set_object_selection (framepos_t start, framepos_t end)
6945 {
6946         _object_selection = Evoral::Range<framepos_t> (start, end);
6947 #ifdef USE_TRACKS_CODE_FEATURES
6948         follow_playhead_priority ();
6949 #endif
6950 }
6951
6952 void
6953 Session::clear_range_selection ()
6954 {
6955         _range_selection = Evoral::Range<framepos_t> (-1,-1);
6956 #ifdef USE_TRACKS_CODE_FEATURES
6957         follow_playhead_priority ();
6958 #endif
6959 }
6960
6961 void
6962 Session::clear_object_selection ()
6963 {
6964         _object_selection = Evoral::Range<framepos_t> (-1,-1);
6965 #ifdef USE_TRACKS_CODE_FEATURES
6966         follow_playhead_priority ();
6967 #endif
6968 }
6969
6970 void
6971 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6972                 const ChanCount& input_start,
6973                 const ChanCount& output_start,
6974                 const ChanCount& input_offset,
6975                 const ChanCount& output_offset)
6976 {
6977         Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6978         _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6979                                 input_start, output_start,
6980                                 input_offset, output_offset));
6981
6982         auto_connect_thread_wakeup ();
6983 }
6984
6985 void
6986 Session::auto_connect_thread_wakeup ()
6987 {
6988         if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6989                 pthread_cond_signal (&_auto_connect_cond);
6990                 pthread_mutex_unlock (&_auto_connect_mutex);
6991         }
6992 }
6993
6994 void
6995 Session::queue_latency_recompute ()
6996 {
6997         g_atomic_int_inc (&_latency_recompute_pending);
6998         auto_connect_thread_wakeup ();
6999 }
7000
7001 void
7002 Session::auto_connect (const AutoConnectRequest& ar)
7003 {
7004         boost::shared_ptr<Route> route = ar.route.lock();
7005
7006         if (!route) { return; }
7007
7008         if (!IO::connecting_legal) {
7009                 return;
7010         }
7011
7012         /* If both inputs and outputs are auto-connected to physical ports,
7013          * use the max of input and output offsets to ensure auto-connected
7014          * port numbers always match up (e.g. the first audio input and the
7015          * first audio output of the route will have the same physical
7016          * port number).  Otherwise just use the lowest input or output
7017          * offset possible.
7018          */
7019
7020         const bool in_out_physical =
7021                 (Config->get_input_auto_connect() & AutoConnectPhysical)
7022                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7023                 && ar.connect_inputs;
7024
7025         const ChanCount in_offset = in_out_physical
7026                 ? ChanCount::max(ar.input_offset, ar.output_offset)
7027                 : ar.input_offset;
7028
7029         const ChanCount out_offset = in_out_physical
7030                 ? ChanCount::max(ar.input_offset, ar.output_offset)
7031                 : ar.output_offset;
7032
7033         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7034                 vector<string> physinputs;
7035                 vector<string> physoutputs;
7036
7037
7038                 /* for connecting track inputs we only want MIDI ports marked
7039                  * for "music".
7040                  */
7041
7042                 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7043
7044                 if (!physinputs.empty() && ar.connect_inputs) {
7045                         uint32_t nphysical_in = physinputs.size();
7046
7047                         for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7048                                 string port;
7049
7050                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7051                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7052                                 }
7053
7054                                 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7055                                         break;
7056                                 }
7057                         }
7058                 }
7059
7060                 if (!physoutputs.empty()) {
7061                         uint32_t nphysical_out = physoutputs.size();
7062                         for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7063                                 string port;
7064
7065                                 /* Waves Tracks:
7066                                  * do not create new connections if we reached the limit of physical outputs
7067                                  * in Multi Out mode
7068                                  */
7069                                 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7070                                                 ARDOUR::Profile->get_trx () &&
7071                                                 ar.output_offset.get(*t) == nphysical_out ) {
7072                                         break;
7073                                 }
7074
7075                                 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7076                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7077                                 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7078                                         /* master bus is audio only */
7079                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7080                                                 port = _master_out->input()->ports().port(*t,
7081                                                                 i % _master_out->input()->n_ports().get(*t))->name();
7082                                         }
7083                                 }
7084
7085                                 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7086                                         break;
7087                                 }
7088                         }
7089                 }
7090         }
7091 }
7092
7093 void
7094 Session::auto_connect_thread_start ()
7095 {
7096         if (g_atomic_int_get (&_ac_thread_active)) {
7097                 return;
7098         }
7099
7100         while (!_auto_connect_queue.empty ()) {
7101                 _auto_connect_queue.pop ();
7102         }
7103
7104         g_atomic_int_set (&_ac_thread_active, 1);
7105         if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7106                 g_atomic_int_set (&_ac_thread_active, 0);
7107         }
7108 }
7109
7110 void
7111 Session::auto_connect_thread_terminate ()
7112 {
7113         if (!g_atomic_int_get (&_ac_thread_active)) {
7114                 return;
7115         }
7116
7117         {
7118                 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7119                 while (!_auto_connect_queue.empty ()) {
7120                         _auto_connect_queue.pop ();
7121                 }
7122         }
7123
7124         /* cannot use auto_connect_thread_wakeup() because that is allowed to
7125          * fail to wakeup the thread.
7126          */
7127
7128         pthread_mutex_lock (&_auto_connect_mutex);
7129         g_atomic_int_set (&_ac_thread_active, 0);
7130         pthread_cond_signal (&_auto_connect_cond);
7131         pthread_mutex_unlock (&_auto_connect_mutex);
7132
7133         void *status;
7134         pthread_join (_auto_connect_thread, &status);
7135 }
7136
7137 void *
7138 Session::auto_connect_thread (void *arg)
7139 {
7140         Session *s = static_cast<Session *>(arg);
7141         s->auto_connect_thread_run ();
7142         pthread_exit (0);
7143         return 0;
7144 }
7145
7146 void
7147 Session::auto_connect_thread_run ()
7148 {
7149         pthread_set_name (X_("autoconnect"));
7150         SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7151         PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7152         pthread_mutex_lock (&_auto_connect_mutex);
7153         while (g_atomic_int_get (&_ac_thread_active)) {
7154
7155                 if (!_auto_connect_queue.empty ()) {
7156                         // Why would we need the process lock ??
7157                         // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7158                         //   graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7159                         //   All ardour-internal backends use a std::vector   xxxAudioBackend::find_port()
7160                         //   We have control over those, but what does jack do?
7161                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7162
7163                         Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7164                         while (!_auto_connect_queue.empty ()) {
7165                                 const AutoConnectRequest ar (_auto_connect_queue.front());
7166                                 _auto_connect_queue.pop ();
7167                                 lx.release ();
7168                                 auto_connect (ar);
7169                                 lx.acquire ();
7170                         }
7171                 }
7172
7173                 if (!actively_recording ()) { // might not be needed,
7174                         /* this is only used for updating plugin latencies, the
7175                          * graph does not change. so it's safe in general.
7176                          * BUT..
7177                          * .. update_latency_compensation () entails set_capture_offset()
7178                          * which calls Diskstream::set_capture_offset () which
7179                          * modifies the capture offset... which can be a proplem
7180                          * in "prepare_to_stop"
7181                          */
7182                         while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7183                                 update_latency_compensation ();
7184                         }
7185                 }
7186
7187                 {
7188                         // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7189                         // jack1 cannot cope with removing ports while processing
7190                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7191                         AudioEngine::instance()->clear_pending_port_deletions ();
7192                 }
7193
7194                 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7195         }
7196         pthread_mutex_unlock (&_auto_connect_mutex);
7197 }
7198
7199 void
7200 Session::cancel_all_solo ()
7201 {
7202         StripableList sl;
7203
7204         get_stripables (sl);
7205
7206         set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7207         clear_all_solo_state (routes.reader());
7208 }