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