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