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