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