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