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