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