2 Copyright (C) 1999-2010 Paul Davis
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.
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.
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.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
36 #include <boost/algorithm/string/erase.hpp>
38 #include "pbd/basename.h"
39 #include "pbd/convert.h"
40 #include "pbd/error.h"
41 #include "pbd/file_utils.h"
43 #include "pbd/pthread_utils.h"
44 #include "pbd/search_path.h"
45 #include "pbd/stacktrace.h"
46 #include "pbd/stl_delete.h"
47 #include "pbd/replace_all.h"
48 #include "pbd/unwind.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/boost_debug.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"
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/playlist_factory.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/revision.h"
94 #include "ardour/route_graph.h"
95 #include "ardour/route_group.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/solo_isolate_control.h"
102 #include "ardour/source_factory.h"
103 #include "ardour/speakers.h"
104 #include "ardour/tempo.h"
105 #include "ardour/ticker.h"
106 #include "ardour/track.h"
107 #include "ardour/user_bundle.h"
108 #include "ardour/utils.h"
109 #include "ardour/vca_manager.h"
110 #include "ardour/vca.h"
112 #include "midi++/port.h"
113 #include "midi++/mmc.h"
115 #include "LuaBridge/LuaBridge.h"
117 #include "pbd/i18n.h"
119 #include <glibmm/checksum.h>
128 using namespace ARDOUR;
131 bool Session::_disable_all_loaded_plugins = false;
132 bool Session::_bypass_all_loaded_plugins = false;
133 guint Session::_name_id_counter = 0;
135 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
136 PBD::Signal1<void,std::string> Session::Dialog;
137 PBD::Signal0<int> Session::AskAboutPendingState;
138 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
139 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
140 PBD::Signal0<void> Session::SendFeedback;
141 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
143 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
144 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
145 PBD::Signal2<void,std::string, std::string> Session::Exported;
146 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
147 PBD::Signal0<void> Session::Quit;
148 PBD::Signal0<void> Session::FeedbackDetected;
149 PBD::Signal0<void> Session::SuccessfulGraphSort;
150 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
152 const framecnt_t Session::bounce_chunk_size = 8192;
153 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
154 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
156 // seconds should be added after the region exceeds end marker
157 #ifdef USE_TRACKS_CODE_FEATURES
158 const uint32_t Session::session_end_shift = 5;
160 const uint32_t Session::session_end_shift = 0;
163 /** @param snapshot_name Snapshot name, without .ardour suffix */
164 Session::Session (AudioEngine &eng,
165 const string& fullpath,
166 const string& snapshot_name,
167 BusProfile* bus_profile,
169 : playlists (new SessionPlaylists)
171 , process_function (&Session::process_with_events)
172 , _bounce_processing_active (false)
173 , waiting_for_sync_offset (false)
174 , _base_frame_rate (0)
175 , _nominal_frame_rate (0)
176 , _current_frame_rate (0)
177 , transport_sub_state (0)
178 , _record_status (Disabled)
179 , _transport_frame (0)
180 , _session_range_location (0)
181 , _session_range_end_is_free (true)
184 , _transport_speed (0)
185 , _default_transport_speed (1.0)
186 , _last_transport_speed (0)
187 , _target_transport_speed (0.0)
188 , auto_play_legal (false)
189 , _last_slave_transport_frame (0)
190 , maximum_output_latency (0)
191 , _requested_return_frame (-1)
192 , current_block_size (0)
193 , _worst_output_latency (0)
194 , _worst_input_latency (0)
195 , _worst_track_latency (0)
196 , _have_captured (false)
197 , _non_soloed_outs_muted (false)
200 , _solo_isolated_cnt (0)
202 , _was_seamless (Config->get_seamless_loop ())
203 , _under_nsm_control (false)
205 , delta_accumulator_cnt (0)
206 , average_slave_delta (1800) // !!! why 1800 ???
208 , have_first_delta_accumulator (false)
209 , _slave_state (Stopped)
210 , _mtc_active (false)
211 , _ltc_active (false)
212 , post_export_sync (false)
213 , post_export_position (0)
215 , _export_rolling (false)
216 , _realtime_export (false)
217 , _region_export (false)
218 , _export_preroll (0)
219 , _export_latency (0)
220 , _pre_export_mmc_enabled (false)
221 , _name (snapshot_name)
223 , _send_qf_mtc (false)
224 , _pframes_since_last_mtc (0)
226 , loop_changing (false)
228 , _session_dir (new SessionDirectory (fullpath))
229 , _current_snapshot_name (snapshot_name)
231 , state_was_pending (false)
232 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
234 , _save_queued (false)
235 , _last_roll_location (0)
236 , _last_roll_or_reversal_location (0)
237 , _last_record_location (0)
238 , pending_locate_roll (false)
239 , pending_locate_frame (0)
240 , pending_locate_flush (false)
241 , pending_abort (false)
242 , pending_auto_loop (false)
243 , _mempool ("Session", 3145728)
244 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
246 , _butler (new Butler (*this))
247 , _post_transport_work (0)
248 , cumulative_rf_motion (0)
250 , _locations (new Locations (*this))
251 , _ignore_skips_updates (false)
252 , _rt_thread_active (false)
253 , _rt_emit_pending (false)
254 , _ac_thread_active (0)
255 , _latency_recompute_pending (0)
257 , outbound_mtc_timecode_frame (0)
258 , next_quarter_frame_to_send (-1)
259 , _samples_per_timecode_frame (0)
260 , _frames_per_hour (0)
261 , _timecode_frames_per_hour (0)
262 , last_timecode_valid (false)
263 , last_timecode_when (0)
264 , _send_timecode_update (false)
276 , ltc_timecode_offset (0)
277 , ltc_timecode_negative_offset (false)
278 , midi_control_ui (0)
280 , _all_route_group (new RouteGroup (*this, "all"))
281 , routes (new RouteList)
282 , _adding_routes_in_progress (false)
283 , _reconnecting_routes_in_progress (false)
284 , _route_deletion_in_progress (false)
285 , destructive_index (0)
286 , _track_number_decimals(1)
287 , default_fade_steepness (0)
288 , default_fade_msecs (0)
289 , _total_free_4k_blocks (0)
290 , _total_free_4k_blocks_uncertain (false)
291 , no_questions_about_missing_files (false)
294 , _bundles (new BundleList)
295 , _bundle_xml_node (0)
299 , click_emphasis_data (0)
301 , click_emphasis_length (0)
302 , _clicks_cleared (0)
303 , _count_in_samples (0)
304 , _play_range (false)
305 , _range_selection (-1,-1)
306 , _object_selection (-1,-1)
307 , _preroll_record_punch_pos (-1)
308 , _preroll_record_trim_len (0)
309 , _count_in_once (false)
311 , first_file_data_format_reset (true)
312 , first_file_header_format_reset (true)
313 , have_looped (false)
314 , _have_rec_enabled_track (false)
315 , _have_rec_disabled_track (true)
317 , _suspend_timecode_transmission (0)
318 , _speakers (new Speakers)
319 , _ignore_route_processor_changes (0)
324 , _vca_manager (new VCAManager (*this))
328 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
330 pthread_mutex_init (&_rt_emit_mutex, 0);
331 pthread_cond_init (&_rt_emit_cond, 0);
333 pthread_mutex_init (&_auto_connect_mutex, 0);
334 pthread_cond_init (&_auto_connect_cond, 0);
336 init_name_id_counter (1); // reset for new sessions, start at 1
337 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
339 pre_engine_init (fullpath); // sets _is_new
345 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
347 #ifdef USE_TRACKS_CODE_FEATURES
348 sr = EngineStateController::instance()->get_current_sample_rate();
350 if (ensure_engine (sr, true)) {
352 throw SessionException (_("Cannot connect to audio/midi engine"));
355 // set samplerate for plugins added early
356 // e.g from templates or MB channelstrip
357 set_block_size (_engine.samples_per_cycle());
358 set_frame_rate (_engine.sample_rate());
360 if (create (mix_template, bus_profile)) {
362 throw SessionException (_("Session initialization failed"));
365 /* if a mix template was provided, then ::create() will
366 * have copied it into the session and we need to load it
367 * so that we have the state ready for ::set_state()
368 * after the engine is started.
370 * Note that we do NOT try to get the sample rate from
371 * the template at this time, though doing so would
372 * be easy if we decided this was an appropriate part
376 if (!mix_template.empty()) {
377 if (load_state (_current_snapshot_name)) {
378 throw SessionException (_("Failed to load template/snapshot state"));
380 store_recent_templates (mix_template);
383 /* load default session properties - if any */
388 if (load_state (_current_snapshot_name)) {
389 throw SessionException (_("Failed to load state"));
392 /* try to get sample rate from XML state so that we
393 * can influence the SR if we set up the audio
398 XMLProperty const * prop;
399 XMLNode const * root (state_tree->root());
400 if ((prop = root->property (X_("sample-rate"))) != 0) {
401 sr = atoi (prop->value());
405 if (ensure_engine (sr, false)) {
407 throw SessionException (_("Cannot connect to audio/midi engine"));
411 if (post_engine_init ()) {
413 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
416 store_recent_sessions (_name, _path);
418 bool was_dirty = dirty();
420 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
422 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
424 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
425 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
428 DirtyChanged (); /* EMIT SIGNAL */
431 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
432 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
434 emit_thread_start ();
435 auto_connect_thread_start ();
437 /* hook us up to the engine since we are now completely constructed */
439 BootMessage (_("Connect to engine"));
441 _engine.set_session (this);
442 _engine.reset_timebase ();
444 #ifdef USE_TRACKS_CODE_FEATURES
446 EngineStateController::instance()->set_session(this);
449 if ( ARDOUR::Profile->get_trx () ) {
451 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
452 * each available input must have corresponding track when session starts.
455 uint32_t how_many (0);
457 std::vector<std::string> inputs;
458 EngineStateController::instance()->get_physical_audio_inputs(inputs);
460 how_many = inputs.size();
462 list<boost::shared_ptr<AudioTrack> > tracks;
464 // Track names after driver
465 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
466 string track_name = "";
467 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
469 track_name = inputs[i];
470 replace_all (track_name, "system:capture", "");
472 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
473 tracks.insert(tracks.begin(), single_track.front());
475 } else { // Default track names
476 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
479 if (tracks.size() != how_many) {
481 throw failed_constructor ();
487 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
492 BootMessage (_("Session loading complete"));
504 Session::next_name_id ()
506 return g_atomic_int_add (&_name_id_counter, 1);
510 Session::name_id_counter ()
512 return g_atomic_int_get (&_name_id_counter);
516 Session::init_name_id_counter (guint n)
518 g_atomic_int_set (&_name_id_counter, n);
522 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
524 if (_engine.current_backend() == 0) {
525 /* backend is unknown ... */
526 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
527 if (r.get_value_or (-1) != 0) {
530 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
532 } else if (_engine.setup_required()) {
533 /* backend is known, but setup is needed */
534 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
535 if (r.get_value_or (-1) != 0) {
538 } else if (!_engine.running()) {
539 if (_engine.start()) {
544 /* at this point the engine should be running */
546 if (!_engine.running()) {
550 return immediately_post_engine ();
555 Session::immediately_post_engine ()
557 /* Do various initializations that should take place directly after we
558 * know that the engine is running, but before we either create a
559 * session or set state for an existing one.
562 if (how_many_dsp_threads () > 1) {
563 /* For now, only create the graph if we are using >1 DSP threads, as
564 it is a bit slower than the old code with 1 thread.
566 _process_graph.reset (new Graph (*this));
569 /* every time we reconnect, recompute worst case output latencies */
571 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
573 if (synced_to_engine()) {
574 _engine.transport_stop ();
577 if (config.get_jack_time_master()) {
578 _engine.transport_locate (_transport_frame);
583 BootMessage (_("Set up LTC"));
585 BootMessage (_("Set up Click"));
587 BootMessage (_("Set up standard connections"));
591 catch (failed_constructor& err) {
595 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
597 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
605 vector<void*> debug_pointers;
607 /* if we got to here, leaving pending capture state around
611 remove_pending_capture_state ();
615 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
617 /* disconnect from any and all signals that we are connected to */
619 Port::PortSignalDrop (); /* EMIT SIGNAL */
622 /* shutdown control surface protocols while we still have ports
623 and the engine to move data to any devices.
626 ControlProtocolManager::instance().drop_protocols ();
628 /* stop autoconnecting */
629 auto_connect_thread_terminate ();
631 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
633 _engine.remove_session ();
635 #ifdef USE_TRACKS_CODE_FEATURES
636 EngineStateController::instance()->remove_session();
639 /* deregister all ports - there will be no process or any other
640 * callbacks from the engine any more.
643 Port::PortDrop (); /* EMIT SIGNAL */
647 /* clear history so that no references to objects are held any more */
651 /* clear state tree so that no references to objects are held any more */
656 // unregister all lua functions, drop held references (if any)
658 lua.do_command ("Session = nil");
666 lua.collect_garbage ();
668 /* reset dynamic state version back to default */
669 Stateful::loading_state_version = 0;
671 _butler->drop_references ();
675 delete _all_route_group;
677 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
678 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
682 if (click_data != default_click) {
683 delete [] click_data;
686 if (click_emphasis_data != default_click_emphasis) {
687 delete [] click_emphasis_data;
692 /* need to remove auditioner before monitoring section
693 * otherwise it is re-connected */
696 /* drop references to routes held by the monitoring section
697 * specifically _monitor_out aux/listen references */
698 remove_monitor_section();
700 /* clear out any pending dead wood from RCU managed objects */
705 AudioDiskstream::free_working_buffers();
707 /* tell everyone who is still standing that we're about to die */
710 /* tell everyone to drop references and delete objects as we go */
712 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
713 RegionFactory::delete_all_regions ();
715 /* Do this early so that VCAs no longer hold references to routes */
717 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
720 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
722 /* reset these three references to special routes before we do the usual route delete thing */
724 _master_out.reset ();
725 _monitor_out.reset ();
728 RCUWriter<RouteList> writer (routes);
729 boost::shared_ptr<RouteList> r = writer.get_copy ();
731 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
732 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
733 (*i)->drop_references ();
737 /* writer goes out of scope and updates master */
742 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
743 Glib::Threads::Mutex::Lock lm (source_lock);
744 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
745 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
746 i->second->drop_references ();
752 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
755 emit_thread_terminate ();
757 pthread_cond_destroy (&_rt_emit_cond);
758 pthread_mutex_destroy (&_rt_emit_mutex);
760 pthread_cond_destroy (&_auto_connect_cond);
761 pthread_mutex_destroy (&_auto_connect_mutex);
763 delete _scene_changer; _scene_changer = 0;
764 delete midi_control_ui; midi_control_ui = 0;
766 delete _mmc; _mmc = 0;
767 delete _midi_ports; _midi_ports = 0;
768 delete _locations; _locations = 0;
773 /* clear event queue, the session is gone, nobody is interested in
774 * those anymore, but they do leak memory if not removed
776 while (!immediate_events.empty ()) {
777 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
778 SessionEvent *ev = immediate_events.front ();
779 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
780 immediate_events.pop_front ();
784 case SessionEvent::AutoLoop:
785 case SessionEvent::AutoLoopDeclick:
786 case SessionEvent::Skip:
787 case SessionEvent::PunchIn:
788 case SessionEvent::PunchOut:
789 case SessionEvent::RecordStart:
790 case SessionEvent::StopOnce:
791 case SessionEvent::RangeStop:
792 case SessionEvent::RangeLocate:
796 case SessionEvent::RealTimeOperation:
803 del = del && !_remove_event (ev);
810 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
812 BOOST_SHOW_POINTERS ();
816 Session::setup_ltc ()
820 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
821 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
823 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
824 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
827 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
828 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
829 // TODO use auto-connect thread somehow (needs a route currently)
830 // see note in Session::auto_connect_thread_run() why process lock is needed.
831 reconnect_ltc_input ();
835 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
836 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
839 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
840 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
841 // TODO use auto-connect thread
842 reconnect_ltc_output ();
846 /* fix up names of LTC ports because we don't want the normal
847 * IO style of NAME/TYPE-{in,out}N
850 _ltc_input->nth (0)->set_name (X_("LTC-in"));
851 _ltc_output->nth (0)->set_name (X_("LTC-out"));
855 Session::setup_click ()
859 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
860 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
862 _click_io.reset (new ClickIO (*this, X_("Click")));
863 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
864 _click_gain->activate ();
866 setup_click_state (state_tree->root());
868 setup_click_state (0);
873 Session::setup_click_state (const XMLNode* node)
875 const XMLNode* child = 0;
877 if (node && (child = find_named_node (*node, "Click")) != 0) {
879 /* existing state for Click */
882 if (Stateful::loading_state_version < 3000) {
883 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
885 const XMLNodeList& children (child->children());
886 XMLNodeList::const_iterator i = children.begin();
887 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
889 if (i != children.end()) {
890 c = _click_gain->set_state (**i, Stateful::loading_state_version);
896 _clicking = Config->get_clicking ();
900 error << _("could not setup Click I/O") << endmsg;
907 /* default state for Click: dual-mono to first 2 physical outputs */
910 _engine.get_physical_outputs (DataType::AUDIO, outs);
912 for (uint32_t physport = 0; physport < 2; ++physport) {
913 if (outs.size() > physport) {
914 if (_click_io->add_port (outs[physport], this)) {
915 // relax, even though its an error
920 if (_click_io->n_ports () > ChanCount::ZERO) {
921 _clicking = Config->get_clicking ();
927 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
928 MidiPortFlags include, MidiPortFlags exclude)
930 _engine.get_physical_inputs (type, inputs, include, exclude);
931 _engine.get_physical_outputs (type, outputs, include, exclude);
935 Session::setup_bundles ()
939 RCUWriter<BundleList> writer (_bundles);
940 boost::shared_ptr<BundleList> b = writer.get_copy ();
941 for (BundleList::iterator i = b->begin(); i != b->end();) {
942 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
950 vector<string> inputs[DataType::num_types];
951 vector<string> outputs[DataType::num_types];
953 for (uint32_t i = 0; i < DataType::num_types; ++i) {
954 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
955 MidiPortFlags (0), /* no specific inclusions */
956 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
960 /* Create a set of Bundle objects that map
961 to the physical I/O currently available. We create both
962 mono and stereo bundles, so that the common cases of mono
963 and stereo tracks get bundles to put in their mixer strip
964 in / out menus. There may be a nicer way of achieving that;
965 it doesn't really scale that well to higher channel counts
968 /* mono output bundles */
970 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
972 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
974 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
976 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
979 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
980 c->add_channel (_("mono"), DataType::AUDIO);
981 c->set_port (0, outputs[DataType::AUDIO][np]);
983 add_bundle (c, false);
986 /* stereo output bundles */
988 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
989 if (np + 1 < outputs[DataType::AUDIO].size()) {
991 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
992 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
993 c->add_channel (_("L"), DataType::AUDIO);
994 c->set_port (0, outputs[DataType::AUDIO][np]);
995 c->add_channel (_("R"), DataType::AUDIO);
996 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
998 add_bundle (c, false);
1002 /* mono input bundles */
1004 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1006 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1008 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1010 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1013 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1014 c->add_channel (_("mono"), DataType::AUDIO);
1015 c->set_port (0, inputs[DataType::AUDIO][np]);
1017 add_bundle (c, false);
1020 /* stereo input bundles */
1022 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1023 if (np + 1 < inputs[DataType::AUDIO].size()) {
1025 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1027 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1028 c->add_channel (_("L"), DataType::AUDIO);
1029 c->set_port (0, inputs[DataType::AUDIO][np]);
1030 c->add_channel (_("R"), DataType::AUDIO);
1031 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1033 add_bundle (c, false);
1037 /* MIDI input bundles */
1039 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1040 string n = inputs[DataType::MIDI][np];
1042 std::string pn = _engine.get_pretty_name_by_name (n);
1046 boost::erase_first (n, X_("alsa_pcm:"));
1048 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1049 c->add_channel ("", DataType::MIDI);
1050 c->set_port (0, inputs[DataType::MIDI][np]);
1051 add_bundle (c, false);
1054 /* MIDI output bundles */
1056 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1057 string n = outputs[DataType::MIDI][np];
1058 std::string pn = _engine.get_pretty_name_by_name (n);
1062 boost::erase_first (n, X_("alsa_pcm:"));
1064 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1065 c->add_channel ("", DataType::MIDI);
1066 c->set_port (0, outputs[DataType::MIDI][np]);
1067 add_bundle (c, false);
1070 // we trust the backend to only calls us if there's a change
1071 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1075 Session::auto_connect_master_bus ()
1077 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1081 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1082 // In this case it means "Multi Out" output mode
1083 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1087 /* if requested auto-connect the outputs to the first N physical ports.
1090 uint32_t limit = _master_out->n_outputs().n_total();
1091 vector<string> outputs[DataType::num_types];
1093 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1094 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1097 for (uint32_t n = 0; n < limit; ++n) {
1098 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1100 if (outputs[p->type()].size() > n) {
1101 connect_to = outputs[p->type()][n];
1104 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1105 if (_master_out->output()->connect (p, connect_to, this)) {
1106 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1115 Session::remove_monitor_section ()
1117 if (!_monitor_out || Profile->get_trx()) {
1121 /* force reversion to Solo-In-Place */
1122 Config->set_solo_control_is_listen_control (false);
1124 /* if we are auditioning, cancel it ... this is a workaround
1125 to a problem (auditioning does not execute the process graph,
1126 which is needed to remove routes when using >1 core for processing)
1131 /* Hold process lock while doing this so that we don't hear bits and
1132 * pieces of audio as we work on each route.
1135 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1137 /* Connect tracks to monitor section. Note that in an
1138 existing session, the internal sends will already exist, but we want the
1139 routes to notice that they connect to the control out specifically.
1143 boost::shared_ptr<RouteList> r = routes.reader ();
1144 ProcessorChangeBlocker pcb (this, false);
1146 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1148 if ((*x)->is_monitor()) {
1150 } else if ((*x)->is_master()) {
1153 (*x)->remove_aux_or_listen (_monitor_out);
1158 remove_route (_monitor_out);
1159 if (_state_of_the_state & Deletion) {
1163 auto_connect_master_bus ();
1166 auditioner->connect ();
1169 Config->ParameterChanged ("use-monitor-bus");
1173 Session::add_monitor_section ()
1177 if (_monitor_out || !_master_out || Profile->get_trx()) {
1181 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1187 BOOST_MARK_ROUTE(r);
1190 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1191 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1192 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1194 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1199 add_routes (rl, false, false, false, 0);
1201 assert (_monitor_out);
1203 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1204 are undefined, at best.
1207 uint32_t limit = _monitor_out->n_inputs().n_audio();
1211 /* connect the inputs to the master bus outputs. this
1212 * represents a separate data feed from the internal sends from
1213 * each route. as of jan 2011, it allows the monitor section to
1214 * conditionally ignore either the internal sends or the normal
1215 * input feed, but we should really find a better way to do
1219 _master_out->output()->disconnect (this);
1221 for (uint32_t n = 0; n < limit; ++n) {
1222 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1223 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1226 string connect_to = o->name();
1227 if (_monitor_out->input()->connect (p, connect_to, this)) {
1228 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1236 /* if monitor section is not connected, connect it to physical outs
1239 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1241 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1243 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1246 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1248 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1249 Config->get_monitor_bus_preferred_bundle())
1255 /* Monitor bus is audio only */
1257 vector<string> outputs[DataType::num_types];
1259 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1260 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1263 uint32_t mod = outputs[DataType::AUDIO].size();
1264 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1268 for (uint32_t n = 0; n < limit; ++n) {
1270 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1272 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1273 connect_to = outputs[DataType::AUDIO][n % mod];
1276 if (!connect_to.empty()) {
1277 if (_monitor_out->output()->connect (p, connect_to, this)) {
1278 error << string_compose (
1279 _("cannot connect control output %1 to %2"),
1290 /* Hold process lock while doing this so that we don't hear bits and
1291 * pieces of audio as we work on each route.
1294 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1296 /* Connect tracks to monitor section. Note that in an
1297 existing session, the internal sends will already exist, but we want the
1298 routes to notice that they connect to the control out specifically.
1302 boost::shared_ptr<RouteList> rls = routes.reader ();
1304 ProcessorChangeBlocker pcb (this, false /* XXX */);
1306 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1308 if ((*x)->is_monitor()) {
1310 } else if ((*x)->is_master()) {
1313 (*x)->enable_monitor_send ();
1318 auditioner->connect ();
1320 Config->ParameterChanged ("use-monitor-bus");
1324 Session::reset_monitor_section ()
1326 /* Process lock should be held by the caller.*/
1328 if (!_monitor_out || Profile->get_trx()) {
1332 uint32_t limit = _master_out->n_outputs().n_audio();
1334 /* connect the inputs to the master bus outputs. this
1335 * represents a separate data feed from the internal sends from
1336 * each route. as of jan 2011, it allows the monitor section to
1337 * conditionally ignore either the internal sends or the normal
1338 * input feed, but we should really find a better way to do
1342 _master_out->output()->disconnect (this);
1343 _monitor_out->output()->disconnect (this);
1345 // monitor section follow master bus - except midi
1346 ChanCount mon_chn (_master_out->output()->n_ports());
1347 mon_chn.set_midi (0);
1349 _monitor_out->input()->ensure_io (mon_chn, false, this);
1350 _monitor_out->output()->ensure_io (mon_chn, false, this);
1352 for (uint32_t n = 0; n < limit; ++n) {
1353 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1354 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1357 string connect_to = o->name();
1358 if (_monitor_out->input()->connect (p, connect_to, this)) {
1359 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1366 /* connect monitor section to physical outs
1369 if (Config->get_auto_connect_standard_busses()) {
1371 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1373 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1376 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1378 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1379 Config->get_monitor_bus_preferred_bundle())
1385 /* Monitor bus is audio only */
1387 vector<string> outputs[DataType::num_types];
1389 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1390 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1393 uint32_t mod = outputs[DataType::AUDIO].size();
1394 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1398 for (uint32_t n = 0; n < limit; ++n) {
1400 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1402 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1403 connect_to = outputs[DataType::AUDIO][n % mod];
1406 if (!connect_to.empty()) {
1407 if (_monitor_out->output()->connect (p, connect_to, this)) {
1408 error << string_compose (
1409 _("cannot connect control output %1 to %2"),
1420 /* Connect tracks to monitor section. Note that in an
1421 existing session, the internal sends will already exist, but we want the
1422 routes to notice that they connect to the control out specifically.
1426 boost::shared_ptr<RouteList> rls = routes.reader ();
1428 ProcessorChangeBlocker pcb (this, false);
1430 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1432 if ((*x)->is_monitor()) {
1434 } else if ((*x)->is_master()) {
1437 (*x)->enable_monitor_send ();
1443 Session::hookup_io ()
1445 /* stop graph reordering notifications from
1446 causing resorts, etc.
1449 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1453 /* we delay creating the auditioner till now because
1454 it makes its own connections to ports.
1458 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1460 throw failed_constructor ();
1462 a->use_new_diskstream ();
1466 catch (failed_constructor& err) {
1467 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1471 /* load bundles, which we may have postponed earlier on */
1472 if (_bundle_xml_node) {
1473 load_bundles (*_bundle_xml_node);
1474 delete _bundle_xml_node;
1477 /* Tell all IO objects to connect themselves together */
1479 IO::enable_connecting ();
1481 /* Now tell all "floating" ports to connect to whatever
1482 they should be connected to.
1485 AudioEngine::instance()->reconnect_ports ();
1487 /* Anyone who cares about input state, wake up and do something */
1489 IOConnectionsComplete (); /* EMIT SIGNAL */
1491 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1493 /* now handle the whole enchilada as if it was one
1494 graph reorder event.
1499 /* update the full solo state, which can't be
1500 correctly determined on a per-route basis, but
1501 needs the global overview that only the session
1505 update_route_solo_state ();
1509 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1511 boost::shared_ptr<Track> track = wp.lock ();
1516 boost::shared_ptr<Playlist> playlist;
1518 if ((playlist = track->playlist()) != 0) {
1519 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1520 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1521 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1526 Session::record_enabling_legal () const
1528 /* this used to be in here, but survey says.... we don't need to restrict it */
1529 // if (record_status() == Recording) {
1533 if (Config->get_all_safe()) {
1540 Session::set_track_monitor_input_status (bool yn)
1542 boost::shared_ptr<RouteList> rl = routes.reader ();
1543 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1544 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1545 if (tr && tr->rec_enable_control()->get_value()) {
1546 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1547 tr->request_input_monitoring (yn);
1553 Session::auto_punch_start_changed (Location* location)
1555 replace_event (SessionEvent::PunchIn, location->start());
1557 if (get_record_enabled() && config.get_punch_in()) {
1558 /* capture start has been changed, so save new pending state */
1559 save_state ("", true);
1564 Session::auto_punch_end_changed (Location* location)
1566 framepos_t when_to_stop = location->end();
1567 // when_to_stop += _worst_output_latency + _worst_input_latency;
1568 replace_event (SessionEvent::PunchOut, when_to_stop);
1572 Session::auto_punch_changed (Location* location)
1574 framepos_t when_to_stop = location->end();
1576 replace_event (SessionEvent::PunchIn, location->start());
1577 //when_to_stop += _worst_output_latency + _worst_input_latency;
1578 replace_event (SessionEvent::PunchOut, when_to_stop);
1581 /** @param loc A loop location.
1582 * @param pos Filled in with the start time of the required fade-out (in session frames).
1583 * @param length Filled in with the length of the required fade-out.
1586 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1588 pos = max (loc->start(), loc->end() - 64);
1589 length = loc->end() - pos;
1593 Session::auto_loop_changed (Location* location)
1595 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1598 auto_loop_declick_range (location, dcp, dcl);
1600 if (transport_rolling() && play_loop) {
1602 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1604 // if (_transport_frame > location->end()) {
1606 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1607 // relocate to beginning of loop
1608 clear_events (SessionEvent::LocateRoll);
1610 request_locate (location->start(), true);
1613 else if (Config->get_seamless_loop() && !loop_changing) {
1615 // schedule a locate-roll to refill the diskstreams at the
1616 // previous loop end
1617 loop_changing = true;
1619 if (location->end() > last_loopend) {
1620 clear_events (SessionEvent::LocateRoll);
1621 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1627 clear_events (SessionEvent::AutoLoopDeclick);
1628 clear_events (SessionEvent::AutoLoop);
1631 /* possibly move playhead if not rolling; if we are rolling we'll move
1632 to the loop start on stop if that is appropriate.
1637 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1638 if (pos == location->start()) {
1639 request_locate (pos);
1644 last_loopend = location->end();
1649 Session::set_auto_punch_location (Location* location)
1653 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1654 punch_connections.drop_connections();
1655 existing->set_auto_punch (false, this);
1656 remove_event (existing->start(), SessionEvent::PunchIn);
1657 clear_events (SessionEvent::PunchOut);
1658 auto_punch_location_changed (0);
1663 if (location == 0) {
1667 if (location->end() <= location->start()) {
1668 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1672 punch_connections.drop_connections ();
1674 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1675 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1676 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1678 location->set_auto_punch (true, this);
1680 auto_punch_changed (location);
1682 auto_punch_location_changed (location);
1686 Session::set_session_extents (framepos_t start, framepos_t end)
1689 if ((existing = _locations->session_range_location()) == 0) {
1690 //if there is no existing session, we need to make a new session location (should never happen)
1691 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1695 error << _("Session: you can't use that location for session start/end)") << endmsg;
1699 existing->set( start, end );
1705 Session::set_auto_loop_location (Location* location)
1709 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1710 loop_connections.drop_connections ();
1711 existing->set_auto_loop (false, this);
1712 remove_event (existing->end(), SessionEvent::AutoLoop);
1715 auto_loop_declick_range (existing, dcp, dcl);
1716 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1717 auto_loop_location_changed (0);
1722 if (location == 0) {
1726 if (location->end() <= location->start()) {
1727 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1731 last_loopend = location->end();
1733 loop_connections.drop_connections ();
1735 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1736 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1737 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1738 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1740 location->set_auto_loop (true, this);
1742 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1743 // set all tracks to use internal looping
1744 boost::shared_ptr<RouteList> rl = routes.reader ();
1745 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1746 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1747 if (tr && !tr->hidden()) {
1748 tr->set_loop (location);
1753 /* take care of our stuff first */
1755 auto_loop_changed (location);
1757 /* now tell everyone else */
1759 auto_loop_location_changed (location);
1763 Session::update_marks (Location*)
1769 Session::update_skips (Location* loc, bool consolidate)
1771 if (_ignore_skips_updates) {
1775 Locations::LocationList skips;
1778 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1779 consolidate_skips (loc);
1782 sync_locations_to_skips ();
1788 Session::consolidate_skips (Location* loc)
1790 Locations::LocationList all_locations = _locations->list ();
1792 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1794 if (!(*l)->is_skip ()) {
1799 /* don't test against self */
1806 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1807 case Evoral::OverlapInternal:
1808 case Evoral::OverlapExternal:
1809 case Evoral::OverlapStart:
1810 case Evoral::OverlapEnd:
1811 /* adjust new location to cover existing one */
1812 loc->set_start (min (loc->start(), (*l)->start()));
1813 loc->set_end (max (loc->end(), (*l)->end()));
1814 /* we don't need this one any more */
1815 _locations->remove (*l);
1816 /* the location has been deleted, so remove reference to it in our local list */
1817 l = all_locations.erase (l);
1820 case Evoral::OverlapNone:
1828 Session::sync_locations_to_skips ()
1830 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1831 * Session::_sync_locations_to_skips() from the audioengine thread.
1833 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1837 Session::_sync_locations_to_skips ()
1839 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1841 Locations::LocationList const & locs (_locations->list());
1843 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1845 Location* location = *i;
1847 if (location->is_skip() && location->is_skipping()) {
1848 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1856 Session::location_added (Location *location)
1858 if (location->is_auto_punch()) {
1859 set_auto_punch_location (location);
1862 if (location->is_auto_loop()) {
1863 set_auto_loop_location (location);
1866 if (location->is_session_range()) {
1867 /* no need for any signal handling or event setting with the session range,
1868 because we keep a direct reference to it and use its start/end directly.
1870 _session_range_location = location;
1873 if (location->is_mark()) {
1874 /* listen for per-location signals that require us to do any * global updates for marks */
1876 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1877 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1878 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1879 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1880 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1883 if (location->is_range_marker()) {
1884 /* listen for per-location signals that require us to do any * global updates for marks */
1886 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1887 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1888 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1889 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1890 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1893 if (location->is_skip()) {
1894 /* listen for per-location signals that require us to update skip-locate events */
1896 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1897 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1898 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1899 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1900 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1902 update_skips (location, true);
1909 Session::location_removed (Location *location)
1911 if (location->is_auto_loop()) {
1912 set_auto_loop_location (0);
1913 set_track_loop (false);
1916 if (location->is_auto_punch()) {
1917 set_auto_punch_location (0);
1920 if (location->is_session_range()) {
1921 /* this is never supposed to happen */
1922 error << _("programming error: session range removed!") << endl;
1925 if (location->is_skip()) {
1927 update_skips (location, false);
1934 Session::locations_changed ()
1936 _locations->apply (*this, &Session::_locations_changed);
1940 Session::_locations_changed (const Locations::LocationList& locations)
1942 /* There was some mass-change in the Locations object.
1944 We might be re-adding a location here but it doesn't actually matter
1945 for all the locations that the Session takes an interest in.
1949 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1950 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1951 location_added (*i);
1955 update_skips (NULL, false);
1959 Session::enable_record ()
1961 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1962 /* no recording at anything except normal speed */
1967 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1969 if (rs == Recording) {
1973 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1975 _last_record_location = _transport_frame;
1976 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1978 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1979 set_track_monitor_input_status (true);
1982 RecordStateChanged ();
1989 Session::set_all_tracks_record_enabled (bool enable )
1991 boost::shared_ptr<RouteList> rl = routes.reader();
1992 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1996 Session::disable_record (bool rt_context, bool force)
2000 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2002 if (!Config->get_latched_record_enable () || force) {
2003 g_atomic_int_set (&_record_status, Disabled);
2004 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2006 if (rs == Recording) {
2007 g_atomic_int_set (&_record_status, Enabled);
2011 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2012 set_track_monitor_input_status (false);
2015 RecordStateChanged (); /* emit signal */
2018 remove_pending_capture_state ();
2020 unset_preroll_record_punch ();
2025 Session::step_back_from_record ()
2027 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2029 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2030 set_track_monitor_input_status (false);
2033 RecordStateChanged (); /* emit signal */
2038 Session::maybe_enable_record (bool rt_context)
2040 if (_step_editors > 0) {
2044 g_atomic_int_set (&_record_status, Enabled);
2046 /* This function is currently called from somewhere other than an RT thread.
2047 * (except maybe lua scripts, which can use rt_context = true)
2048 * This save_state() call therefore doesn't impact anything. Doing it here
2049 * means that we save pending state of which sources the next record will use,
2050 * which gives us some chance of recovering from a crash during the record.
2054 save_state ("", true);
2057 if (_transport_speed) {
2058 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2062 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2063 RecordStateChanged (); /* EMIT SIGNAL */
2070 Session::audible_frame (bool* latent_locate) const
2074 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2075 offset *= transport_speed ();
2076 if (latent_locate) {
2077 *latent_locate = false;
2080 if (synced_to_engine()) {
2081 /* Note: this is basically just sync-to-JACK */
2082 ret = _engine.transport_frame();
2084 ret = _transport_frame;
2087 if (transport_rolling()) {
2090 /* Check to see if we have passed the first guaranteed
2091 * audible frame past our last start position. if not,
2092 * return that last start point because in terms
2093 * of audible frames, we have not moved yet.
2095 * `Start position' in this context means the time we last
2096 * either started, located, or changed transport direction.
2099 if (_transport_speed > 0.0f) {
2101 if (!play_loop || !have_looped) {
2102 if (ret < _last_roll_or_reversal_location) {
2103 if (latent_locate) {
2104 *latent_locate = true;
2106 return _last_roll_or_reversal_location;
2109 /* the play-position wrapped at the loop-point
2110 * ardour is already playing the beginning of the loop,
2111 * but due to playback latency, the "audible frame"
2112 * is still at the end of the loop.
2114 Location *location = _locations->auto_loop_location();
2115 frameoffset_t lo = location->start() - ret;
2117 ret = location->end () - lo;
2118 if (latent_locate) {
2119 *latent_locate = true;
2124 } else if (_transport_speed < 0.0f) {
2126 /* XXX wot? no backward looping? */
2128 if (ret > _last_roll_or_reversal_location) {
2129 return _last_roll_or_reversal_location;
2134 return std::max ((framepos_t)0, ret);
2139 Session::preroll_samples (framepos_t pos) const
2141 const float pr = Config->get_preroll_seconds();
2142 if (pos >= 0 && pr < 0) {
2143 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2144 const Meter& meter = _tempo_map->meter_at_frame (pos);
2145 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2150 return pr * frame_rate();
2154 Session::set_frame_rate (framecnt_t frames_per_second)
2156 /** \fn void Session::set_frame_size(framecnt_t)
2157 the AudioEngine object that calls this guarantees
2158 that it will not be called while we are also in
2159 ::process(). Its fine to do things that block
2163 if (_base_frame_rate == 0) {
2164 _base_frame_rate = frames_per_second;
2166 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2167 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2169 _nominal_frame_rate = frames_per_second;
2174 reset_write_sources (false);
2176 // XXX we need some equivalent to this, somehow
2177 // SndFileSource::setup_standard_crossfades (frames_per_second);
2181 /* XXX need to reset/reinstantiate all LADSPA plugins */
2185 Session::set_block_size (pframes_t nframes)
2187 /* the AudioEngine guarantees
2188 that it will not be called while we are also in
2189 ::process(). It is therefore fine to do things that block
2194 current_block_size = nframes;
2198 boost::shared_ptr<RouteList> r = routes.reader ();
2200 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2201 (*i)->set_block_size (nframes);
2204 boost::shared_ptr<RouteList> rl = routes.reader ();
2205 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2206 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2208 tr->set_block_size (nframes);
2212 set_worst_io_latencies ();
2218 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2220 boost::shared_ptr<Route> r2;
2222 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2223 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2227 /* make a copy of the existing list of routes that feed r1 */
2229 Route::FedBy existing (r1->fed_by());
2231 /* for each route that feeds r1, recurse, marking it as feeding
2235 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2236 if (!(r2 = i->r.lock ())) {
2237 /* (*i) went away, ignore it */
2241 /* r2 is a route that feeds r1 which somehow feeds base. mark
2242 base as being fed by r2
2245 rbase->add_fed_by (r2, i->sends_only);
2249 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2253 if (r1->feeds (r2) && r2->feeds (r1)) {
2257 /* now recurse, so that we can mark base as being fed by
2258 all routes that feed r2
2261 trace_terminal (r2, rbase);
2268 Session::resort_routes ()
2270 /* don't do anything here with signals emitted
2271 by Routes during initial setup or while we
2272 are being destroyed.
2275 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2279 if (_route_deletion_in_progress) {
2284 RCUWriter<RouteList> writer (routes);
2285 boost::shared_ptr<RouteList> r = writer.get_copy ();
2286 resort_routes_using (r);
2287 /* writer goes out of scope and forces update */
2291 if (DEBUG_ENABLED(DEBUG::Graph)) {
2292 boost::shared_ptr<RouteList> rl = routes.reader ();
2293 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2294 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2296 const Route::FedBy& fb ((*i)->fed_by());
2298 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2299 boost::shared_ptr<Route> sf = f->r.lock();
2301 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2310 /** This is called whenever we need to rebuild the graph of how we will process
2312 * @param r List of routes, in any order.
2316 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2318 /* We are going to build a directed graph of our routes;
2319 this is where the edges of that graph are put.
2324 /* Go through all routes doing two things:
2326 * 1. Collect the edges of the route graph. Each of these edges
2327 * is a pair of routes, one of which directly feeds the other
2328 * either by a JACK connection or by an internal send.
2330 * 2. Begin the process of making routes aware of which other
2331 * routes directly or indirectly feed them. This information
2332 * is used by the solo code.
2335 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2337 /* Clear out the route's list of direct or indirect feeds */
2338 (*i)->clear_fed_by ();
2340 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2342 bool via_sends_only;
2344 /* See if this *j feeds *i according to the current state of the JACK
2345 connections and internal sends.
2347 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2348 /* add the edge to the graph (part #1) */
2349 edges.add (*j, *i, via_sends_only);
2350 /* tell the route (for part #2) */
2351 (*i)->add_fed_by (*j, via_sends_only);
2356 /* Attempt a topological sort of the route graph */
2357 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2359 if (sorted_routes) {
2360 /* We got a satisfactory topological sort, so there is no feedback;
2363 Note: the process graph rechain does not require a
2364 topologically-sorted list, but hey ho.
2366 if (_process_graph) {
2367 _process_graph->rechain (sorted_routes, edges);
2370 _current_route_graph = edges;
2372 /* Complete the building of the routes' lists of what directly
2373 or indirectly feeds them.
2375 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2376 trace_terminal (*i, *i);
2379 *r = *sorted_routes;
2382 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2383 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2384 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2388 SuccessfulGraphSort (); /* EMIT SIGNAL */
2391 /* The topological sort failed, so we have a problem. Tell everyone
2392 and stick to the old graph; this will continue to be processed, so
2393 until the feedback is fixed, what is played back will not quite
2394 reflect what is actually connected. Note also that we do not
2395 do trace_terminal here, as it would fail due to an endless recursion,
2396 so the solo code will think that everything is still connected
2400 FeedbackDetected (); /* EMIT SIGNAL */
2405 /** Find a route name starting with \a base, maybe followed by the
2406 * lowest \a id. \a id will always be added if \a definitely_add_number
2407 * is true on entry; otherwise it will only be added if required
2408 * to make the name unique.
2410 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2411 * The available route name with the lowest ID will be used, and \a id
2412 * will be set to the ID.
2414 * \return false if a route name could not be found, and \a track_name
2415 * and \a id do not reflect a free route name.
2418 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2420 /* the base may conflict with ports that do not belong to existing
2421 routes, but hidden objects like the click track. So check port names
2422 before anything else.
2425 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2426 if (base == reserved->first) {
2427 /* Check if this reserved name already exists, and if
2428 so, disallow it without a numeric suffix.
2430 if (!reserved->second || route_by_name (reserved->first)) {
2431 definitely_add_number = true;
2440 /* if we have "base 1" already, it doesn't make sense to add "base"
2441 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2443 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2444 /* just use the base */
2450 name = string_compose ("%1 %2", base, id);
2452 if (route_by_name (name) == 0) {
2458 } while (id < (UINT_MAX-1));
2463 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2465 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2467 in = ChanCount::ZERO;
2468 out = ChanCount::ZERO;
2470 boost::shared_ptr<RouteList> r = routes.reader ();
2472 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2473 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2474 if (tr && !tr->is_auditioner()) {
2475 in += tr->n_inputs();
2476 out += tr->n_outputs();
2482 Session::default_track_name_pattern (DataType t)
2485 case DataType::AUDIO:
2486 if (Profile->get_trx()) {
2493 case DataType::MIDI:
2500 /** Caller must not hold process lock
2501 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2502 * @param instrument plugin info for the instrument to insert pre-fader, if any
2504 list<boost::shared_ptr<MidiTrack> >
2505 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2506 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2507 RouteGroup* route_group, uint32_t how_many,
2508 string name_template, PresentationInfo::order_t order,
2512 uint32_t track_id = 0;
2514 RouteList new_routes;
2515 list<boost::shared_ptr<MidiTrack> > ret;
2517 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2518 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2521 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2522 error << "cannot find name for new midi track" << endmsg;
2526 boost::shared_ptr<MidiTrack> track;
2529 track.reset (new MidiTrack (*this, track_name, mode));
2531 if (track->init ()) {
2536 track->set_strict_io (true);
2539 track->use_new_diskstream();
2541 BOOST_MARK_TRACK (track);
2544 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2545 if (track->input()->ensure_io (input, false, this)) {
2546 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2550 if (track->output()->ensure_io (output, false, this)) {
2551 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2556 track->non_realtime_input_change();
2559 route_group->add (track);
2562 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2564 new_routes.push_back (track);
2565 ret.push_back (track);
2568 catch (failed_constructor &err) {
2569 error << _("Session: could not create new midi track.") << endmsg;
2573 catch (AudioEngine::PortRegistrationFailure& pfe) {
2575 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;
2583 if (!new_routes.empty()) {
2584 StateProtector sp (this);
2585 if (Profile->get_trx()) {
2586 add_routes (new_routes, false, false, false, order);
2588 add_routes (new_routes, true, true, false, order);
2592 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2593 PluginPtr plugin = instrument->load (*this);
2595 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2599 plugin->load_preset (*pset);
2601 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2603 pi->set_strict_io (true);
2606 (*r)->add_processor (pi, PreFader);
2608 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2609 (*r)->move_instrument_down (false);
2619 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2620 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2621 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2624 uint32_t bus_id = 0;
2628 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2631 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2632 error << "cannot find name for new midi bus" << endmsg;
2637 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2644 bus->set_strict_io (true);
2647 BOOST_MARK_ROUTE(bus);
2650 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2652 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2653 error << _("cannot configure new midi bus input") << endmsg;
2658 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2659 error << _("cannot configure new midi bus output") << endmsg;
2665 route_group->add (bus);
2668 bus->add_internal_return ();
2669 ret.push_back (bus);
2672 catch (failed_constructor &err) {
2673 error << _("Session: could not create new audio route.") << endmsg;
2677 catch (AudioEngine::PortRegistrationFailure& pfe) {
2678 error << pfe.what() << endmsg;
2688 StateProtector sp (this);
2689 add_routes (ret, false, false, false, order);
2692 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2693 PluginPtr plugin = instrument->load (*this);
2695 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2699 plugin->load_preset (*pset);
2701 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2703 pi->set_strict_io (true);
2706 (*r)->add_processor (pi, PreFader);
2708 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2709 (*r)->move_instrument_down (false);
2721 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2723 boost::shared_ptr<Route> midi_track (wmt.lock());
2729 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2731 if (change.after.n_audio() <= change.before.n_audio()) {
2735 /* new audio ports: make sure the audio goes somewhere useful,
2736 * unless the user has no-auto-connect selected.
2738 * The existing ChanCounts don't matter for this call as they are only
2739 * to do with matching input and output indices, and we are only changing
2742 auto_connect_route (midi_track, false, ChanCount(), change.before);
2746 #ifdef USE_TRACKS_CODE_FEATURES
2749 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2751 return route1->remote_control_id() < route2->remote_control_id();
2755 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2757 // it is not allowed to perform connection
2758 if (!IO::connecting_legal) {
2762 // if we are deleting routes we will call this once at the end
2763 if (_route_deletion_in_progress) {
2767 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2773 // We need to disconnect the route's inputs and outputs first
2774 // basing on autoconnect configuration
2775 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2776 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2778 ChanCount existing_inputs;
2779 ChanCount existing_outputs;
2780 count_existing_track_channels (existing_inputs, existing_outputs);
2782 //ChanCount inputs = ChanCount::ZERO;
2783 //ChanCount outputs = ChanCount::ZERO;
2785 RouteList existing_routes = *routes.reader ();
2786 existing_routes.sort (compare_routes_by_remote_id);
2789 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2791 vector<string> physinputs;
2792 vector<string> physoutputs;
2794 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2795 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2797 uint32_t input_n = 0;
2798 uint32_t output_n = 0;
2799 RouteList::iterator rIter = existing_routes.begin();
2800 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2801 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2802 for (; rIter != existing_routes.end(); ++rIter) {
2803 if (*rIter == _master_out || *rIter == _monitor_out ) {
2807 if (current_output_auto_connection == AutoConnectPhysical) {
2808 (*rIter)->amp()->deactivate();
2809 } else if (current_output_auto_connection == AutoConnectMaster) {
2810 (*rIter)->amp()->activate();
2813 if (reconnectIputs) {
2814 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2816 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2818 if (current_input_auto_connection & AutoConnectPhysical) {
2820 if ( input_n == physinputs.size() ) {
2824 string port = physinputs[input_n];
2826 if (port.empty() ) {
2827 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2830 //GZ: check this; could be heavy
2831 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2837 if (reconnectOutputs) {
2839 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2840 if (current_output_auto_connection & AutoConnectPhysical) {
2842 //GZ: check this; could be heavy
2843 (*rIter)->output()->disconnect (this);
2844 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2846 //GZ: check this; could be heavy
2847 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2849 } else if (current_output_auto_connection & AutoConnectMaster){
2851 if (!reconnect_master) {
2855 //GZ: check this; could be heavy
2856 (*rIter)->output()->disconnect (this);
2859 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2860 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2862 error << error << "Master bus is not available" << endmsg;
2867 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2868 if (current_output_auto_connection & AutoConnectPhysical) {
2870 if ( output_n == physoutputs.size() ) {
2874 string port = physoutputs[output_n];
2876 if (port.empty() ) {
2877 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2880 //GZ: check this; could be heavy
2881 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2884 } else if (current_output_auto_connection & AutoConnectMaster) {
2886 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2890 // connect to master bus
2891 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2893 if (port.empty() ) {
2894 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2898 //GZ: check this; could be heavy
2899 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2906 _master_out->output()->disconnect (this);
2907 auto_connect_master_bus ();
2912 session_routes_reconnected (); /* EMIT SIGNAL */
2916 Session::reconnect_midi_scene_ports(bool inputs)
2920 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2922 scene_in_ptr->disconnect_all ();
2924 std::vector<EngineStateController::MidiPortState> midi_port_states;
2925 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2927 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2929 for (; state_iter != midi_port_states.end(); ++state_iter) {
2930 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2931 scene_in_ptr->connect (state_iter->name);
2938 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2940 if (scene_out_ptr ) {
2941 scene_out_ptr->disconnect_all ();
2943 std::vector<EngineStateController::MidiPortState> midi_port_states;
2944 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2946 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2948 for (; state_iter != midi_port_states.end(); ++state_iter) {
2949 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2950 scene_out_ptr->connect (state_iter->name);
2958 Session::reconnect_mtc_ports ()
2960 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2966 mtc_in_ptr->disconnect_all ();
2968 std::vector<EngineStateController::MidiPortState> midi_port_states;
2969 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2971 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2973 for (; state_iter != midi_port_states.end(); ++state_iter) {
2974 if (state_iter->available && state_iter->mtc_in) {
2975 mtc_in_ptr->connect (state_iter->name);
2979 if (!_midi_ports->mtc_input_port ()->connected () &&
2980 config.get_external_sync () &&
2981 (Config->get_sync_source () == MTC) ) {
2982 config.set_external_sync (false);
2985 if ( ARDOUR::Profile->get_trx () ) {
2986 // Tracks need this signal to update timecode_source_dropdown
2987 MtcOrLtcInputPortChanged (); //emit signal
2992 Session::reconnect_mmc_ports(bool inputs)
2994 if (inputs ) { // get all enabled midi input ports
2996 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2998 mmc_in_ptr->disconnect_all ();
2999 std::vector<std::string> enabled_midi_inputs;
3000 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3002 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3004 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3005 mmc_in_ptr->connect (*port_iter);
3009 } else { // get all enabled midi output ports
3011 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3013 mmc_out_ptr->disconnect_all ();
3014 std::vector<std::string> enabled_midi_outputs;
3015 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3017 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3019 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3020 mmc_out_ptr->connect (*port_iter);
3029 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3031 if (first_new_order == PresentationInfo::max_order) {
3032 /* adding at end, no worries */
3036 /* create a gap in the presentation info to accomodate @param how_many
3040 get_stripables (sl);
3042 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3043 boost::shared_ptr<Stripable> s (*si);
3045 if (s->is_monitor() || s->is_auditioner()) {
3049 if (s->presentation_info().order () >= first_new_order) {
3050 s->set_presentation_order (s->presentation_info().order () + how_many);
3055 /** Caller must not hold process lock
3056 * @param name_template string to use for the start of the name, or "" to use "Audio".
3058 list< boost::shared_ptr<AudioTrack> >
3059 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3060 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3064 uint32_t track_id = 0;
3066 RouteList new_routes;
3067 list<boost::shared_ptr<AudioTrack> > ret;
3069 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3070 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3074 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3075 error << "cannot find name for new audio track" << endmsg;
3079 boost::shared_ptr<AudioTrack> track;
3082 track.reset (new AudioTrack (*this, track_name, mode));
3084 if (track->init ()) {
3088 if (Profile->get_mixbus ()) {
3089 track->set_strict_io (true);
3092 if (ARDOUR::Profile->get_trx ()) {
3093 // TRACKS considers it's not a USE CASE, it's
3094 // a piece of behavior of the session model:
3096 // Gain for a newly created route depends on
3097 // the current output_auto_connect mode:
3099 // 0 for Stereo Out mode
3101 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3102 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3106 track->use_new_diskstream();
3108 BOOST_MARK_TRACK (track);
3111 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3113 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3114 error << string_compose (
3115 _("cannot configure %1 in/%2 out configuration for new audio track"),
3116 input_channels, output_channels)
3121 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3122 error << string_compose (
3123 _("cannot configure %1 in/%2 out configuration for new audio track"),
3124 input_channels, output_channels)
3131 route_group->add (track);
3134 track->non_realtime_input_change();
3136 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3138 new_routes.push_back (track);
3139 ret.push_back (track);
3142 catch (failed_constructor &err) {
3143 error << _("Session: could not create new audio track.") << endmsg;
3147 catch (AudioEngine::PortRegistrationFailure& pfe) {
3149 error << pfe.what() << endmsg;
3157 if (!new_routes.empty()) {
3158 StateProtector sp (this);
3159 if (Profile->get_trx()) {
3160 add_routes (new_routes, false, false, false, order);
3162 add_routes (new_routes, true, true, false, order);
3169 /** Caller must not hold process lock.
3170 * @param name_template string to use for the start of the name, or "" to use "Bus".
3173 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3174 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3177 uint32_t bus_id = 0;
3181 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3184 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3185 error << "cannot find name for new audio bus" << endmsg;
3190 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3196 if (Profile->get_mixbus ()) {
3197 bus->set_strict_io (true);
3200 BOOST_MARK_ROUTE(bus);
3203 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3205 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3206 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3207 input_channels, output_channels)
3213 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3214 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3215 input_channels, output_channels)
3222 route_group->add (bus);
3225 bus->add_internal_return ();
3226 ret.push_back (bus);
3229 catch (failed_constructor &err) {
3230 error << _("Session: could not create new audio route.") << endmsg;
3234 catch (AudioEngine::PortRegistrationFailure& pfe) {
3235 error << pfe.what() << endmsg;
3245 StateProtector sp (this);
3246 if (Profile->get_trx()) {
3247 add_routes (ret, false, false, false, order);
3249 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3258 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3259 PlaylistDisposition pd)
3263 if (!tree.read (template_path.c_str())) {
3267 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3271 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3274 uint32_t number = 0;
3275 const uint32_t being_added = how_many;
3276 /* This will prevent the use of any existing XML-provided PBD::ID
3279 Stateful::ForceIDRegeneration force_ids;
3280 IO::disable_connecting ();
3284 /* We're going to modify the node contents a bit so take a
3285 * copy. The node may be re-used when duplicating more than once.
3288 XMLNode node_copy (node);
3293 if (!name_base.empty()) {
3295 /* if we're adding more than one routes, force
3296 * all the names of the new routes to be
3297 * numbered, via the final parameter.
3300 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3301 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3307 string const route_name = node_copy.property(X_("name"))->value ();
3309 /* generate a new name by adding a number to the end of the template name */
3310 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3311 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3312 abort(); /*NOTREACHED*/
3316 /* set this name in the XML description that we are about to use */
3318 if (pd == CopyPlaylist) {
3319 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3321 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3322 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3323 // Use same name as Route::set_name_in_state so playlist copy
3324 // is picked up when creating the Route in XMLRouteFactory below
3325 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3326 playlist->reset_shares ();
3328 } else if (pd == SharePlaylist) {
3329 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3331 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3332 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3333 playlist->share_with ((node_copy.property (X_("id")))->value());
3337 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3339 Route::set_name_in_state (node_copy, name, rename_playlist);
3341 /* trim bitslots from listen sends so that new ones are used */
3342 XMLNodeList children = node_copy.children ();
3343 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3344 if ((*i)->name() == X_("Processor")) {
3345 /* ForceIDRegeneration does not catch the following */
3346 XMLProperty const * role = (*i)->property (X_("role"));
3347 XMLProperty const * type = (*i)->property (X_("type"));
3348 if (role && role->value() == X_("Aux")) {
3349 /* check if the target bus exists.
3350 * we should not save aux-sends in templates.
3352 XMLProperty const * target = (*i)->property (X_("target"));
3354 (*i)->add_property ("type", "dangling-aux-send");
3357 boost::shared_ptr<Route> r = route_by_id (target->value());
3358 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3359 (*i)->add_property ("type", "dangling-aux-send");
3363 if (role && role->value() == X_("Listen")) {
3364 (*i)->remove_property (X_("bitslot"));
3366 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3368 Delivery::Role xrole;
3369 uint32_t bitslot = 0;
3370 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3371 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3372 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3373 (*i)->remove_property (X_("bitslot"));
3374 (*i)->remove_property (X_("name"));
3375 (*i)->add_property ("bitslot", buf);
3376 (*i)->add_property ("name", name);
3378 else if (type && type->value() == X_("intreturn")) {
3379 (*i)->remove_property (X_("bitslot"));
3380 (*i)->add_property ("ignore-bitslot", "1");
3382 else if (type && type->value() == X_("return")) {
3383 // Return::set_state() generates a new one
3384 (*i)->remove_property (X_("bitslot"));
3386 else if (type && type->value() == X_("port")) {
3387 // PortInsert::set_state() handles the bitslot
3388 (*i)->remove_property (X_("bitslot"));
3389 (*i)->add_property ("ignore-name", "1");
3394 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3397 error << _("Session: cannot create track/bus from template description") << endmsg;
3401 if (boost::dynamic_pointer_cast<Track>(route)) {
3402 /* force input/output change signals so that the new diskstream
3403 picks up the configuration of the route. During session
3404 loading this normally happens in a different way.
3407 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3409 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3410 change.after = route->input()->n_ports();
3411 route->input()->changed (change, this);
3412 change.after = route->output()->n_ports();
3413 route->output()->changed (change, this);
3416 ret.push_back (route);
3419 catch (failed_constructor &err) {
3420 error << _("Session: could not create new route from template") << endmsg;
3424 catch (AudioEngine::PortRegistrationFailure& pfe) {
3425 error << pfe.what() << endmsg;
3434 StateProtector sp (this);
3435 if (Profile->get_trx()) {
3436 add_routes (ret, false, false, false, insert_at);
3438 add_routes (ret, true, true, false, insert_at);
3440 IO::enable_connecting ();
3447 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3450 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3451 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3454 error << _("Adding new tracks/busses failed") << endmsg;
3459 update_latency (true);
3460 update_latency (false);
3465 save_state (_current_snapshot_name);
3468 update_route_record_state ();
3470 RouteAdded (new_routes); /* EMIT SIGNAL */
3474 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3476 ChanCount existing_inputs;
3477 ChanCount existing_outputs;
3481 count_existing_track_channels (existing_inputs, existing_outputs);
3484 RCUWriter<RouteList> writer (routes);
3485 boost::shared_ptr<RouteList> r = writer.get_copy ();
3486 r->insert (r->end(), new_routes.begin(), new_routes.end());
3487 n_routes = r->size();
3489 /* if there is no control out and we're not in the middle of loading,
3490 * resort the graph here. if there is a control out, we will resort
3491 * toward the end of this method. if we are in the middle of loading,
3492 * we will resort when done.
3495 if (!_monitor_out && IO::connecting_legal) {
3496 resort_routes_using (r);
3500 /* auditioner and monitor routes are not part of the order */
3502 assert (n_routes > 0);
3506 assert (n_routes > 0);
3510 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3511 ensure_route_presentation_info_gap (order, new_routes.size());
3514 PresentationInfo::ChangeSuspender cs;
3516 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3518 boost::weak_ptr<Route> wpr (*x);
3519 boost::shared_ptr<Route> r (*x);
3521 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3522 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3523 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3525 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3526 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3527 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3529 if (r->is_master()) {
3533 if (r->is_monitor()) {
3537 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3539 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3540 track_playlist_changed (boost::weak_ptr<Track> (tr));
3541 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3543 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3545 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3546 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3547 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3551 if (!r->presentation_info().special()) {
3553 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3555 /* presentation info order may already have been set from XML */
3557 if (!r->presentation_info().order_set()) {
3558 /* this is only useful for headless sessions,
3559 * Editor::add_routes() and Mixer_UI::add_routes() will
3560 * override it following the RouteAdded signal.
3562 * Also routes should be sorted before VCAs (like the GUI does).
3563 * Session::ensure_route_presentation_info_gap() does not special case VCAs either.
3565 * ... but not to worry, the GUI's
3566 * gtk2_ardour/route_sorter.h and various ::sync_presentation_info_from_treeview()
3570 if (order == PresentationInfo::max_order) {
3571 /* just add to the end */
3572 r->set_presentation_order (n_routes + added);
3573 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3575 r->set_presentation_order (order + added);
3576 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3579 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3583 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3584 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3585 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3587 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3589 r->presentation_info().order(),
3590 enum_2_string (r->presentation_info().flags()),
3591 r->presentation_info()));
3595 if (input_auto_connect || output_auto_connect) {
3596 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3597 existing_inputs += r->n_inputs();
3598 existing_outputs += r->n_outputs();
3605 if (_monitor_out && IO::connecting_legal) {
3606 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3608 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3609 if ((*x)->is_monitor()) {
3611 } else if ((*x)->is_master()) {
3614 (*x)->enable_monitor_send ();
3619 reassign_track_numbers ();
3623 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3625 boost::shared_ptr<RouteList> r = routes.reader ();
3626 boost::shared_ptr<Send> s;
3628 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3629 if ((s = (*i)->internal_send_for (dest)) != 0) {
3630 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3636 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3638 boost::shared_ptr<RouteList> r = routes.reader ();
3639 boost::shared_ptr<Send> s;
3641 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3642 if ((s = (*i)->internal_send_for (dest)) != 0) {
3643 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3649 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3651 boost::shared_ptr<RouteList> r = routes.reader ();
3652 boost::shared_ptr<Send> s;
3654 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3655 if ((s = (*i)->internal_send_for (dest)) != 0) {
3656 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3661 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3663 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3665 boost::shared_ptr<RouteList> r = routes.reader ();
3666 boost::shared_ptr<RouteList> t (new RouteList);
3668 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3669 /* no MIDI sends because there are no MIDI busses yet */
3670 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3675 add_internal_sends (dest, p, t);
3679 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3681 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3682 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3687 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3689 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3693 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3695 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3699 if (!dest->internal_return()) {
3700 dest->add_internal_return ();
3703 sender->add_aux_send (dest, before);
3709 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3711 { // RCU Writer scope
3712 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3713 RCUWriter<RouteList> writer (routes);
3714 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3717 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3719 if (*iter == _master_out) {
3723 /* speed up session deletion, don't do the solo dance */
3724 if (0 == (_state_of_the_state & Deletion)) {
3725 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3730 /* deleting the master out seems like a dumb
3731 idea, but its more of a UI policy issue
3735 if (*iter == _master_out) {
3736 _master_out = boost::shared_ptr<Route> ();
3739 if (*iter == _monitor_out) {
3740 _monitor_out.reset ();
3743 // We need to disconnect the route's inputs and outputs
3745 (*iter)->input()->disconnect (0);
3746 (*iter)->output()->disconnect (0);
3748 /* if the route had internal sends sending to it, remove them */
3749 if ((*iter)->internal_return()) {
3751 boost::shared_ptr<RouteList> r = routes.reader ();
3752 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3753 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3755 (*i)->remove_processor (s);
3760 /* if the monitoring section had a pointer to this route, remove it */
3761 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3762 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3763 ProcessorChangeBlocker pcb (this, false);
3764 (*iter)->remove_aux_or_listen (_monitor_out);
3767 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3768 if (mt && mt->step_editing()) {
3769 if (_step_editors > 0) {
3775 /* writer goes out of scope, forces route list update */
3777 } // end of RCU Writer scope
3779 update_route_solo_state ();
3780 update_latency_compensation ();
3783 /* Re-sort routes to remove the graph's current references to the one that is
3784 * going away, then flush old references out of the graph.
3785 * Wave Tracks: reconnect routes
3788 #ifdef USE_TRACKS_CODE_FEATURES
3789 reconnect_existing_routes(true, false);
3791 routes.flush (); // maybe unsafe, see below.
3795 if (_process_graph && !(_state_of_the_state & Deletion)) {
3796 _process_graph->clear_other_chain ();
3799 /* get rid of it from the dead wood collection in the route list manager */
3800 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3804 /* try to cause everyone to drop their references
3805 * and unregister ports from the backend
3808 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3809 cerr << "Drop references to " << (*iter)->name() << endl;
3810 (*iter)->drop_references ();
3813 if (_state_of_the_state & Deletion) {
3818 so.add (Properties::selected);
3819 so.add (Properties::order);
3820 PresentationInfo::Change (PropertyChange (so));
3822 /* save the new state of the world */
3824 if (save_state (_current_snapshot_name)) {
3825 save_history (_current_snapshot_name);
3828 update_route_record_state ();
3832 Session::remove_route (boost::shared_ptr<Route> route)
3834 boost::shared_ptr<RouteList> rl (new RouteList);
3835 rl->push_back (route);
3840 Session::route_mute_changed ()
3846 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3848 boost::shared_ptr<Route> route (wpr.lock());
3854 assert (Config->get_solo_control_is_listen_control());
3856 if (route->solo_control()->soloed_by_self_or_masters()) {
3858 if (Config->get_exclusive_solo()) {
3860 RouteGroup* rg = route->route_group ();
3861 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3863 boost::shared_ptr<RouteList> r = routes.reader ();
3865 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3866 if ((*i) == route) {
3867 /* already changed */
3871 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3872 /* route does not get solo propagated to it */
3876 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3877 /* this route is a part of the same solo group as the route
3878 * that was changed. Changing that route did change or will
3879 * change all group members appropriately, so we can ignore it
3884 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3890 } else if (_listen_cnt > 0) {
3897 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3899 boost::shared_ptr<Route> route (wpr.lock());
3905 bool send_changed = false;
3907 if (route->solo_isolate_control()->solo_isolated()) {
3908 if (_solo_isolated_cnt == 0) {
3909 send_changed = true;
3911 _solo_isolated_cnt++;
3912 } else if (_solo_isolated_cnt > 0) {
3913 _solo_isolated_cnt--;
3914 if (_solo_isolated_cnt == 0) {
3915 send_changed = true;
3920 IsolatedChanged (); /* EMIT SIGNAL */
3925 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3927 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3929 boost::shared_ptr<Route> route (wpr.lock());
3935 if (Config->get_solo_control_is_listen_control()) {
3936 route_listen_changed (group_override, wpr);
3940 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: self %2 masters %3 transition %4\n", route->name(), route->self_soloed(), route->solo_control()->get_masters_value(), route->solo_control()->transitioned_into_solo()));
3942 if (route->solo_control()->transitioned_into_solo() == 0) {
3943 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3946 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 not self-soloed nor soloed by master (%2), ignoring\n", route->name(), route->solo_control()->get_masters_value()));
3950 boost::shared_ptr<RouteList> r = routes.reader ();
3951 int32_t delta = route->solo_control()->transitioned_into_solo ();
3953 /* the route may be a member of a group that has shared-solo
3954 * semantics. If so, then all members of that group should follow the
3955 * solo of the changed route. But ... this is optional, controlled by a
3956 * Controllable::GroupControlDisposition.
3958 * The first argument to the signal that this method is connected to is the
3959 * GroupControlDisposition value that was used to change solo.
3961 * If the solo change was done with group semantics (either InverseGroup
3962 * (force the entire group to change even if the group shared solo is
3963 * disabled) or UseGroup (use the group, which may or may not have the
3964 * shared solo property enabled)) then as we propagate the change to
3965 * the entire session we should IGNORE THE GROUP that the changed route
3969 RouteGroup* rg = route->route_group ();
3970 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3972 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
3974 if (delta == 1 && Config->get_exclusive_solo()) {
3976 /* new solo: disable all other solos, but not the group if its solo-enabled */
3978 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3980 if ((*i) == route) {
3981 /* already changed */
3985 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3986 /* route does not get solo propagated to it */
3990 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3991 /* this route is a part of the same solo group as the route
3992 * that was changed. Changing that route did change or will
3993 * change all group members appropriately, so we can ignore it
3999 (*i)->solo_control()->set_value (0.0, group_override);
4003 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4005 RouteList uninvolved;
4007 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4009 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4010 bool via_sends_only;
4011 bool in_signal_flow;
4013 if ((*i) == route) {
4014 /* already changed */
4018 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4019 /* route does not get solo propagated to it */
4020 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 excluded from solo because iso = %2 can_solo = %3\n", (*i)->name(), (*i)->solo_isolate_control()->solo_isolated(),
4025 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4026 /* this route is a part of the same solo group as the route
4027 * that was changed. Changing that route did change or will
4028 * change all group members appropriately, so we can ignore it
4034 in_signal_flow = false;
4036 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4038 if ((*i)->feeds (route, &via_sends_only)) {
4039 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4040 if (!via_sends_only) {
4041 if (!route->soloed_by_others_upstream()) {
4042 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4044 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4047 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4049 in_signal_flow = true;
4051 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4054 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4056 if (route->feeds (*i, &via_sends_only)) {
4057 /* propagate solo upstream only if routing other than
4058 sends is involved, but do consider the other route
4059 (*i) to be part of the signal flow even if only
4062 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4066 route->soloed_by_others_downstream(),
4067 route->soloed_by_others_upstream()));
4068 if (!via_sends_only) {
4069 //NB. Triggers Invert Push, which handles soloed by downstream
4070 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4071 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4073 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4075 in_signal_flow = true;
4077 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4080 if (!in_signal_flow) {
4081 uninvolved.push_back (*i);
4085 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4087 /* now notify that the mute state of the routes not involved in the signal
4088 pathway of the just-solo-changed route may have altered.
4091 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4092 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4093 (*i)->act_on_mute ();
4094 /* Session will emit SoloChanged() after all solo changes are
4095 * complete, which should be used by UIs to update mute status
4101 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4103 /* now figure out if anything that matters is soloed (or is "listening")*/
4105 bool something_soloed = false;
4106 bool something_listening = false;
4107 uint32_t listeners = 0;
4108 uint32_t isolated = 0;
4111 r = routes.reader();
4114 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4115 if ((*i)->can_solo()) {
4116 if (Config->get_solo_control_is_listen_control()) {
4117 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4119 something_listening = true;
4122 (*i)->set_listen (false);
4123 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4124 something_soloed = true;
4129 if ((*i)->solo_isolate_control()->solo_isolated()) {
4134 if (something_soloed != _non_soloed_outs_muted) {
4135 _non_soloed_outs_muted = something_soloed;
4136 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4139 if (something_listening != _listening) {
4140 _listening = something_listening;
4141 SoloActive (_listening);
4144 _listen_cnt = listeners;
4146 if (isolated != _solo_isolated_cnt) {
4147 _solo_isolated_cnt = isolated;
4148 IsolatedChanged (); /* EMIT SIGNAL */
4151 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4152 something_soloed, listeners, isolated));
4155 SoloChanged (); /* EMIT SIGNAL */
4160 Session::get_stripables (StripableList& sl) const
4162 boost::shared_ptr<RouteList> r = routes.reader ();
4163 sl.insert (sl.end(), r->begin(), r->end());
4165 VCAList v = _vca_manager->vcas ();
4166 sl.insert (sl.end(), v.begin(), v.end());
4169 boost::shared_ptr<RouteList>
4170 Session::get_routes_with_internal_returns() const
4172 boost::shared_ptr<RouteList> r = routes.reader ();
4173 boost::shared_ptr<RouteList> rl (new RouteList);
4175 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4176 if ((*i)->internal_return ()) {
4184 Session::io_name_is_legal (const std::string& name) const
4186 boost::shared_ptr<RouteList> r = routes.reader ();
4188 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4189 if (name == reserved->first) {
4190 if (!route_by_name (reserved->first)) {
4191 /* first instance of a reserved name is allowed */
4194 /* all other instances of a reserved name are not allowed */
4199 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4200 if ((*i)->name() == name) {
4204 if ((*i)->has_io_processor_named (name)) {
4213 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4216 vector<string> connections;
4218 /* if we are passed only a single route and we're not told to turn
4219 * others off, then just do the simple thing.
4222 if (flip_others == false && rl->size() == 1) {
4223 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4225 mt->set_input_active (onoff);
4230 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4232 PortSet& ps ((*rt)->input()->ports());
4234 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4235 p->get_connections (connections);
4238 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4239 routes_using_input_from (*s, rl2);
4242 /* scan all relevant routes to see if others are on or off */
4244 bool others_are_already_on = false;
4246 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4248 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4254 if ((*r) != (*rt)) {
4255 if (mt->input_active()) {
4256 others_are_already_on = true;
4259 /* this one needs changing */
4260 mt->set_input_active (onoff);
4266 /* globally reverse other routes */
4268 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4269 if ((*r) != (*rt)) {
4270 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4272 mt->set_input_active (!others_are_already_on);
4281 Session::routes_using_input_from (const string& str, RouteList& rl)
4283 boost::shared_ptr<RouteList> r = routes.reader();
4285 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4286 if ((*i)->input()->connected_to (str)) {
4292 boost::shared_ptr<Route>
4293 Session::route_by_name (string name) const
4295 boost::shared_ptr<RouteList> r = routes.reader ();
4297 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4298 if ((*i)->name() == name) {
4303 return boost::shared_ptr<Route> ((Route*) 0);
4306 boost::shared_ptr<Route>
4307 Session::route_by_id (PBD::ID id) const
4309 boost::shared_ptr<RouteList> r = routes.reader ();
4311 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4312 if ((*i)->id() == id) {
4317 return boost::shared_ptr<Route> ((Route*) 0);
4320 boost::shared_ptr<Processor>
4321 Session::processor_by_id (PBD::ID id) const
4323 boost::shared_ptr<RouteList> r = routes.reader ();
4325 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4326 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4332 return boost::shared_ptr<Processor> ();
4335 boost::shared_ptr<Track>
4336 Session::track_by_diskstream_id (PBD::ID id) const
4338 boost::shared_ptr<RouteList> r = routes.reader ();
4340 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4341 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4342 if (t && t->using_diskstream_id (id)) {
4347 return boost::shared_ptr<Track> ();
4350 boost::shared_ptr<Route>
4351 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4353 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4356 boost::shared_ptr<Stripable>
4357 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4360 PresentationInfo::order_t match_cnt = 0;
4362 get_stripables (sl);
4363 sl.sort (Stripable::PresentationOrderSorter());
4365 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4367 if ((*s)->presentation_info().hidden()) {
4368 /* if the caller didn't explicitly ask for hidden
4369 stripables, ignore hidden ones. This matches
4370 the semantics of the pre-PresentationOrder
4371 "get by RID" logic of Ardour 4.x and earlier.
4373 XXX at some point we should likely reverse
4374 the logic of the flags, because asking for "the
4375 hidden stripables" is not going to be common,
4376 whereas asking for visible ones is normal.
4379 if (! (flags & PresentationInfo::Hidden)) {
4384 if ((*s)->presentation_info().flag_match (flags)) {
4385 if (match_cnt++ == n) {
4391 /* there is no nth stripable that matches the given flags */
4392 return boost::shared_ptr<Stripable>();
4395 struct PresentationOrderSorter {
4396 bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4397 if (a->presentation_info().special() && !b->presentation_info().special()) {
4398 /* a is not ordered, b is; b comes before a */
4400 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4401 /* b is not ordered, a is; a comes before b */
4404 return a->presentation_info().order() < b->presentation_info().order();
4409 boost::shared_ptr<Route>
4410 Session::route_by_selected_count (uint32_t id) const
4412 RouteList r (*(routes.reader ()));
4413 PresentationOrderSorter sorter;
4416 RouteList::iterator i;
4418 for (i = r.begin(); i != r.end(); ++i) {
4419 if ((*i)->presentation_info().selected()) {
4427 return boost::shared_ptr<Route> ();
4431 Session::reassign_track_numbers ()
4435 RouteList r (*(routes.reader ()));
4436 PresentationOrderSorter sorter;
4439 StateProtector sp (this);
4441 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4442 if (boost::dynamic_pointer_cast<Track> (*i)) {
4443 (*i)->set_track_number(++tn);
4445 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4446 (*i)->set_track_number(--bn);
4449 const uint32_t decimals = ceilf (log10f (tn + 1));
4450 const bool decimals_changed = _track_number_decimals != decimals;
4451 _track_number_decimals = decimals;
4453 if (decimals_changed && config.get_track_name_number ()) {
4454 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4455 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4457 t->resync_track_name();
4460 // trigger GUI re-layout
4461 config.ParameterChanged("track-name-number");
4465 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4466 boost::shared_ptr<RouteList> rl = routes.reader ();
4467 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4468 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4476 Session::playlist_region_added (boost::weak_ptr<Region> w)
4478 boost::shared_ptr<Region> r = w.lock ();
4483 /* These are the operations that are currently in progress... */
4484 list<GQuark> curr = _current_trans_quarks;
4487 /* ...and these are the operations during which we want to update
4488 the session range location markers.
4491 ops.push_back (Operations::capture);
4492 ops.push_back (Operations::paste);
4493 ops.push_back (Operations::duplicate_region);
4494 ops.push_back (Operations::insert_file);
4495 ops.push_back (Operations::insert_region);
4496 ops.push_back (Operations::drag_region_brush);
4497 ops.push_back (Operations::region_drag);
4498 ops.push_back (Operations::selection_grab);
4499 ops.push_back (Operations::region_fill);
4500 ops.push_back (Operations::fill_selection);
4501 ops.push_back (Operations::create_region);
4502 ops.push_back (Operations::region_copy);
4503 ops.push_back (Operations::fixed_time_region_copy);
4506 /* See if any of the current operations match the ones that we want */
4508 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4510 /* If so, update the session range markers */
4512 maybe_update_session_range (r->position (), r->last_frame ());
4516 /** Update the session range markers if a is before the current start or
4517 * b is after the current end.
4520 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4522 if (_state_of_the_state & Loading) {
4526 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4528 if (_session_range_location == 0) {
4530 set_session_range_location (a, b + session_end_marker_shift_samples);
4534 if (a < _session_range_location->start()) {
4535 _session_range_location->set_start (a);
4538 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4539 _session_range_location->set_end (b);
4545 Session::set_end_is_free (bool yn)
4547 _session_range_end_is_free = yn;
4551 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4553 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4554 maybe_update_session_range (i->to, i->to + i->length);
4559 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4561 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4562 maybe_update_session_range (i->from, i->to);
4566 /* Region management */
4568 boost::shared_ptr<Region>
4569 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4571 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4572 RegionFactory::RegionMap::const_iterator i;
4573 boost::shared_ptr<Region> region;
4575 Glib::Threads::Mutex::Lock lm (region_lock);
4577 for (i = regions.begin(); i != regions.end(); ++i) {
4581 if (region->whole_file()) {
4583 if (child->source_equivalent (region)) {
4589 return boost::shared_ptr<Region> ();
4593 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4595 set<boost::shared_ptr<Region> > relevant_regions;
4597 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4598 RegionFactory::get_regions_using_source (*s, relevant_regions);
4601 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4602 set<boost::shared_ptr<Region> >::iterator tmp;
4607 playlists->destroy_region (*r);
4608 RegionFactory::map_remove (*r);
4610 (*r)->drop_sources ();
4611 (*r)->drop_references ();
4613 relevant_regions.erase (r);
4618 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4621 Glib::Threads::Mutex::Lock ls (source_lock);
4622 /* remove from the main source list */
4623 sources.erase ((*s)->id());
4626 (*s)->mark_for_remove ();
4627 (*s)->drop_references ();
4636 Session::remove_last_capture ()
4638 list<boost::shared_ptr<Source> > srcs;
4640 boost::shared_ptr<RouteList> rl = routes.reader ();
4641 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4642 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4647 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4650 srcs.insert (srcs.end(), l.begin(), l.end());
4655 destroy_sources (srcs);
4657 save_state (_current_snapshot_name);
4662 /* Source Management */
4665 Session::add_source (boost::shared_ptr<Source> source)
4667 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4668 pair<SourceMap::iterator,bool> result;
4670 entry.first = source->id();
4671 entry.second = source;
4674 Glib::Threads::Mutex::Lock lm (source_lock);
4675 result = sources.insert (entry);
4678 if (result.second) {
4680 /* yay, new source */
4682 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4685 if (!fs->within_session()) {
4686 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4692 boost::shared_ptr<AudioFileSource> afs;
4694 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4695 if (Config->get_auto_analyse_audio()) {
4696 Analyser::queue_source_for_analysis (source, false);
4700 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4705 Session::remove_source (boost::weak_ptr<Source> src)
4707 if (_state_of_the_state & Deletion) {
4711 SourceMap::iterator i;
4712 boost::shared_ptr<Source> source = src.lock();
4719 Glib::Threads::Mutex::Lock lm (source_lock);
4721 if ((i = sources.find (source->id())) != sources.end()) {
4726 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4728 /* save state so we don't end up with a session file
4729 referring to non-existent sources.
4732 save_state (_current_snapshot_name);
4736 boost::shared_ptr<Source>
4737 Session::source_by_id (const PBD::ID& id)
4739 Glib::Threads::Mutex::Lock lm (source_lock);
4740 SourceMap::iterator i;
4741 boost::shared_ptr<Source> source;
4743 if ((i = sources.find (id)) != sources.end()) {
4750 boost::shared_ptr<AudioFileSource>
4751 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4753 /* Restricted to audio files because only audio sources have channel
4757 Glib::Threads::Mutex::Lock lm (source_lock);
4759 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4760 boost::shared_ptr<AudioFileSource> afs
4761 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4763 if (afs && afs->path() == path && chn == afs->channel()) {
4768 return boost::shared_ptr<AudioFileSource>();
4771 boost::shared_ptr<MidiSource>
4772 Session::midi_source_by_path (const std::string& path) const
4774 /* Restricted to MIDI files because audio sources require a channel
4775 for unique identification, in addition to a path.
4778 Glib::Threads::Mutex::Lock lm (source_lock);
4780 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4781 boost::shared_ptr<MidiSource> ms
4782 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4783 boost::shared_ptr<FileSource> fs
4784 = boost::dynamic_pointer_cast<FileSource>(s->second);
4786 if (ms && fs && fs->path() == path) {
4791 return boost::shared_ptr<MidiSource>();
4795 Session::count_sources_by_origin (const string& path)
4798 Glib::Threads::Mutex::Lock lm (source_lock);
4800 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4801 boost::shared_ptr<FileSource> fs
4802 = boost::dynamic_pointer_cast<FileSource>(i->second);
4804 if (fs && fs->origin() == path) {
4813 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4815 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4816 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4818 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4823 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4825 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4827 if (Glib::path_is_absolute (filepath)) {
4829 /* rip the session dir from the audiofile source */
4831 string session_path;
4832 bool in_another_session = true;
4834 if (filepath.find (interchange_dir_string) != string::npos) {
4836 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4837 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4838 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4839 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4841 /* see if it is within our session */
4843 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4844 if (i->path == session_path) {
4845 in_another_session = false;
4850 in_another_session = false;
4854 if (in_another_session) {
4855 SessionDirectory sd (session_path);
4856 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4860 /* 1) if file belongs to this session
4861 * it may be a relative path (interchange/...)
4862 * or just basename (session_state, remove source)
4863 * -> just use the basename
4865 std::string filename = Glib::path_get_basename (filepath);
4868 /* 2) if the file is outside our session dir:
4869 * (imported but not copied) add the path for check-summming */
4871 path = Glib::path_get_dirname (filepath);
4874 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4878 Session::new_audio_source_path_for_embedded (const std::string& path)
4882 * we know that the filename is already unique because it exists
4883 * out in the filesystem.
4885 * However, when we bring it into the session, we could get a
4888 * Eg. two embedded files:
4893 * When merged into session, these collide.
4895 * There will not be a conflict with in-memory sources
4896 * because when the source was created we already picked
4897 * a unique name for it.
4899 * This collision is not likely to be common, but we have to guard
4900 * against it. So, if there is a collision, take the md5 hash of the
4901 * the path, and use that as the filename instead.
4904 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4905 string base = Glib::path_get_basename (path);
4906 string newpath = Glib::build_filename (sdir.sound_path(), base);
4908 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4912 md5.digestString (path.c_str());
4913 md5.writeToString ();
4914 base = md5.digestChars;
4916 string ext = get_suffix (path);
4923 newpath = Glib::build_filename (sdir.sound_path(), base);
4925 /* if this collides, we're screwed */
4927 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4928 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4937 /** Return true if there are no audio file sources that use @param name as
4938 * the filename component of their path.
4940 * Return false otherwise.
4942 * This method MUST ONLY be used to check in-session, mono files since it
4943 * hard-codes the channel of the audio file source we are looking for as zero.
4945 * If/when Ardour supports native files in non-mono formats, the logic here
4946 * will need to be revisited.
4949 Session::audio_source_name_is_unique (const string& name)
4951 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4952 vector<space_and_path>::iterator i;
4953 uint32_t existing = 0;
4955 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4957 /* note that we search *without* the extension so that
4958 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4959 in the event that this new name is required for
4960 a file format change.
4963 const string spath = *i;
4965 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4970 /* it is possible that we have the path already
4971 * assigned to a source that has not yet been written
4972 * (ie. the write source for a diskstream). we have to
4973 * check this in order to make sure that our candidate
4974 * path isn't used again, because that can lead to
4975 * two Sources point to the same file with different
4976 * notions of their removability.
4980 string possible_path = Glib::build_filename (spath, name);
4982 if (audio_source_by_path_and_channel (possible_path, 0)) {
4988 return (existing == 0);
4992 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)
4995 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4997 if (Profile->get_trx() && destructive) {
4999 sstr << setfill ('0') << setw (4) << cnt;
5000 sstr << legalized_base;
5002 sstr << legalized_base;
5004 if (take_required || related_exists) {
5016 } else if (nchan > 2) {
5021 /* XXX what? more than 26 channels! */
5032 /** Return a unique name based on \a base for a new internal audio source */
5034 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5037 string possible_name;
5038 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5040 bool some_related_source_name_exists = false;
5042 legalized = legalize_for_path (base);
5044 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5046 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5048 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5050 if (audio_source_name_is_unique (possible_name)) {
5054 some_related_source_name_exists = true;
5057 error << string_compose(
5058 _("There are already %1 recordings for %2, which I consider too many."),
5059 limit, base) << endmsg;
5061 throw failed_constructor();
5065 /* We've established that the new name does not exist in any session
5066 * directory, so now find out which one we should use for this new
5070 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5072 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5077 /** Return a unique name based on `base` for a new internal MIDI source */
5079 Session::new_midi_source_path (const string& base)
5082 char buf[PATH_MAX+1];
5083 const uint32_t limit = 10000;
5085 string possible_path;
5086 string possible_name;
5089 legalized = legalize_for_path (base);
5091 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5092 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5094 /* - the main session folder is the first in the vector.
5095 * - after checking all locations for file-name uniqueness,
5096 * we keep the one from the last iteration as new file name
5097 * - midi files are small and should just be kept in the main session-folder
5099 * -> reverse the array, check main session folder last and use that as location
5102 std::reverse(sdirs.begin(), sdirs.end());
5104 for (cnt = 1; cnt <= limit; ++cnt) {
5106 vector<space_and_path>::iterator i;
5107 uint32_t existing = 0;
5109 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5111 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5112 possible_name = buf;
5114 possible_path = Glib::build_filename (*i, possible_name);
5116 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5120 if (midi_source_by_path (possible_path)) {
5125 if (existing == 0) {
5130 error << string_compose(
5131 _("There are already %1 recordings for %2, which I consider too many."),
5132 limit, base) << endmsg;
5138 /* No need to "find best location" for software/app-based RAID, because
5139 MIDI is so small that we always put it in the same place.
5142 return possible_path;
5146 /** Create a new within-session audio source */
5147 boost::shared_ptr<AudioFileSource>
5148 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5150 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5152 if (!path.empty()) {
5153 return boost::dynamic_pointer_cast<AudioFileSource> (
5154 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5156 throw failed_constructor ();
5160 /** Create a new within-session MIDI source */
5161 boost::shared_ptr<MidiSource>
5162 Session::create_midi_source_for_session (string const & basic_name)
5164 const string path = new_midi_source_path (basic_name);
5166 if (!path.empty()) {
5167 return boost::dynamic_pointer_cast<SMFSource> (
5168 SourceFactory::createWritable (
5169 DataType::MIDI, *this, path, false, frame_rate()));
5171 throw failed_constructor ();
5175 /** Create a new within-session MIDI source */
5176 boost::shared_ptr<MidiSource>
5177 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5179 /* the caller passes in the track the source will be used in,
5180 so that we can keep the numbering sane.
5182 Rationale: a track with the name "Foo" that has had N
5183 captures carried out so far will ALREADY have a write source
5184 named "Foo-N+1.mid" waiting to be used for the next capture.
5186 If we call new_midi_source_name() we will get "Foo-N+2". But
5187 there is no region corresponding to "Foo-N+1", so when
5188 "Foo-N+2" appears in the track, the gap presents the user
5189 with odd behaviour - why did it skip past Foo-N+1?
5191 We could explain this to the user in some odd way, but
5192 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5195 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5198 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5200 std::string name = track->steal_write_source_name ();
5203 return boost::shared_ptr<MidiSource>();
5206 /* MIDI files are small, just put them in the first location of the
5207 session source search path.
5210 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5212 return boost::dynamic_pointer_cast<SMFSource> (
5213 SourceFactory::createWritable (
5214 DataType::MIDI, *this, path, false, frame_rate()));
5219 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5221 if (playlist->hidden()) {
5225 playlists->add (playlist);
5228 playlist->release();
5235 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5237 if (_state_of_the_state & Deletion) {
5241 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5247 playlists->remove (playlist);
5253 Session::set_audition (boost::shared_ptr<Region> r)
5255 pending_audition_region = r;
5256 add_post_transport_work (PostTransportAudition);
5257 _butler->schedule_transport_work ();
5261 Session::audition_playlist ()
5263 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5264 ev->region.reset ();
5270 Session::register_lua_function (
5271 const std::string& name,
5272 const std::string& script,
5273 const LuaScriptParamList& args
5276 Glib::Threads::Mutex::Lock lm (lua_lock);
5278 lua_State* L = lua.getState();
5280 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5281 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5282 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5283 if ((*i)->optional && !(*i)->is_set) { continue; }
5284 tbl_arg[(*i)->name] = (*i)->value;
5286 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5289 LuaScriptsChanged (); /* EMIT SIGNAL */
5294 Session::unregister_lua_function (const std::string& name)
5296 Glib::Threads::Mutex::Lock lm (lua_lock);
5297 (*_lua_del)(name); // throws luabridge::LuaException
5298 lua.collect_garbage ();
5301 LuaScriptsChanged (); /* EMIT SIGNAL */
5305 std::vector<std::string>
5306 Session::registered_lua_functions ()
5308 Glib::Threads::Mutex::Lock lm (lua_lock);
5309 std::vector<std::string> rv;
5312 luabridge::LuaRef list ((*_lua_list)());
5313 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5314 if (!i.key ().isString ()) { assert(0); continue; }
5315 rv.push_back (i.key ().cast<std::string> ());
5317 } catch (luabridge::LuaException const& e) { }
5322 static void _lua_print (std::string s) {
5323 std::cout << "SessionLua: " << s << "\n";
5328 Session::try_run_lua (pframes_t nframes)
5330 if (_n_lua_scripts == 0) return;
5331 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5333 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5334 lua.collect_garbage_step ();
5339 Session::setup_lua ()
5342 lua.Print.connect (&_lua_print);
5346 "function ArdourSession ()"
5347 " local self = { scripts = {}, instances = {} }"
5349 " local remove = function (n)"
5350 " self.scripts[n] = nil"
5351 " self.instances[n] = nil"
5352 " Session:scripts_changed()" // call back
5355 " local addinternal = function (n, f, a)"
5356 " assert(type(n) == 'string', 'function-name must be string')"
5357 " assert(type(f) == 'function', 'Given script is a not a function')"
5358 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5359 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5360 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5361 " 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"
5362 " local env = { print = print, tostring = tostring, assert = assert, ipairs = ipairs, error = error, select = select, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall, bit32=bit32, Session = Session, PBD = PBD, Timecode = Timecode, Evoral = Evoral, C = C, ARDOUR = ARDOUR }"
5363 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5364 " Session:scripts_changed()" // call back
5367 " local add = function (n, b, a)"
5368 " assert(type(b) == 'string', 'ByteCode must be string')"
5369 " load (b)()" // assigns f
5370 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5371 " addinternal (n, load(f), a)"
5374 " local run = function (...)"
5375 " for n, s in pairs (self.instances) do"
5376 " local status, err = pcall (s, ...)"
5377 " if not status then"
5378 " print ('fn \"'.. n .. '\": ', err)"
5385 " local cleanup = function ()"
5386 " self.scripts = nil"
5387 " self.instances = nil"
5390 " local list = function ()"
5392 " for n, _ in pairs (self.scripts) do"
5398 " local function basic_serialize (o)"
5399 " if type(o) == \"number\" then"
5400 " return tostring(o)"
5402 " return string.format(\"%q\", o)"
5406 " local function serialize (name, value)"
5407 " local rv = name .. ' = '"
5409 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5410 " return rv .. basic_serialize(value) .. ' '"
5411 " elseif type(value) == \"table\" then"
5413 " for k,v in pairs(value) do"
5414 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5415 " rv = rv .. serialize(fieldname, v) .. ' '"
5416 " collectgarbage()" // string concatenation allocates a new string :(
5419 " elseif type(value) == \"function\" then"
5420 " return rv .. string.format(\"%q\", string.dump(value, true))"
5422 " error('cannot save a ' .. type(value))"
5427 " local save = function ()"
5428 " return (serialize('scripts', self.scripts))"
5431 " local restore = function (state)"
5432 " self.scripts = {}"
5434 " for n, s in pairs (scripts) do"
5435 " addinternal (n, load(s['f']), s['a'])"
5439 " return { run = run, add = add, remove = remove,"
5440 " list = list, restore = restore, save = save, cleanup = cleanup}"
5443 " sess = ArdourSession ()"
5444 " ArdourSession = nil"
5446 "function ardour () end"
5449 lua_State* L = lua.getState();
5452 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5453 lua.do_command ("sess = nil"); // hide it.
5454 lua.do_command ("collectgarbage()");
5456 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5457 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5458 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5459 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5460 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5461 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5462 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5463 } catch (luabridge::LuaException const& e) {
5464 fatal << string_compose (_("programming error: %1"),
5465 X_("Failed to setup Lua interpreter"))
5467 abort(); /*NOTREACHED*/
5470 LuaBindings::stddef (L);
5471 LuaBindings::common (L);
5472 LuaBindings::dsp (L);
5473 luabridge::push <Session *> (L, this);
5474 lua_setglobal (L, "Session");
5478 Session::scripts_changed ()
5480 assert (!lua_lock.trylock()); // must hold lua_lock
5483 luabridge::LuaRef list ((*_lua_list)());
5485 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5486 if (!i.key ().isString ()) { assert(0); continue; }
5489 _n_lua_scripts = cnt;
5490 } catch (luabridge::LuaException const& e) {
5491 fatal << string_compose (_("programming error: %1"),
5492 X_("Indexing Lua Session Scripts failed."))
5494 abort(); /*NOTREACHED*/
5499 Session::non_realtime_set_audition ()
5501 assert (pending_audition_region);
5502 auditioner->audition_region (pending_audition_region);
5503 pending_audition_region.reset ();
5504 AuditionActive (true); /* EMIT SIGNAL */
5508 Session::audition_region (boost::shared_ptr<Region> r)
5510 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5516 Session::cancel_audition ()
5521 if (auditioner->auditioning()) {
5522 auditioner->cancel_audition ();
5523 AuditionActive (false); /* EMIT SIGNAL */
5528 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5530 if (a->is_monitor()) {
5533 if (b->is_monitor()) {
5536 return a->presentation_info().order() < b->presentation_info().order();
5540 Session::is_auditioning () const
5542 /* can be called before we have an auditioner object */
5544 return auditioner->auditioning();
5551 Session::graph_reordered ()
5553 /* don't do this stuff if we are setting up connections
5554 from a set_state() call or creating new tracks. Ditto for deletion.
5557 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5561 /* every track/bus asked for this to be handled but it was deferred because
5562 we were connecting. do it now.
5565 request_input_change_handling ();
5569 /* force all diskstreams to update their capture offset values to
5570 reflect any changes in latencies within the graph.
5573 boost::shared_ptr<RouteList> rl = routes.reader ();
5574 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5575 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5577 tr->set_capture_offset ();
5582 /** @return Number of frames that there is disk space available to write,
5585 boost::optional<framecnt_t>
5586 Session::available_capture_duration ()
5588 Glib::Threads::Mutex::Lock lm (space_lock);
5590 if (_total_free_4k_blocks_uncertain) {
5591 return boost::optional<framecnt_t> ();
5594 float sample_bytes_on_disk = 4.0; // keep gcc happy
5596 switch (config.get_native_file_data_format()) {
5598 sample_bytes_on_disk = 4.0;
5602 sample_bytes_on_disk = 3.0;
5606 sample_bytes_on_disk = 2.0;
5610 /* impossible, but keep some gcc versions happy */
5611 fatal << string_compose (_("programming error: %1"),
5612 X_("illegal native file data format"))
5614 abort(); /*NOTREACHED*/
5617 double scale = 4096.0 / sample_bytes_on_disk;
5619 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5620 return max_framecnt;
5623 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5627 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5630 RCUWriter<BundleList> writer (_bundles);
5631 boost::shared_ptr<BundleList> b = writer.get_copy ();
5632 b->push_back (bundle);
5636 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5643 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5645 bool removed = false;
5648 RCUWriter<BundleList> writer (_bundles);
5649 boost::shared_ptr<BundleList> b = writer.get_copy ();
5650 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5652 if (i != b->end()) {
5659 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5665 boost::shared_ptr<Bundle>
5666 Session::bundle_by_name (string name) const
5668 boost::shared_ptr<BundleList> b = _bundles.reader ();
5670 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5671 if ((*i)->name() == name) {
5676 return boost::shared_ptr<Bundle> ();
5680 Session::tempo_map_changed (const PropertyChange&)
5684 playlists->update_after_tempo_map_change ();
5686 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5692 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5694 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5695 (*i)->recompute_frames_from_beat ();
5699 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5700 * the given count with the current block size.
5703 Session::ensure_buffers (ChanCount howmany)
5705 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5709 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5711 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5712 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5717 Session::next_insert_id ()
5719 /* this doesn't really loop forever. just think about it */
5722 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5723 if (!insert_bitset[n]) {
5724 insert_bitset[n] = true;
5730 /* none available, so resize and try again */
5732 insert_bitset.resize (insert_bitset.size() + 16, false);
5737 Session::next_send_id ()
5739 /* this doesn't really loop forever. just think about it */
5742 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5743 if (!send_bitset[n]) {
5744 send_bitset[n] = true;
5750 /* none available, so resize and try again */
5752 send_bitset.resize (send_bitset.size() + 16, false);
5757 Session::next_aux_send_id ()
5759 /* this doesn't really loop forever. just think about it */
5762 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5763 if (!aux_send_bitset[n]) {
5764 aux_send_bitset[n] = true;
5770 /* none available, so resize and try again */
5772 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5777 Session::next_return_id ()
5779 /* this doesn't really loop forever. just think about it */
5782 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5783 if (!return_bitset[n]) {
5784 return_bitset[n] = true;
5790 /* none available, so resize and try again */
5792 return_bitset.resize (return_bitset.size() + 16, false);
5797 Session::mark_send_id (uint32_t id)
5799 if (id >= send_bitset.size()) {
5800 send_bitset.resize (id+16, false);
5802 if (send_bitset[id]) {
5803 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5805 send_bitset[id] = true;
5809 Session::mark_aux_send_id (uint32_t id)
5811 if (id >= aux_send_bitset.size()) {
5812 aux_send_bitset.resize (id+16, false);
5814 if (aux_send_bitset[id]) {
5815 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5817 aux_send_bitset[id] = true;
5821 Session::mark_return_id (uint32_t id)
5823 if (id >= return_bitset.size()) {
5824 return_bitset.resize (id+16, false);
5826 if (return_bitset[id]) {
5827 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5829 return_bitset[id] = true;
5833 Session::mark_insert_id (uint32_t id)
5835 if (id >= insert_bitset.size()) {
5836 insert_bitset.resize (id+16, false);
5838 if (insert_bitset[id]) {
5839 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5841 insert_bitset[id] = true;
5845 Session::unmark_send_id (uint32_t id)
5847 if (id < send_bitset.size()) {
5848 send_bitset[id] = false;
5853 Session::unmark_aux_send_id (uint32_t id)
5855 if (id < aux_send_bitset.size()) {
5856 aux_send_bitset[id] = false;
5861 Session::unmark_return_id (uint32_t id)
5863 if (_state_of_the_state & Deletion) { return; }
5864 if (id < return_bitset.size()) {
5865 return_bitset[id] = false;
5870 Session::unmark_insert_id (uint32_t id)
5872 if (id < insert_bitset.size()) {
5873 insert_bitset[id] = false;
5878 Session::reset_native_file_format ()
5880 boost::shared_ptr<RouteList> rl = routes.reader ();
5882 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5883 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5885 /* don't save state as we do this, there's no point
5887 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5888 tr->reset_write_sources (false);
5889 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5895 Session::route_name_unique (string n) const
5897 boost::shared_ptr<RouteList> r = routes.reader ();
5899 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5900 if ((*i)->name() == n) {
5909 Session::route_name_internal (string n) const
5911 if (auditioner && auditioner->name() == n) {
5915 if (_click_io && _click_io->name() == n) {
5923 Session::freeze_all (InterThreadInfo& itt)
5925 boost::shared_ptr<RouteList> r = routes.reader ();
5927 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5929 boost::shared_ptr<Track> t;
5931 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5932 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5942 boost::shared_ptr<Region>
5943 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5944 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5945 InterThreadInfo& itt,
5946 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5947 bool for_export, bool for_freeze)
5949 boost::shared_ptr<Region> result;
5950 boost::shared_ptr<Playlist> playlist;
5951 boost::shared_ptr<Source> source;
5952 ChanCount diskstream_channels (track.n_channels());
5953 framepos_t position;
5954 framecnt_t this_chunk;
5956 framepos_t latency_skip;
5958 framepos_t len = end - start;
5959 bool need_block_size_reset = false;
5960 ChanCount const max_proc = track.max_processor_streams ();
5961 string legal_playlist_name;
5962 string possible_path;
5965 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5966 end, start) << endmsg;
5970 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5971 include_endpoint, for_export, for_freeze);
5973 if (diskstream_channels.n(track.data_type()) < 1) {
5974 error << _("Cannot write a range with no data.") << endmsg;
5978 // block all process callback handling
5980 block_processing ();
5983 // synchronize with AudioEngine::process_callback()
5984 // make sure processing is not currently running
5985 // and processing_blocked() is honored before
5986 // acquiring thread buffers
5987 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5990 _bounce_processing_active = true;
5992 /* call tree *MUST* hold route_lock */
5994 if ((playlist = track.playlist()) == 0) {
5998 legal_playlist_name = legalize_for_path (playlist->name());
6000 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
6002 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6003 string path = ((track.data_type() == DataType::AUDIO)
6004 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6005 : new_midi_source_path (legal_playlist_name));
6012 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6015 catch (failed_constructor& err) {
6016 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6020 srcs.push_back (source);
6023 /* tell redirects that care that we are about to use a much larger
6024 * blocksize. this will flush all plugins too, so that they are ready
6025 * to be used for this process.
6028 need_block_size_reset = true;
6029 track.set_block_size (bounce_chunk_size);
6030 _engine.main_thread()->get_buffers ();
6034 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6036 /* create a set of reasonably-sized buffers */
6037 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6038 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6040 buffers.set_count (max_proc);
6042 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6043 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6044 boost::shared_ptr<MidiSource> ms;
6046 afs->prepare_for_peakfile_writes ();
6047 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6048 Source::Lock lock(ms->mutex());
6049 ms->mark_streaming_write_started(lock);
6053 while (to_do && !itt.cancel) {
6055 this_chunk = min (to_do, bounce_chunk_size);
6057 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6061 start += this_chunk;
6062 to_do -= this_chunk;
6063 itt.progress = (float) (1.0 - ((double) to_do / len));
6065 if (latency_skip >= bounce_chunk_size) {
6066 latency_skip -= bounce_chunk_size;
6070 const framecnt_t current_chunk = this_chunk - latency_skip;
6073 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6074 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6075 boost::shared_ptr<MidiSource> ms;
6078 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6081 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6082 Source::Lock lock(ms->mutex());
6084 const MidiBuffer& buf = buffers.get_midi(0);
6085 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6086 Evoral::Event<framepos_t> ev = *i;
6087 ev.set_time(ev.time() - position);
6088 ms->append_event_frames(lock, ev, ms->timeline_position());
6095 /* post-roll, pick up delayed processor output */
6096 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6098 while (latency_skip && !itt.cancel) {
6099 this_chunk = min (latency_skip, bounce_chunk_size);
6100 latency_skip -= this_chunk;
6102 buffers.silence (this_chunk, 0);
6103 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6106 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6107 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6110 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6122 xnow = localtime (&now);
6124 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6125 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6126 boost::shared_ptr<MidiSource> ms;
6129 afs->update_header (position, *xnow, now);
6130 afs->flush_header ();
6131 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6132 Source::Lock lock(ms->mutex());
6133 ms->mark_streaming_write_completed(lock);
6137 /* construct a region to represent the bounced material */
6141 plist.add (Properties::start, 0);
6142 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6143 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6145 result = RegionFactory::create (srcs, plist);
6151 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6152 (*src)->mark_for_remove ();
6153 (*src)->drop_references ();
6157 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6158 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6161 afs->done_with_peakfile_writes ();
6165 _bounce_processing_active = false;
6167 if (need_block_size_reset) {
6168 _engine.main_thread()->drop_buffers ();
6169 track.set_block_size (get_block_size());
6172 unblock_processing ();
6178 Session::gain_automation_buffer() const
6180 return ProcessThread::gain_automation_buffer ();
6184 Session::trim_automation_buffer() const
6186 return ProcessThread::trim_automation_buffer ();
6190 Session::send_gain_automation_buffer() const
6192 return ProcessThread::send_gain_automation_buffer ();
6196 Session::pan_automation_buffer() const
6198 return ProcessThread::pan_automation_buffer ();
6202 Session::get_silent_buffers (ChanCount count)
6204 return ProcessThread::get_silent_buffers (count);
6208 Session::get_scratch_buffers (ChanCount count, bool silence)
6210 return ProcessThread::get_scratch_buffers (count, silence);
6214 Session::get_noinplace_buffers (ChanCount count)
6216 return ProcessThread::get_noinplace_buffers (count);
6220 Session::get_route_buffers (ChanCount count, bool silence)
6222 return ProcessThread::get_route_buffers (count, silence);
6227 Session::get_mix_buffers (ChanCount count)
6229 return ProcessThread::get_mix_buffers (count);
6233 Session::ntracks () const
6236 boost::shared_ptr<RouteList> r = routes.reader ();
6238 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6239 if (boost::dynamic_pointer_cast<Track> (*i)) {
6248 Session::nbusses () const
6251 boost::shared_ptr<RouteList> r = routes.reader ();
6253 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6254 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6263 Session::add_automation_list(AutomationList *al)
6265 automation_lists[al->id()] = al;
6268 /** @return true if there is at least one record-enabled track, otherwise false */
6270 Session::have_rec_enabled_track () const
6272 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6276 Session::have_rec_disabled_track () const
6278 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6281 /** Update the state of our rec-enabled tracks flag */
6283 Session::update_route_record_state ()
6285 boost::shared_ptr<RouteList> rl = routes.reader ();
6286 RouteList::iterator i = rl->begin();
6287 while (i != rl->end ()) {
6289 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6290 if (tr && tr->rec_enable_control()->get_value()) {
6297 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6299 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6301 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6302 RecordStateChanged (); /* EMIT SIGNAL */
6305 for (i = rl->begin(); i != rl->end (); ++i) {
6306 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6307 if (tr && !tr->rec_enable_control()->get_value()) {
6312 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6314 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6316 if (record_status() == Recording && record_arm_state_changed ) {
6317 RecordArmStateChanged ();
6323 Session::listen_position_changed ()
6325 ProcessorChangeBlocker pcb (this);
6326 boost::shared_ptr<RouteList> r = routes.reader ();
6327 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6328 (*i)->listen_position_changed ();
6333 Session::solo_control_mode_changed ()
6335 if (soloing() || listening()) {
6337 /* We can't use ::clear_all_solo_state() here because during
6338 session loading at program startup, that will queue a call
6339 to rt_clear_all_solo_state() that will not execute until
6340 AFTER solo states have been established (thus throwing away
6341 the session's saved solo state). So just explicitly turn
6344 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6346 clear_all_solo_state (get_routes());
6351 /** Called when a property of one of our route groups changes */
6353 Session::route_group_property_changed (RouteGroup* rg)
6355 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6358 /** Called when a route is added to one of our route groups */
6360 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6362 RouteAddedToRouteGroup (rg, r);
6365 /** Called when a route is removed from one of our route groups */
6367 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6369 update_route_record_state ();
6370 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6372 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6373 remove_route_group (*rg);
6377 boost::shared_ptr<RouteList>
6378 Session::get_tracks () const
6380 boost::shared_ptr<RouteList> rl = routes.reader ();
6381 boost::shared_ptr<RouteList> tl (new RouteList);
6383 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6384 if (boost::dynamic_pointer_cast<Track> (*r)) {
6385 if (!(*r)->is_auditioner()) {
6393 boost::shared_ptr<RouteList>
6394 Session::get_routes_with_regions_at (framepos_t const p) const
6396 boost::shared_ptr<RouteList> r = routes.reader ();
6397 boost::shared_ptr<RouteList> rl (new RouteList);
6399 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6400 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6405 boost::shared_ptr<Playlist> pl = tr->playlist ();
6410 if (pl->has_region_at (p)) {
6419 Session::goto_end ()
6421 if (_session_range_location) {
6422 request_locate (_session_range_location->end(), false);
6424 request_locate (0, false);
6429 Session::goto_start (bool and_roll)
6431 if (_session_range_location) {
6432 request_locate (_session_range_location->start(), and_roll);
6434 request_locate (0, and_roll);
6439 Session::current_start_frame () const
6441 return _session_range_location ? _session_range_location->start() : 0;
6445 Session::current_end_frame () const
6447 return _session_range_location ? _session_range_location->end() : 0;
6451 Session::set_session_range_location (framepos_t start, framepos_t end)
6453 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6454 _locations->add (_session_range_location);
6458 Session::step_edit_status_change (bool yn)
6464 send = (_step_editors == 0);
6469 send = (_step_editors == 1);
6472 if (_step_editors > 0) {
6478 StepEditStatusChange (val);
6484 Session::start_time_changed (framepos_t old)
6486 /* Update the auto loop range to match the session range
6487 (unless the auto loop range has been changed by the user)
6490 Location* s = _locations->session_range_location ();
6495 Location* l = _locations->auto_loop_location ();
6497 if (l && l->start() == old) {
6498 l->set_start (s->start(), true);
6504 Session::end_time_changed (framepos_t old)
6506 /* Update the auto loop range to match the session range
6507 (unless the auto loop range has been changed by the user)
6510 Location* s = _locations->session_range_location ();
6515 Location* l = _locations->auto_loop_location ();
6517 if (l && l->end() == old) {
6518 l->set_end (s->end(), true);
6523 std::vector<std::string>
6524 Session::source_search_path (DataType type) const
6528 if (session_dirs.size() == 1) {
6530 case DataType::AUDIO:
6531 sp.push_back (_session_dir->sound_path());
6533 case DataType::MIDI:
6534 sp.push_back (_session_dir->midi_path());
6538 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6539 SessionDirectory sdir (i->path);
6541 case DataType::AUDIO:
6542 sp.push_back (sdir.sound_path());
6544 case DataType::MIDI:
6545 sp.push_back (sdir.midi_path());
6551 if (type == DataType::AUDIO) {
6552 const string sound_path_2X = _session_dir->sound_path_2X();
6553 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6554 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6555 sp.push_back (sound_path_2X);
6560 // now check the explicit (possibly user-specified) search path
6563 case DataType::AUDIO:
6564 sp += Searchpath(config.get_audio_search_path ());
6566 case DataType::MIDI:
6567 sp += Searchpath(config.get_midi_search_path ());
6575 Session::ensure_search_path_includes (const string& path, DataType type)
6584 case DataType::AUDIO:
6585 sp += Searchpath(config.get_audio_search_path ());
6587 case DataType::MIDI:
6588 sp += Searchpath (config.get_midi_search_path ());
6592 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6593 /* No need to add this new directory if it has the same inode as
6594 an existing one; checking inode rather than name prevents duplicated
6595 directories when we are using symlinks.
6597 On Windows, I think we could just do if (*i == path) here.
6599 if (PBD::equivalent_paths (*i, path)) {
6607 case DataType::AUDIO:
6608 config.set_audio_search_path (sp.to_string());
6610 case DataType::MIDI:
6611 config.set_midi_search_path (sp.to_string());
6617 Session::remove_dir_from_search_path (const string& dir, DataType type)
6622 case DataType::AUDIO:
6623 sp = Searchpath(config.get_audio_search_path ());
6625 case DataType::MIDI:
6626 sp = Searchpath (config.get_midi_search_path ());
6633 case DataType::AUDIO:
6634 config.set_audio_search_path (sp.to_string());
6636 case DataType::MIDI:
6637 config.set_midi_search_path (sp.to_string());
6643 boost::shared_ptr<Speakers>
6644 Session::get_speakers()
6650 Session::unknown_processors () const
6654 boost::shared_ptr<RouteList> r = routes.reader ();
6655 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6656 list<string> t = (*i)->unknown_processors ();
6657 copy (t.begin(), t.end(), back_inserter (p));
6667 Session::update_latency (bool playback)
6670 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6672 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6676 boost::shared_ptr<RouteList> r = routes.reader ();
6677 framecnt_t max_latency = 0;
6680 /* reverse the list so that we work backwards from the last route to run to the first */
6681 RouteList* rl = routes.reader().get();
6682 r.reset (new RouteList (*rl));
6683 reverse (r->begin(), r->end());
6686 /* compute actual latency values for the given direction and store them all in per-port
6687 structures. this will also publish the same values (to JACK) so that computation of latency
6688 for routes can consistently use public latency values.
6691 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6692 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6695 /* because we latency compensate playback, our published playback latencies should
6696 be the same for all output ports - all material played back by ardour has
6697 the same latency, whether its caused by plugins or by latency compensation. since
6698 these may differ from the values computed above, reset all playback port latencies
6702 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6704 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6705 (*i)->set_public_port_latencies (max_latency, playback);
6710 post_playback_latency ();
6714 post_capture_latency ();
6717 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6721 Session::post_playback_latency ()
6723 set_worst_playback_latency ();
6725 boost::shared_ptr<RouteList> r = routes.reader ();
6727 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6728 if (!(*i)->is_auditioner() && ((*i)->active())) {
6729 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6733 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6734 (*i)->set_latency_compensation (_worst_track_latency);
6739 Session::post_capture_latency ()
6741 set_worst_capture_latency ();
6743 /* reflect any changes in capture latencies into capture offsets
6746 boost::shared_ptr<RouteList> rl = routes.reader();
6747 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6748 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6750 tr->set_capture_offset ();
6756 Session::initialize_latencies ()
6759 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6760 update_latency (false);
6761 update_latency (true);
6764 set_worst_io_latencies ();
6768 Session::set_worst_io_latencies ()
6770 set_worst_playback_latency ();
6771 set_worst_capture_latency ();
6775 Session::set_worst_playback_latency ()
6777 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6781 _worst_output_latency = 0;
6783 if (!_engine.connected()) {
6787 boost::shared_ptr<RouteList> r = routes.reader ();
6789 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6790 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6793 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6797 Session::set_worst_capture_latency ()
6799 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6803 _worst_input_latency = 0;
6805 if (!_engine.connected()) {
6809 boost::shared_ptr<RouteList> r = routes.reader ();
6811 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6812 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6815 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6819 Session::update_latency_compensation (bool force_whole_graph)
6821 bool some_track_latency_changed = false;
6823 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6827 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6829 _worst_track_latency = 0;
6831 boost::shared_ptr<RouteList> r = routes.reader ();
6833 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6834 if (!(*i)->is_auditioner() && ((*i)->active())) {
6836 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6837 some_track_latency_changed = true;
6839 _worst_track_latency = max (tl, _worst_track_latency);
6843 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6844 (some_track_latency_changed ? "yes" : "no")));
6846 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6848 if (some_track_latency_changed || force_whole_graph) {
6849 _engine.update_latencies ();
6853 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6854 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6858 tr->set_capture_offset ();
6863 Session::session_name_is_legal (const string& path)
6865 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6867 for (int i = 0; illegal_chars[i]; ++i) {
6868 if (path.find (illegal_chars[i]) != string::npos) {
6869 return illegal_chars[i];
6877 Session::notify_presentation_info_change ()
6879 if (deletion_in_progress()) {
6883 reassign_track_numbers();
6885 #ifdef USE_TRACKS_CODE_FEATURES
6886 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6887 * if track order has been changed by user
6889 reconnect_existing_routes(true, true);
6895 Session::operation_in_progress (GQuark op) const
6897 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6900 boost::shared_ptr<Port>
6901 Session::ltc_input_port () const
6903 return _ltc_input->nth (0);
6906 boost::shared_ptr<Port>
6907 Session::ltc_output_port () const
6909 return _ltc_output->nth (0);
6913 Session::reconnect_ltc_input ()
6917 string src = Config->get_ltc_source_port();
6919 _ltc_input->disconnect (this);
6921 if (src != _("None") && !src.empty()) {
6922 _ltc_input->nth (0)->connect (src);
6925 if ( ARDOUR::Profile->get_trx () ) {
6926 // Tracks need this signal to update timecode_source_dropdown
6927 MtcOrLtcInputPortChanged (); //emit signal
6933 Session::reconnect_ltc_output ()
6937 string src = Config->get_ltc_output_port();
6939 _ltc_output->disconnect (this);
6941 if (src != _("None") && !src.empty()) {
6942 _ltc_output->nth (0)->connect (src);
6948 Session::set_range_selection (framepos_t start, framepos_t end)
6950 _range_selection = Evoral::Range<framepos_t> (start, end);
6951 #ifdef USE_TRACKS_CODE_FEATURES
6952 follow_playhead_priority ();
6957 Session::set_object_selection (framepos_t start, framepos_t end)
6959 _object_selection = Evoral::Range<framepos_t> (start, end);
6960 #ifdef USE_TRACKS_CODE_FEATURES
6961 follow_playhead_priority ();
6966 Session::clear_range_selection ()
6968 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6969 #ifdef USE_TRACKS_CODE_FEATURES
6970 follow_playhead_priority ();
6975 Session::clear_object_selection ()
6977 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6978 #ifdef USE_TRACKS_CODE_FEATURES
6979 follow_playhead_priority ();
6984 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6985 const ChanCount& input_start,
6986 const ChanCount& output_start,
6987 const ChanCount& input_offset,
6988 const ChanCount& output_offset)
6990 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6991 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6992 input_start, output_start,
6993 input_offset, output_offset));
6995 auto_connect_thread_wakeup ();
6999 Session::auto_connect_thread_wakeup ()
7001 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7002 pthread_cond_signal (&_auto_connect_cond);
7003 pthread_mutex_unlock (&_auto_connect_mutex);
7008 Session::queue_latency_recompute ()
7010 g_atomic_int_inc (&_latency_recompute_pending);
7011 auto_connect_thread_wakeup ();
7015 Session::auto_connect (const AutoConnectRequest& ar)
7017 boost::shared_ptr<Route> route = ar.route.lock();
7019 if (!route) { return; }
7021 if (!IO::connecting_legal) {
7025 /* If both inputs and outputs are auto-connected to physical ports,
7026 * use the max of input and output offsets to ensure auto-connected
7027 * port numbers always match up (e.g. the first audio input and the
7028 * first audio output of the route will have the same physical
7029 * port number). Otherwise just use the lowest input or output
7033 const bool in_out_physical =
7034 (Config->get_input_auto_connect() & AutoConnectPhysical)
7035 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7036 && ar.connect_inputs;
7038 const ChanCount in_offset = in_out_physical
7039 ? ChanCount::max(ar.input_offset, ar.output_offset)
7042 const ChanCount out_offset = in_out_physical
7043 ? ChanCount::max(ar.input_offset, ar.output_offset)
7046 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7047 vector<string> physinputs;
7048 vector<string> physoutputs;
7051 /* for connecting track inputs we only want MIDI ports marked
7055 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7057 if (!physinputs.empty() && ar.connect_inputs) {
7058 uint32_t nphysical_in = physinputs.size();
7060 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7063 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7064 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7067 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7073 if (!physoutputs.empty()) {
7074 uint32_t nphysical_out = physoutputs.size();
7075 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7079 * do not create new connections if we reached the limit of physical outputs
7082 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7083 ARDOUR::Profile->get_trx () &&
7084 ar.output_offset.get(*t) == nphysical_out ) {
7088 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7089 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7090 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7091 /* master bus is audio only */
7092 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7093 port = _master_out->input()->ports().port(*t,
7094 i % _master_out->input()->n_ports().get(*t))->name();
7098 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7107 Session::auto_connect_thread_start ()
7109 if (g_atomic_int_get (&_ac_thread_active)) {
7113 while (!_auto_connect_queue.empty ()) {
7114 _auto_connect_queue.pop ();
7117 g_atomic_int_set (&_ac_thread_active, 1);
7118 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7119 g_atomic_int_set (&_ac_thread_active, 0);
7124 Session::auto_connect_thread_terminate ()
7126 if (!g_atomic_int_get (&_ac_thread_active)) {
7131 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7132 while (!_auto_connect_queue.empty ()) {
7133 _auto_connect_queue.pop ();
7137 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7138 * fail to wakeup the thread.
7141 pthread_mutex_lock (&_auto_connect_mutex);
7142 g_atomic_int_set (&_ac_thread_active, 0);
7143 pthread_cond_signal (&_auto_connect_cond);
7144 pthread_mutex_unlock (&_auto_connect_mutex);
7147 pthread_join (_auto_connect_thread, &status);
7151 Session::auto_connect_thread (void *arg)
7153 Session *s = static_cast<Session *>(arg);
7154 s->auto_connect_thread_run ();
7160 Session::auto_connect_thread_run ()
7162 pthread_set_name (X_("autoconnect"));
7163 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7164 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7165 pthread_mutex_lock (&_auto_connect_mutex);
7166 while (g_atomic_int_get (&_ac_thread_active)) {
7168 if (!_auto_connect_queue.empty ()) {
7169 // Why would we need the process lock ??
7170 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7171 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7172 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7173 // We have control over those, but what does jack do?
7174 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7176 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7177 while (!_auto_connect_queue.empty ()) {
7178 const AutoConnectRequest ar (_auto_connect_queue.front());
7179 _auto_connect_queue.pop ();
7186 if (!actively_recording ()) { // might not be needed,
7187 /* this is only used for updating plugin latencies, the
7188 * graph does not change. so it's safe in general.
7190 * .. update_latency_compensation () entails set_capture_offset()
7191 * which calls Diskstream::set_capture_offset () which
7192 * modifies the capture offset... which can be a proplem
7193 * in "prepare_to_stop"
7195 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7196 update_latency_compensation ();
7201 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7202 // jack1 cannot cope with removing ports while processing
7203 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7204 AudioEngine::instance()->clear_pending_port_deletions ();
7207 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7209 pthread_mutex_unlock (&_auto_connect_mutex);
7213 Session::cancel_all_solo ()
7217 get_stripables (sl);
7219 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7220 clear_all_solo_state (routes.reader());