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