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