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