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