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