2 * Copyright (C) 1999-2019 Paul Davis <paul@linuxaudiosystems.com>
3 * Copyright (C) 2006-2007 Jesse Chappell <jesse@essej.net>
4 * Copyright (C) 2006-2009 Sampo Savolainen <v2@iki.fi>
5 * Copyright (C) 2006-2015 David Robillard <d@drobilla.net>
6 * Copyright (C) 2006-2016 Tim Mayberry <mojofunk@gmail.com>
7 * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
8 * Copyright (C) 2008-2009 Hans Baier <hansfbaier@googlemail.com>
9 * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
10 * Copyright (C) 2013-2017 Nick Mainsbridge <mainsbridge@gmail.com>
11 * Copyright (C) 2014-2019 Ben Loftis <ben@harrisonconsoles.com>
12 * Copyright (C) 2015 GZharun <grygoriiz@wavesglobal.com>
13 * Copyright (C) 2016-2018 Len Ovens <len@ovenwerks.net>
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License along
26 * with this program; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
36 #include <cstdio> /* sprintf(3) ... grrr */
42 #include <glibmm/threads.h>
43 #include <glibmm/miscutils.h>
44 #include <glibmm/fileutils.h>
46 #include <boost/algorithm/string/erase.hpp>
48 #include "pbd/basename.h"
49 #include "pbd/convert.h"
50 #include "pbd/error.h"
51 #include "pbd/file_utils.h"
54 #include "pbd/pthread_utils.h"
55 #include "pbd/search_path.h"
56 #include "pbd/stacktrace.h"
57 #include "pbd/stl_delete.h"
58 #include "pbd/replace_all.h"
59 #include "pbd/types_convert.h"
60 #include "pbd/unwind.h"
62 #include "ardour/amp.h"
63 #include "ardour/analyser.h"
64 #include "ardour/async_midi_port.h"
65 #include "ardour/audio_buffer.h"
66 #include "ardour/audio_port.h"
67 #include "ardour/audio_track.h"
68 #include "ardour/audioengine.h"
69 #include "ardour/audiofilesource.h"
70 #include "ardour/auditioner.h"
71 #include "ardour/boost_debug.h"
72 #include "ardour/buffer_manager.h"
73 #include "ardour/buffer_set.h"
74 #include "ardour/bundle.h"
75 #include "ardour/butler.h"
76 #include "ardour/click.h"
77 #include "ardour/control_protocol_manager.h"
78 #include "ardour/data_type.h"
79 #include "ardour/debug.h"
80 #include "ardour/disk_reader.h"
81 #include "ardour/directory_names.h"
82 #include "ardour/filename_extensions.h"
83 #include "ardour/gain_control.h"
84 #include "ardour/graph.h"
85 #include "ardour/luabindings.h"
86 #include "ardour/midiport_manager.h"
87 #include "ardour/scene_changer.h"
88 #include "ardour/midi_patch_manager.h"
89 #include "ardour/midi_track.h"
90 #include "ardour/midi_ui.h"
91 #include "ardour/operations.h"
92 #include "ardour/playlist.h"
93 #include "ardour/playlist_factory.h"
94 #include "ardour/plugin.h"
95 #include "ardour/plugin_insert.h"
96 #include "ardour/process_thread.h"
97 #include "ardour/profile.h"
98 #include "ardour/rc_configuration.h"
99 #include "ardour/recent_sessions.h"
100 #include "ardour/region.h"
101 #include "ardour/region_factory.h"
102 #include "ardour/revision.h"
103 #include "ardour/route_graph.h"
104 #include "ardour/route_group.h"
105 #include "ardour/rt_tasklist.h"
106 #include "ardour/send.h"
107 #include "ardour/selection.h"
108 #include "ardour/session.h"
109 #include "ardour/session_directory.h"
110 #include "ardour/session_playlists.h"
111 #include "ardour/smf_source.h"
112 #include "ardour/solo_isolate_control.h"
113 #include "ardour/source_factory.h"
114 #include "ardour/speakers.h"
115 #include "ardour/tempo.h"
116 #include "ardour/ticker.h"
117 #include "ardour/transport_fsm.h"
118 #include "ardour/transport_master.h"
119 #include "ardour/transport_master_manager.h"
120 #include "ardour/track.h"
121 #include "ardour/types_convert.h"
122 #include "ardour/user_bundle.h"
123 #include "ardour/utils.h"
124 #include "ardour/vca_manager.h"
125 #include "ardour/vca.h"
127 #include "midi++/port.h"
128 #include "midi++/mmc.h"
130 #include "LuaBridge/LuaBridge.h"
132 #include <glibmm/checksum.h>
141 using namespace ARDOUR;
144 bool Session::_disable_all_loaded_plugins = false;
145 bool Session::_bypass_all_loaded_plugins = false;
146 guint Session::_name_id_counter = 0;
148 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
149 PBD::Signal1<void,std::string> Session::Dialog;
150 PBD::Signal0<int> Session::AskAboutPendingState;
151 PBD::Signal2<int, samplecnt_t, samplecnt_t> Session::AskAboutSampleRateMismatch;
152 PBD::Signal2<void, samplecnt_t, samplecnt_t> Session::NotifyAboutSampleRateMismatch;
153 PBD::Signal0<void> Session::SendFeedback;
154 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
156 PBD::Signal1<void, samplepos_t> Session::StartTimeChanged;
157 PBD::Signal1<void, samplepos_t> Session::EndTimeChanged;
158 PBD::Signal2<void,std::string, std::string> Session::Exported;
159 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
160 PBD::Signal0<void> Session::Quit;
161 PBD::Signal0<void> Session::FeedbackDetected;
162 PBD::Signal0<void> Session::SuccessfulGraphSort;
163 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
165 const samplecnt_t Session::bounce_chunk_size = 8192;
166 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
167 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
168 const uint32_t Session::session_end_shift = 0;
170 /** @param snapshot_name Snapshot name, without .ardour suffix */
171 Session::Session (AudioEngine &eng,
172 const string& fullpath,
173 const string& snapshot_name,
174 BusProfile* bus_profile,
176 : _playlists (new SessionPlaylists)
178 , process_function (&Session::process_with_events)
179 , _bounce_processing_active (false)
180 , waiting_for_sync_offset (false)
181 , _base_sample_rate (0)
182 , _nominal_sample_rate (0)
183 , _current_sample_rate (0)
184 , _record_status (Disabled)
185 , _transport_sample (0)
187 , _session_range_location (0)
188 , _session_range_is_free (true)
190 , _remaining_latency_preroll (0)
191 , _engine_speed (1.0)
192 , _transport_speed (0)
193 , _default_transport_speed (1.0)
194 , _last_transport_speed (0)
195 , _signalled_varispeed (0)
196 , _target_transport_speed (0.0)
197 , auto_play_legal (false)
198 , _requested_return_sample (-1)
199 , current_block_size (0)
200 , _worst_output_latency (0)
201 , _worst_input_latency (0)
202 , _worst_route_latency (0)
203 , _send_latency_changes (0)
204 , _have_captured (false)
205 , _non_soloed_outs_muted (false)
208 , _solo_isolated_cnt (0)
210 , _was_seamless (Config->get_seamless_loop ())
211 , _under_nsm_control (false)
213 , transport_master_tracking_state (Stopped)
214 , master_wait_end (0)
215 , post_export_sync (false)
216 , post_export_position (0)
218 , _export_rolling (false)
219 , _realtime_export (false)
220 , _region_export (false)
221 , _export_preroll (0)
222 , _pre_export_mmc_enabled (false)
223 , _name (snapshot_name)
225 , _send_qf_mtc (false)
226 , _pframes_since_last_mtc (0)
228 , loop_changing (false)
230 , _session_dir (new SessionDirectory (fullpath))
231 , _current_snapshot_name (snapshot_name)
233 , state_was_pending (false)
234 , _state_of_the_state (StateOfTheState (CannotSave | InitialConnecting | Loading))
236 , _save_queued (false)
237 , _last_roll_location (0)
238 , _last_roll_or_reversal_location (0)
239 , _last_record_location (0)
240 , pending_auto_loop (false)
241 , _mempool ("Session", 3145728)
242 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
244 , _butler (new Butler (*this))
245 , _transport_fsm (new TransportFSM (*this))
246 , _post_transport_work (0)
247 , _locations (new Locations (*this))
248 , _ignore_skips_updates (false)
249 , _rt_thread_active (false)
250 , _rt_emit_pending (false)
251 , _ac_thread_active (0)
252 , _latency_recompute_pending (0)
254 , outbound_mtc_timecode_frame (0)
255 , next_quarter_frame_to_send (-1)
256 , _samples_per_timecode_frame (0)
257 , _frames_per_hour (0)
258 , _timecode_frames_per_hour (0)
259 , last_timecode_valid (false)
260 , last_timecode_when (0)
261 , _send_timecode_update (false)
273 , ltc_timecode_offset (0)
274 , ltc_timecode_negative_offset (false)
275 , midi_control_ui (0)
277 , _all_route_group (new RouteGroup (*this, "all"))
278 , routes (new RouteList)
279 , _adding_routes_in_progress (false)
280 , _reconnecting_routes_in_progress (false)
281 , _route_deletion_in_progress (false)
282 , destructive_index (0)
283 , _track_number_decimals(1)
284 , default_fade_steepness (0)
285 , default_fade_msecs (0)
286 , _total_free_4k_blocks (0)
287 , _total_free_4k_blocks_uncertain (false)
288 , no_questions_about_missing_files (false)
291 , _bundles (new BundleList)
292 , _bundle_xml_node (0)
295 , _click_rec_only (false)
297 , click_emphasis_data (0)
299 , click_emphasis_length (0)
300 , _clicks_cleared (0)
301 , _count_in_samples (0)
302 , _play_range (false)
303 , _range_selection (-1,-1)
304 , _object_selection (-1,-1)
305 , _preroll_record_trim_len (0)
306 , _count_in_once (false)
308 , first_file_data_format_reset (true)
309 , first_file_header_format_reset (true)
310 , have_looped (false)
311 , _have_rec_enabled_track (false)
312 , _have_rec_disabled_track (true)
314 , _suspend_timecode_transmission (0)
315 , _speakers (new Speakers)
316 , _ignore_route_processor_changes (0)
321 , _vca_manager (new VCAManager (*this))
322 , _selection (new CoreSelection (*this))
323 , _global_locate_pending (false)
327 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
329 pthread_mutex_init (&_rt_emit_mutex, 0);
330 pthread_cond_init (&_rt_emit_cond, 0);
332 pthread_mutex_init (&_auto_connect_mutex, 0);
333 pthread_cond_init (&_auto_connect_cond, 0);
335 init_name_id_counter (1); // reset for new sessions, start at 1
336 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
338 pre_engine_init (fullpath); // sets _is_new
344 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
346 if (ensure_engine (sr, true)) {
348 throw SessionException (_("Cannot connect to audio/midi engine"));
351 // set samplerate for plugins added early
352 // e.g from templates or MB channelstrip
353 set_block_size (_engine.samples_per_cycle());
354 set_sample_rate (_engine.sample_rate());
356 if (create (mix_template, bus_profile)) {
358 throw SessionException (_("Session initialization failed"));
361 /* if a mix template was provided, then ::create() will
362 * have copied it into the session and we need to load it
363 * so that we have the state ready for ::set_state()
364 * after the engine is started.
366 * Note that we do NOT try to get the sample rate from
367 * the template at this time, though doing so would
368 * be easy if we decided this was an appropriate part
372 if (!mix_template.empty()) {
374 if (load_state (_current_snapshot_name)) {
375 throw SessionException (_("Failed to load template/snapshot state"));
377 } catch (PBD::unknown_enumeration& e) {
378 throw SessionException (_("Failed to parse 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 int err = post_engine_init ();
416 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
420 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
423 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
426 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
429 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Unexpected exception during session setup, possibly invalid audio/midi engine parameters. Please see stdout/stderr for details")));
434 store_recent_sessions (_name, _path);
436 bool was_dirty = dirty();
439 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
441 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
442 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
445 DirtyChanged (); /* EMIT SIGNAL */
448 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
449 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
451 LatentSend::ChangedLatency.connect_same_thread (*this, boost::bind (&Session::send_latency_compensation_change, this));
453 emit_thread_start ();
454 auto_connect_thread_start ();
456 /* hook us up to the engine since we are now completely constructed */
458 BootMessage (_("Connect to engine"));
460 _engine.set_session (this);
461 _engine.reset_timebase ();
463 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
465 if (!mix_template.empty ()) {
466 /* ::create() unsets _is_new after creating the session.
467 * But for templated sessions, the sample-rate is initially unset
468 * (not read from template), so we need to save it (again).
476 BootMessage (_("Session loading complete"));
488 Session::next_name_id ()
490 return g_atomic_int_add (&_name_id_counter, 1);
494 Session::name_id_counter ()
496 return g_atomic_int_get (&_name_id_counter);
500 Session::init_name_id_counter (guint n)
502 g_atomic_int_set (&_name_id_counter, n);
506 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
508 if (_engine.current_backend() == 0) {
509 /* backend is unknown ... */
510 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
511 if (r.get_value_or (-1) != 0) {
514 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
516 } else if (_engine.setup_required()) {
517 /* backend is known, but setup is needed */
518 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
519 if (r.get_value_or (-1) != 0) {
522 } else if (!_engine.running()) {
523 if (_engine.start()) {
528 /* at this point the engine should be running */
530 if (!_engine.running()) {
534 return immediately_post_engine ();
539 Session::immediately_post_engine ()
541 /* Do various initializations that should take place directly after we
542 * know that the engine is running, but before we either create a
543 * session or set state for an existing one.
546 _rt_tasklist.reset (new RTTaskList ());
548 if (how_many_dsp_threads () > 1) {
549 /* For now, only create the graph if we are using >1 DSP threads, as
550 it is a bit slower than the old code with 1 thread.
552 _process_graph.reset (new Graph (*this));
555 /* Restart transport FSM */
557 _transport_fsm->start ();
559 /* every time we reconnect, do stuff ... */
561 _engine.Running.connect_same_thread (*this, boost::bind (&Session::engine_running, this));
563 if (synced_to_engine()) {
564 _engine.transport_stop ();
567 if (config.get_jack_time_master()) {
568 _engine.transport_locate (_transport_sample);
572 BootMessage (_("Set up LTC"));
574 BootMessage (_("Set up Click"));
576 BootMessage (_("Set up standard connections"));
580 catch (failed_constructor& err) {
584 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
586 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
594 vector<void*> debug_pointers;
596 /* if we got to here, leaving pending capture state around
600 remove_pending_capture_state ();
604 _state_of_the_state = StateOfTheState (CannotSave | Deletion);
607 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
611 /* disconnect from any and all signals that we are connected to */
613 Port::PortSignalDrop (); /* EMIT SIGNAL */
616 /* shutdown control surface protocols while we still have ports
617 * and the engine to move data to any devices.
620 /* remove I/O objects before unsetting the engine session */
622 _ltc_output.reset ();
624 ControlProtocolManager::instance().drop_protocols ();
626 /* stop auto dis/connecting */
627 auto_connect_thread_terminate ();
629 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
631 _engine.remove_session ();
633 /* deregister all ports - there will be no process or any other
634 * callbacks from the engine any more.
637 Port::PortDrop (); /* EMIT SIGNAL */
640 Glib::Threads::Mutex::Lock lm (controllables_lock);
641 for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
642 (*i)->DropReferences (); /* EMIT SIGNAL */
644 controllables.clear ();
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 */
657 /* unregister all lua functions, drop held references (if any) */
658 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
660 lua.do_command ("Session = nil");
668 lua.collect_garbage ();
671 /* reset dynamic state version back to default */
672 Stateful::loading_state_version = 0;
674 _butler->drop_references ();
678 delete _all_route_group;
680 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
681 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
685 if (click_data != default_click) {
686 delete [] click_data;
689 if (click_emphasis_data != default_click_emphasis) {
690 delete [] click_emphasis_data;
695 /* need to remove auditioner before monitoring section
696 * otherwise it is re-connected.
697 * Note: If a session was never successfully loaded, there
698 * may not yet be an auditioner.
701 auditioner->drop_references ();
705 /* drop references to routes held by the monitoring section
706 * specifically _monitor_out aux/listen references */
707 remove_monitor_section();
709 /* clear out any pending dead wood from RCU managed objects */
714 DiskReader::free_working_buffers();
716 /* tell everyone who is still standing that we're about to die */
719 /* tell everyone to drop references and delete objects as we go */
721 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
722 RegionFactory::delete_all_regions ();
724 /* Do this early so that VCAs no longer hold references to routes */
726 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
729 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
731 /* reset these three references to special routes before we do the usual route delete thing */
733 _master_out.reset ();
734 _monitor_out.reset ();
737 RCUWriter<RouteList> writer (routes);
738 boost::shared_ptr<RouteList> r = writer.get_copy ();
740 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
741 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
742 (*i)->drop_references ();
746 /* writer goes out of scope and updates master */
751 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
752 Glib::Threads::Mutex::Lock lm (source_lock);
753 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
754 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
755 i->second->drop_references ();
761 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
764 emit_thread_terminate ();
766 pthread_cond_destroy (&_rt_emit_cond);
767 pthread_mutex_destroy (&_rt_emit_mutex);
769 pthread_cond_destroy (&_auto_connect_cond);
770 pthread_mutex_destroy (&_auto_connect_mutex);
772 delete _scene_changer; _scene_changer = 0;
773 delete midi_control_ui; midi_control_ui = 0;
775 delete _mmc; _mmc = 0;
776 delete _midi_ports; _midi_ports = 0;
777 delete _locations; _locations = 0;
782 /* clear event queue, the session is gone, nobody is interested in
783 * those anymore, but they do leak memory if not removed
785 while (!immediate_events.empty ()) {
786 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
787 SessionEvent *ev = immediate_events.front ();
788 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
789 immediate_events.pop_front ();
793 case SessionEvent::AutoLoop:
794 case SessionEvent::Skip:
795 case SessionEvent::PunchIn:
796 case SessionEvent::PunchOut:
797 case SessionEvent::RangeStop:
798 case SessionEvent::RangeLocate:
802 case SessionEvent::RealTimeOperation:
809 del = del && !_remove_event (ev);
817 /* unregister all dropped ports, process pending port deletion. */
818 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
819 // jack1 cannot cope with removing ports while processing
820 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
821 AudioEngine::instance()->clear_pending_port_deletions ();
824 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
828 _transport_fsm->stop ();
830 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
833 Controllable::dump_registry ();
836 BOOST_SHOW_POINTERS ();
840 Session::setup_ltc ()
844 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
846 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
847 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
850 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
851 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
852 // TODO use auto-connect thread
853 reconnect_ltc_output ();
857 /* fix up names of LTC ports because we don't want the normal
858 * IO style of NAME/TYPE-{in,out}N
861 _ltc_output->nth (0)->set_name (X_("LTC-out"));
865 Session::setup_click ()
869 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
870 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
872 _click_io.reset (new ClickIO (*this, X_("Click")));
873 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
874 _click_gain->activate ();
876 setup_click_state (state_tree->root());
878 setup_click_state (0);
883 Session::setup_click_state (const XMLNode* node)
885 const XMLNode* child = 0;
887 if (node && (child = find_named_node (*node, "Click")) != 0) {
889 /* existing state for Click */
892 if (Stateful::loading_state_version < 3000) {
893 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
895 const XMLNodeList& children (child->children());
896 XMLNodeList::const_iterator i = children.begin();
897 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
899 if (i != children.end()) {
900 c = _click_gain->set_state (**i, Stateful::loading_state_version);
906 _clicking = Config->get_clicking ();
910 error << _("could not setup Click I/O") << endmsg;
917 /* default state for Click: dual-mono to first 2 physical outputs */
920 _engine.get_physical_outputs (DataType::AUDIO, outs);
922 for (uint32_t physport = 0; physport < 2; ++physport) {
923 if (outs.size() > physport) {
924 if (_click_io->add_port (outs[physport], this)) {
925 // relax, even though its an error
930 if (_click_io->n_ports () > ChanCount::ZERO) {
931 _clicking = Config->get_clicking ();
937 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
938 MidiPortFlags include, MidiPortFlags exclude)
940 _engine.get_physical_inputs (type, inputs, include, exclude);
941 _engine.get_physical_outputs (type, outputs, include, exclude);
946 Session::auto_connect_master_bus ()
948 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
952 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
953 // In this case it means "Multi Out" output mode
954 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
958 /* if requested auto-connect the outputs to the first N physical ports.
961 uint32_t limit = _master_out->n_outputs().n_total();
962 vector<string> outputs[DataType::num_types];
964 for (uint32_t i = 0; i < DataType::num_types; ++i) {
965 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
968 for (uint32_t n = 0; n < limit; ++n) {
969 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
971 if (outputs[p->type()].size() > n) {
972 connect_to = outputs[p->type()][n];
975 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
976 if (_master_out->output()->connect (p, connect_to, this)) {
977 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
986 Session::remove_monitor_section ()
988 if (!_monitor_out || Profile->get_trx()) {
992 /* allow deletion when session is unloaded */
993 if (!_engine.running() && !deletion_in_progress ()) {
994 error << _("Cannot remove monitor section while the engine is offline.") << endmsg;
998 /* force reversion to Solo-In-Place */
999 Config->set_solo_control_is_listen_control (false);
1001 /* if we are auditioning, cancel it ... this is a workaround
1002 to a problem (auditioning does not execute the process graph,
1003 which is needed to remove routes when using >1 core for processing)
1007 if (!deletion_in_progress ()) {
1008 /* Hold process lock while doing this so that we don't hear bits and
1009 * pieces of audio as we work on each route.
1012 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1014 /* Connect tracks to monitor section. Note that in an
1015 existing session, the internal sends will already exist, but we want the
1016 routes to notice that they connect to the control out specifically.
1020 boost::shared_ptr<RouteList> r = routes.reader ();
1021 ProcessorChangeBlocker pcb (this, false);
1023 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1025 if ((*x)->is_monitor()) {
1027 } else if ((*x)->is_master()) {
1030 (*x)->remove_aux_or_listen (_monitor_out);
1035 remove_route (_monitor_out);
1036 if (deletion_in_progress ()) {
1040 auto_connect_master_bus ();
1043 auditioner->connect ();
1046 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1050 Session::add_monitor_section ()
1054 if (!_engine.running()) {
1055 error << _("Cannot create monitor section while the engine is offline.") << endmsg;
1059 if (_monitor_out || !_master_out || Profile->get_trx()) {
1063 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1069 BOOST_MARK_ROUTE(r);
1072 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1073 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1074 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1076 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1081 add_routes (rl, false, false, false, 0);
1083 assert (_monitor_out);
1085 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1086 are undefined, at best.
1089 uint32_t limit = _monitor_out->n_inputs().n_audio();
1093 /* connect the inputs to the master bus outputs. this
1094 * represents a separate data feed from the internal sends from
1095 * each route. as of jan 2011, it allows the monitor section to
1096 * conditionally ignore either the internal sends or the normal
1097 * input feed, but we should really find a better way to do
1101 _master_out->output()->disconnect (this);
1103 for (uint32_t n = 0; n < limit; ++n) {
1104 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1105 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1108 string connect_to = o->name();
1109 if (_monitor_out->input()->connect (p, connect_to, this)) {
1110 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1118 /* if monitor section is not connected, connect it to physical outs
1121 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1123 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1125 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1128 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1130 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1131 Config->get_monitor_bus_preferred_bundle())
1137 /* Monitor bus is audio only */
1139 vector<string> outputs[DataType::num_types];
1141 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1142 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1145 uint32_t mod = outputs[DataType::AUDIO].size();
1146 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1150 for (uint32_t n = 0; n < limit; ++n) {
1152 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1154 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1155 connect_to = outputs[DataType::AUDIO][n % mod];
1158 if (!connect_to.empty()) {
1159 if (_monitor_out->output()->connect (p, connect_to, this)) {
1160 error << string_compose (
1161 _("cannot connect control output %1 to %2"),
1172 /* Hold process lock while doing this so that we don't hear bits and
1173 * pieces of audio as we work on each route.
1176 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1178 /* Connect tracks to monitor section. Note that in an
1179 existing session, the internal sends will already exist, but we want the
1180 routes to notice that they connect to the control out specifically.
1184 boost::shared_ptr<RouteList> rls = routes.reader ();
1186 ProcessorChangeBlocker pcb (this, false /* XXX */);
1188 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1190 if ((*x)->is_monitor()) {
1192 } else if ((*x)->is_master()) {
1195 (*x)->enable_monitor_send ();
1200 auditioner->connect ();
1203 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1207 Session::reset_monitor_section ()
1209 /* Process lock should be held by the caller.*/
1211 if (!_monitor_out || Profile->get_trx()) {
1215 uint32_t limit = _master_out->n_outputs().n_audio();
1217 /* connect the inputs to the master bus outputs. this
1218 * represents a separate data feed from the internal sends from
1219 * each route. as of jan 2011, it allows the monitor section to
1220 * conditionally ignore either the internal sends or the normal
1221 * input feed, but we should really find a better way to do
1225 _master_out->output()->disconnect (this);
1226 _monitor_out->output()->disconnect (this);
1228 // monitor section follow master bus - except midi
1229 ChanCount mon_chn (_master_out->output()->n_ports());
1230 mon_chn.set_midi (0);
1232 _monitor_out->input()->ensure_io (mon_chn, false, this);
1233 _monitor_out->output()->ensure_io (mon_chn, false, this);
1235 for (uint32_t n = 0; n < limit; ++n) {
1236 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1237 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1240 string connect_to = o->name();
1241 if (_monitor_out->input()->connect (p, connect_to, this)) {
1242 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1249 /* connect monitor section to physical outs
1252 if (Config->get_auto_connect_standard_busses()) {
1254 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1256 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1259 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1261 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1262 Config->get_monitor_bus_preferred_bundle())
1268 /* Monitor bus is audio only */
1270 vector<string> outputs[DataType::num_types];
1272 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1273 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1276 uint32_t mod = outputs[DataType::AUDIO].size();
1277 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1281 for (uint32_t n = 0; n < limit; ++n) {
1283 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1285 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1286 connect_to = outputs[DataType::AUDIO][n % mod];
1289 if (!connect_to.empty()) {
1290 if (_monitor_out->output()->connect (p, connect_to, this)) {
1291 error << string_compose (
1292 _("cannot connect control output %1 to %2"),
1303 /* Connect tracks to monitor section. Note that in an
1304 existing session, the internal sends will already exist, but we want the
1305 routes to notice that they connect to the control out specifically.
1309 boost::shared_ptr<RouteList> rls = routes.reader ();
1311 ProcessorChangeBlocker pcb (this, false);
1313 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1315 if ((*x)->is_monitor()) {
1317 } else if ((*x)->is_master()) {
1320 (*x)->enable_monitor_send ();
1326 Session::add_master_bus (ChanCount const& count)
1328 if (master_out ()) {
1334 boost::shared_ptr<Route> r (new Route (*this, _("Master"), PresentationInfo::MasterOut, DataType::AUDIO));
1339 BOOST_MARK_ROUTE(r);
1342 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1343 r->input()->ensure_io (count, false, this);
1344 r->output()->ensure_io (count, false, this);
1348 add_routes (rl, false, false, false, PresentationInfo::max_order);
1353 Session::hookup_io ()
1355 /* stop graph reordering notifications from
1356 causing resorts, etc.
1359 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1363 /* we delay creating the auditioner till now because
1364 it makes its own connections to ports.
1368 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1370 throw failed_constructor ();
1375 catch (failed_constructor& err) {
1376 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1380 /* load bundles, which we may have postponed earlier on */
1381 if (_bundle_xml_node) {
1382 load_bundles (*_bundle_xml_node);
1383 delete _bundle_xml_node;
1386 /* Tell all IO objects to connect themselves together */
1388 IO::enable_connecting ();
1390 /* Now tell all "floating" ports to connect to whatever
1391 they should be connected to.
1394 AudioEngine::instance()->reconnect_ports ();
1395 TransportMasterManager::instance().reconnect_ports ();
1397 /* Anyone who cares about input state, wake up and do something */
1399 IOConnectionsComplete (); /* EMIT SIGNAL */
1401 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1403 /* now handle the whole enchilada as if it was one
1404 graph reorder event.
1409 /* update the full solo state, which can't be
1410 correctly determined on a per-route basis, but
1411 needs the global overview that only the session
1415 update_route_solo_state ();
1419 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1421 boost::shared_ptr<Track> track = wp.lock ();
1426 boost::shared_ptr<Playlist> playlist;
1428 if ((playlist = track->playlist()) != 0) {
1429 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1430 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1431 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1436 Session::record_enabling_legal () const
1438 if (Config->get_all_safe()) {
1445 Session::set_track_monitor_input_status (bool yn)
1447 boost::shared_ptr<RouteList> rl = routes.reader ();
1448 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1449 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1450 if (tr && tr->rec_enable_control()->get_value()) {
1451 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1452 tr->request_input_monitoring (yn);
1458 Session::auto_punch_start_changed (Location* location)
1460 replace_event (SessionEvent::PunchIn, location->start());
1462 if (get_record_enabled() && config.get_punch_in() && !actively_recording ()) {
1463 /* capture start has been changed, so save new pending state */
1464 save_state ("", true);
1469 Session::auto_punch_end_changed (Location* location)
1471 replace_event (SessionEvent::PunchOut, location->end());
1475 Session::auto_punch_changed (Location* location)
1477 auto_punch_start_changed (location);
1478 auto_punch_end_changed (location);
1481 /** @param loc A loop location.
1482 * @param pos Filled in with the start time of the required fade-out (in session samples).
1483 * @param length Filled in with the length of the required fade-out.
1486 Session::auto_loop_declick_range (Location* loc, samplepos_t & pos, samplepos_t & length)
1488 pos = max (loc->start(), loc->end() - 64);
1489 length = loc->end() - pos;
1493 Session::auto_loop_changed (Location* location)
1495 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1498 auto_loop_declick_range (location, dcp, dcl);
1500 bool rolling = transport_rolling ();
1502 if (rolling && play_loop) {
1504 if (_transport_sample < location->start() || _transport_sample > location->end()) {
1505 // relocate to beginning of loop
1506 clear_events (SessionEvent::LocateRoll);
1507 request_locate (location->start(), true);
1511 clear_events (SessionEvent::AutoLoop);
1514 /* possibly move playhead if not rolling; if we are rolling we'll move
1515 to the loop start on stop if that is appropriate.
1520 if (!rolling && select_playhead_priority_target (pos)) {
1521 if (pos == location->start()) {
1522 request_locate (pos);
1526 last_loopend = location->end();
1531 Session::set_auto_punch_location (Location* location)
1535 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1536 punch_connections.drop_connections();
1537 existing->set_auto_punch (false, this);
1538 clear_events (SessionEvent::PunchIn);
1539 clear_events (SessionEvent::PunchOut);
1540 auto_punch_location_changed (0);
1545 if (location == 0) {
1549 if (location->end() <= location->start()) {
1550 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1554 punch_connections.drop_connections ();
1556 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1557 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1558 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1560 location->set_auto_punch (true, this);
1562 auto_punch_changed (location);
1564 auto_punch_location_changed (location);
1568 Session::set_session_extents (samplepos_t start, samplepos_t end)
1571 if ((existing = _locations->session_range_location()) == 0) {
1572 //if there is no existing session, we need to make a new session location (should never happen)
1573 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1577 error << _("Session: you can't use that location for session start/end)") << endmsg;
1581 existing->set( start, end );
1587 Session::set_auto_loop_location (Location* location)
1591 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1592 loop_connections.drop_connections ();
1593 existing->set_auto_loop (false, this);
1594 remove_event (existing->end(), SessionEvent::AutoLoop);
1597 auto_loop_declick_range (existing, dcp, dcl);
1598 auto_loop_location_changed (0);
1603 if (location == 0) {
1607 if (location->end() <= location->start()) {
1608 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1612 last_loopend = location->end();
1614 loop_connections.drop_connections ();
1616 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1617 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1618 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1619 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1621 location->set_auto_loop (true, this);
1623 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1624 // set all tracks to use internal looping
1625 boost::shared_ptr<RouteList> rl = routes.reader ();
1626 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1627 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1628 if (tr && !tr->is_private_route()) {
1629 tr->set_loop (location);
1634 /* take care of our stuff first */
1636 auto_loop_changed (location);
1638 /* now tell everyone else */
1640 auto_loop_location_changed (location);
1644 Session::update_marks (Location*)
1650 Session::update_skips (Location* loc, bool consolidate)
1652 if (_ignore_skips_updates) {
1656 Locations::LocationList skips;
1659 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1660 consolidate_skips (loc);
1663 sync_locations_to_skips ();
1669 Session::consolidate_skips (Location* loc)
1671 Locations::LocationList all_locations = _locations->list ();
1673 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1675 if (!(*l)->is_skip ()) {
1680 /* don't test against self */
1687 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1688 case Evoral::OverlapInternal:
1689 case Evoral::OverlapExternal:
1690 case Evoral::OverlapStart:
1691 case Evoral::OverlapEnd:
1692 /* adjust new location to cover existing one */
1693 loc->set_start (min (loc->start(), (*l)->start()));
1694 loc->set_end (max (loc->end(), (*l)->end()));
1695 /* we don't need this one any more */
1696 _locations->remove (*l);
1697 /* the location has been deleted, so remove reference to it in our local list */
1698 l = all_locations.erase (l);
1701 case Evoral::OverlapNone:
1709 Session::sync_locations_to_skips ()
1711 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1712 * Session::_sync_locations_to_skips() from the audioengine thread.
1714 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1718 Session::_sync_locations_to_skips ()
1720 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1722 Locations::LocationList const & locs (_locations->list());
1724 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1726 Location* location = *i;
1728 if (location->is_skip() && location->is_skipping()) {
1729 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1737 Session::location_added (Location *location)
1739 if (location->is_auto_punch()) {
1740 set_auto_punch_location (location);
1743 if (location->is_auto_loop()) {
1744 set_auto_loop_location (location);
1747 if (location->is_session_range()) {
1748 /* no need for any signal handling or event setting with the session range,
1749 because we keep a direct reference to it and use its start/end directly.
1751 _session_range_location = location;
1754 if (location->is_mark()) {
1755 /* listen for per-location signals that require us to do any * global updates for marks */
1757 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1758 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1759 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1760 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1761 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1764 if (location->is_range_marker()) {
1765 /* listen for per-location signals that require us to do any * global updates for marks */
1767 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1768 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1769 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1770 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1771 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1774 if (location->is_skip()) {
1775 /* listen for per-location signals that require us to update skip-locate events */
1777 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1778 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1779 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1780 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1781 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1783 update_skips (location, true);
1790 Session::location_removed (Location *location)
1792 if (location->is_auto_loop()) {
1793 set_auto_loop_location (0);
1795 set_track_loop (false);
1800 if (location->is_auto_punch()) {
1801 set_auto_punch_location (0);
1804 if (location->is_session_range()) {
1805 /* this is never supposed to happen */
1806 error << _("programming error: session range removed!") << endl;
1809 if (location->is_skip()) {
1811 update_skips (location, false);
1818 Session::locations_changed ()
1820 _locations->apply (*this, &Session::_locations_changed);
1824 Session::_locations_changed (const Locations::LocationList& locations)
1826 /* There was some mass-change in the Locations object.
1828 * We might be re-adding a location here but it doesn't actually matter
1829 * for all the locations that the Session takes an interest in.
1833 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1834 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1835 location_added (*i);
1839 update_skips (NULL, false);
1843 Session::enable_record ()
1845 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1846 /* no recording at anything except normal speed */
1851 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1853 if (rs == Recording) {
1857 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1859 _last_record_location = _transport_sample;
1860 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1862 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1863 set_track_monitor_input_status (true);
1866 RecordStateChanged ();
1873 Session::set_all_tracks_record_enabled (bool enable )
1875 boost::shared_ptr<RouteList> rl = routes.reader();
1876 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1880 Session::disable_record (bool rt_context, bool force)
1884 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1886 if (!Config->get_latched_record_enable () || force) {
1887 g_atomic_int_set (&_record_status, Disabled);
1888 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1890 if (rs == Recording) {
1891 g_atomic_int_set (&_record_status, Enabled);
1895 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1896 set_track_monitor_input_status (false);
1899 RecordStateChanged (); /* emit signal */
1904 Session::step_back_from_record ()
1906 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1908 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1909 set_track_monitor_input_status (false);
1912 RecordStateChanged (); /* emit signal */
1917 Session::maybe_enable_record (bool rt_context)
1919 if (_step_editors > 0) {
1923 g_atomic_int_set (&_record_status, Enabled);
1925 /* This function is currently called from somewhere other than an RT thread.
1926 * (except maybe lua scripts, which can use rt_context = true)
1927 * This save_state() call therefore doesn't impact anything. Doing it here
1928 * means that we save pending state of which sources the next record will use,
1929 * which gives us some chance of recovering from a crash during the record.
1933 save_state ("", true);
1936 if (_transport_speed) {
1937 if (!config.get_punch_in()) {
1941 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1942 RecordStateChanged (); /* EMIT SIGNAL */
1949 Session::audible_sample (bool* latent_locate) const
1951 if (latent_locate) {
1952 *latent_locate = false;
1957 if (synced_to_engine()) {
1958 /* Note: this is basically just sync-to-JACK */
1959 ret = _engine.transport_sample();
1961 ret = _transport_sample;
1966 if (!transport_rolling()) {
1970 #if 0 // TODO looping
1971 if (_transport_speed > 0.0f) {
1972 if (play_loop && have_looped) {
1973 /* the play-position wrapped at the loop-point
1974 * ardour is already playing the beginning of the loop,
1975 * but due to playback latency, the "audible frame"
1976 * is still at the end of the loop.
1978 Location *location = _locations->auto_loop_location();
1979 sampleoffset_t lo = location->start() - ret;
1981 ret = location->end () - lo;
1982 if (latent_locate) {
1983 *latent_locate = true;
1987 } else if (_transport_speed < 0.0f) {
1988 /* XXX wot? no backward looping? */
1992 return std::max ((samplepos_t)0, ret);
1996 Session::preroll_samples (samplepos_t pos) const
1998 const float pr = Config->get_preroll_seconds();
1999 if (pos >= 0 && pr < 0) {
2000 const Tempo& tempo = _tempo_map->tempo_at_sample (pos);
2001 const Meter& meter = _tempo_map->meter_at_sample (pos);
2002 return meter.samples_per_bar (tempo, sample_rate()) * -pr;
2007 return pr * sample_rate();
2011 Session::set_sample_rate (samplecnt_t frames_per_second)
2013 /** \fn void Session::set_sample_size(samplecnt_t)
2014 the AudioEngine object that calls this guarantees
2015 that it will not be called while we are also in
2016 ::process(). Its fine to do things that block
2020 if (_base_sample_rate == 0) {
2021 _base_sample_rate = frames_per_second;
2023 else if (_base_sample_rate != frames_per_second && frames_per_second != _nominal_sample_rate) {
2024 NotifyAboutSampleRateMismatch (_base_sample_rate, frames_per_second);
2026 _nominal_sample_rate = frames_per_second;
2031 reset_write_sources (false);
2033 // XXX we need some equivalent to this, somehow
2034 // SndFileSource::setup_standard_crossfades (frames_per_second);
2038 /* XXX need to reset/reinstantiate all LADSPA plugins */
2042 Session::set_block_size (pframes_t nframes)
2044 /* the AudioEngine guarantees
2045 that it will not be called while we are also in
2046 ::process(). It is therefore fine to do things that block
2051 current_block_size = nframes;
2055 boost::shared_ptr<RouteList> r = routes.reader ();
2057 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2058 (*i)->set_block_size (nframes);
2061 boost::shared_ptr<RouteList> rl = routes.reader ();
2062 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2063 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2065 tr->set_block_size (nframes);
2069 set_worst_io_latencies ();
2075 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase, bool sends_only)
2077 boost::shared_ptr<Route> r2;
2079 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2080 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2084 /* make a copy of the existing list of routes that feed r1 */
2086 Route::FedBy existing (r1->fed_by());
2088 /* for each route that feeds r1, recurse, marking it as feeding
2092 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2093 if (!(r2 = i->r.lock ())) {
2094 /* (*i) went away, ignore it */
2098 /* r2 is a route that feeds r1 which somehow feeds base. mark
2099 base as being fed by r2
2102 rbase->add_fed_by (r2, i->sends_only || sends_only);
2106 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2110 if (r1->feeds (r2) && r2->feeds (r1)) {
2114 /* now recurse, so that we can mark base as being fed by
2115 all routes that feed r2
2118 trace_terminal (r2, rbase, i->sends_only || sends_only);
2125 Session::resort_routes ()
2127 /* don't do anything here with signals emitted
2128 by Routes during initial setup or while we
2129 are being destroyed.
2132 if (inital_connect_or_deletion_in_progress ()) {
2136 if (_route_deletion_in_progress) {
2141 RCUWriter<RouteList> writer (routes);
2142 boost::shared_ptr<RouteList> r = writer.get_copy ();
2143 resort_routes_using (r);
2144 /* writer goes out of scope and forces update */
2148 if (DEBUG_ENABLED(DEBUG::Graph)) {
2149 boost::shared_ptr<RouteList> rl = routes.reader ();
2150 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2151 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2153 const Route::FedBy& fb ((*i)->fed_by());
2155 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2156 boost::shared_ptr<Route> sf = f->r.lock();
2158 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2167 /** This is called whenever we need to rebuild the graph of how we will process
2169 * @param r List of routes, in any order.
2173 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2175 /* We are going to build a directed graph of our routes;
2176 this is where the edges of that graph are put.
2181 /* Go through all routes doing two things:
2183 * 1. Collect the edges of the route graph. Each of these edges
2184 * is a pair of routes, one of which directly feeds the other
2185 * either by a JACK connection or by an internal send.
2187 * 2. Begin the process of making routes aware of which other
2188 * routes directly or indirectly feed them. This information
2189 * is used by the solo code.
2192 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2194 /* Clear out the route's list of direct or indirect feeds */
2195 (*i)->clear_fed_by ();
2197 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2199 bool via_sends_only;
2201 /* See if this *j feeds *i according to the current state of the JACK
2202 connections and internal sends.
2204 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2205 /* add the edge to the graph (part #1) */
2206 edges.add (*j, *i, via_sends_only);
2207 /* tell the route (for part #2) */
2208 (*i)->add_fed_by (*j, via_sends_only);
2213 /* Attempt a topological sort of the route graph */
2214 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2216 if (sorted_routes) {
2217 /* We got a satisfactory topological sort, so there is no feedback;
2220 Note: the process graph rechain does not require a
2221 topologically-sorted list, but hey ho.
2223 if (_process_graph) {
2224 _process_graph->rechain (sorted_routes, edges);
2227 _current_route_graph = edges;
2229 /* Complete the building of the routes' lists of what directly
2230 or indirectly feeds them.
2232 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2233 trace_terminal (*i, *i, false);
2236 *r = *sorted_routes;
2239 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2240 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2241 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2245 SuccessfulGraphSort (); /* EMIT SIGNAL */
2248 /* The topological sort failed, so we have a problem. Tell everyone
2249 and stick to the old graph; this will continue to be processed, so
2250 until the feedback is fixed, what is played back will not quite
2251 reflect what is actually connected. Note also that we do not
2252 do trace_terminal here, as it would fail due to an endless recursion,
2253 so the solo code will think that everything is still connected
2257 FeedbackDetected (); /* EMIT SIGNAL */
2262 /** Find a route name starting with \a base, maybe followed by the
2263 * lowest \a id. \a id will always be added if \a definitely_add_number
2264 * is true on entry; otherwise it will only be added if required
2265 * to make the name unique.
2267 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2268 * The available route name with the lowest ID will be used, and \a id
2269 * will be set to the ID.
2271 * \return false if a route name could not be found, and \a track_name
2272 * and \a id do not reflect a free route name.
2275 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2277 /* the base may conflict with ports that do not belong to existing
2278 routes, but hidden objects like the click track. So check port names
2279 before anything else.
2282 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2283 if (base == reserved->first) {
2284 /* Check if this reserved name already exists, and if
2285 so, disallow it without a numeric suffix.
2287 if (!reserved->second || route_by_name (reserved->first)) {
2288 definitely_add_number = true;
2297 /* if we have "base 1" already, it doesn't make sense to add "base"
2298 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2300 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2301 /* just use the base */
2307 name = string_compose ("%1 %2", base, id);
2309 if (route_by_name (name) == 0) {
2315 } while (id < (UINT_MAX-1));
2320 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2322 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2324 in = ChanCount::ZERO;
2325 out = ChanCount::ZERO;
2327 boost::shared_ptr<RouteList> r = routes.reader ();
2329 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2330 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2334 assert (!tr->is_auditioner()); // XXX remove me
2335 in += tr->n_inputs();
2336 out += tr->n_outputs();
2341 Session::default_track_name_pattern (DataType t)
2344 case DataType::AUDIO:
2345 if (Profile->get_trx()) {
2352 case DataType::MIDI:
2359 /** Caller must not hold process lock
2360 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2361 * @param instrument plugin info for the instrument to insert pre-fader, if any
2363 list<boost::shared_ptr<MidiTrack> >
2364 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2365 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2366 RouteGroup* route_group, uint32_t how_many,
2367 string name_template, PresentationInfo::order_t order,
2371 uint32_t track_id = 0;
2373 RouteList new_routes;
2374 list<boost::shared_ptr<MidiTrack> > ret;
2376 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2377 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2380 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2381 error << "cannot find name for new midi track" << endmsg;
2385 boost::shared_ptr<MidiTrack> track;
2388 track.reset (new MidiTrack (*this, track_name, mode));
2390 if (track->init ()) {
2395 track->set_strict_io (true);
2398 BOOST_MARK_TRACK (track);
2401 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2402 if (track->input()->ensure_io (input, false, this)) {
2403 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2407 if (track->output()->ensure_io (output, false, this)) {
2408 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2414 route_group->add (track);
2417 new_routes.push_back (track);
2418 ret.push_back (track);
2421 catch (failed_constructor &err) {
2422 error << _("Session: could not create new midi track.") << endmsg;
2426 catch (AudioEngine::PortRegistrationFailure& pfe) {
2428 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;
2436 if (!new_routes.empty()) {
2437 StateProtector sp (this);
2438 if (Profile->get_trx()) {
2439 add_routes (new_routes, false, false, false, order);
2441 add_routes (new_routes, true, true, false, order);
2445 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2446 PluginPtr plugin = instrument->load (*this);
2448 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2452 plugin->load_preset (*pset);
2454 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2456 pi->set_strict_io (true);
2459 (*r)->add_processor (pi, PreFader);
2461 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2462 (*r)->move_instrument_down (false);
2472 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2473 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2474 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2477 uint32_t bus_id = 0;
2481 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2484 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2485 error << "cannot find name for new midi bus" << endmsg;
2490 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2497 bus->set_strict_io (true);
2500 BOOST_MARK_ROUTE(bus);
2503 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2505 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2506 error << _("cannot configure new midi bus input") << endmsg;
2511 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2512 error << _("cannot configure new midi bus output") << endmsg;
2518 route_group->add (bus);
2521 bus->add_internal_return ();
2522 ret.push_back (bus);
2525 catch (failed_constructor &err) {
2526 error << _("Session: could not create new audio route.") << endmsg;
2530 catch (AudioEngine::PortRegistrationFailure& pfe) {
2531 error << pfe.what() << endmsg;
2541 StateProtector sp (this);
2542 add_routes (ret, false, false, false, order);
2545 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2546 PluginPtr plugin = instrument->load (*this);
2548 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2552 plugin->load_preset (*pset);
2554 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2556 pi->set_strict_io (true);
2559 (*r)->add_processor (pi, PreFader);
2561 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2562 (*r)->move_instrument_down (false);
2574 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2576 boost::shared_ptr<Route> midi_track (wmt.lock());
2582 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2584 if (change.after.n_audio() <= change.before.n_audio()) {
2588 /* new audio ports: make sure the audio goes somewhere useful,
2589 * unless the user has no-auto-connect selected.
2591 * The existing ChanCounts don't matter for this call as they are only
2592 * to do with matching input and output indices, and we are only changing
2595 auto_connect_route (midi_track, false, ChanCount(), change.before);
2600 Session::ensure_stripable_sort_order ()
2603 get_stripables (sl);
2604 sl.sort (Stripable::Sorter ());
2606 bool change = false;
2607 PresentationInfo::order_t order = 0;
2609 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
2610 boost::shared_ptr<Stripable> s (*si);
2611 assert (!s->is_auditioner ()); // XXX remove me
2612 if (s->is_monitor ()) {
2615 if (order != s->presentation_info().order()) {
2616 s->set_presentation_order (order);
2625 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
2627 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
2629 if (first_new_order == PresentationInfo::max_order) {
2630 /* adding at end, no worries */
2634 /* create a gap in the presentation info to accomodate @param how_many
2638 get_stripables (sl);
2640 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
2641 boost::shared_ptr<Stripable> s (*si);
2643 if (s->presentation_info().special (false)) {
2647 if (!s->presentation_info().order_set()) {
2651 if (s->presentation_info().order () >= first_new_order) {
2652 s->set_presentation_order (s->presentation_info().order () + how_many);
2657 /** Caller must not hold process lock
2658 * @param name_template string to use for the start of the name, or "" to use "Audio".
2660 list< boost::shared_ptr<AudioTrack> >
2661 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
2662 uint32_t how_many, string name_template, PresentationInfo::order_t order,
2666 uint32_t track_id = 0;
2668 RouteList new_routes;
2669 list<boost::shared_ptr<AudioTrack> > ret;
2671 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2672 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2676 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2677 error << "cannot find name for new audio track" << endmsg;
2681 boost::shared_ptr<AudioTrack> track;
2684 track.reset (new AudioTrack (*this, track_name, mode));
2686 if (track->init ()) {
2690 if (Profile->get_mixbus ()) {
2691 track->set_strict_io (true);
2694 if (ARDOUR::Profile->get_trx ()) {
2695 // TRACKS considers it's not a USE CASE, it's
2696 // a piece of behavior of the session model:
2698 // Gain for a newly created route depends on
2699 // the current output_auto_connect mode:
2701 // 0 for Stereo Out mode
2703 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2704 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
2708 BOOST_MARK_TRACK (track);
2711 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2713 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2714 error << string_compose (
2715 _("cannot configure %1 in/%2 out configuration for new audio track"),
2716 input_channels, output_channels)
2721 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2722 error << string_compose (
2723 _("cannot configure %1 in/%2 out configuration for new audio track"),
2724 input_channels, output_channels)
2731 route_group->add (track);
2734 new_routes.push_back (track);
2735 ret.push_back (track);
2738 catch (failed_constructor &err) {
2739 error << _("Session: could not create new audio track.") << endmsg;
2743 catch (AudioEngine::PortRegistrationFailure& pfe) {
2745 error << pfe.what() << endmsg;
2753 if (!new_routes.empty()) {
2754 StateProtector sp (this);
2755 if (Profile->get_trx()) {
2756 add_routes (new_routes, false, false, false, order);
2758 add_routes (new_routes, true, true, false, order);
2765 /** Caller must not hold process lock.
2766 * @param name_template string to use for the start of the name, or "" to use "Bus".
2769 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
2770 PresentationInfo::Flag flags, PresentationInfo::order_t order)
2773 uint32_t bus_id = 0;
2777 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2780 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
2781 error << "cannot find name for new audio bus" << endmsg;
2786 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
2792 if (Profile->get_mixbus ()) {
2793 bus->set_strict_io (true);
2796 BOOST_MARK_ROUTE(bus);
2799 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2801 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2802 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2803 input_channels, output_channels)
2809 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2810 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2811 input_channels, output_channels)
2818 route_group->add (bus);
2821 bus->add_internal_return ();
2822 ret.push_back (bus);
2825 catch (failed_constructor &err) {
2826 error << _("Session: could not create new audio route.") << endmsg;
2830 catch (AudioEngine::PortRegistrationFailure& pfe) {
2831 error << pfe.what() << endmsg;
2841 StateProtector sp (this);
2842 if (Profile->get_trx()) {
2843 add_routes (ret, false, false, false, order);
2844 } else if (flags == PresentationInfo::FoldbackBus) {
2845 add_routes (ret, false, false, true, order); // no autoconnect
2847 add_routes (ret, false, true, true, order); // autoconnect // outputs only
2856 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
2857 PlaylistDisposition pd)
2861 if (!tree.read (template_path.c_str())) {
2865 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
2869 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
2872 uint32_t number = 0;
2873 const uint32_t being_added = how_many;
2874 /* This will prevent the use of any existing XML-provided PBD::ID
2877 Stateful::ForceIDRegeneration force_ids;
2878 IO::disable_connecting ();
2882 /* We're going to modify the node contents a bit so take a
2883 * copy. The node may be re-used when duplicating more than once.
2886 XMLNode node_copy (node);
2887 std::vector<boost::shared_ptr<Playlist> > shared_playlists;
2892 if (!name_base.empty()) {
2894 /* if we're adding more than one routes, force
2895 * all the names of the new routes to be
2896 * numbered, via the final parameter.
2899 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
2900 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2901 abort(); /*NOTREACHED*/
2906 string const route_name = node_copy.property(X_("name"))->value ();
2908 /* generate a new name by adding a number to the end of the template name */
2909 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
2910 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2911 abort(); /*NOTREACHED*/
2915 /* figure out the appropriate playlist setup. The track
2916 * (if the Route we're creating is a track) will find
2920 if (pd == CopyPlaylist) {
2922 PBD::ID playlist_id;
2924 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
2925 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
2926 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
2927 playlist->reset_shares ();
2928 node_copy.set_property (X_("audio-playlist"), playlist->id());
2931 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
2932 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
2933 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
2934 playlist->reset_shares ();
2935 node_copy.set_property (X_("midi-playlist"), playlist->id());
2938 } else if (pd == SharePlaylist) {
2939 PBD::ID playlist_id;
2941 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
2942 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
2943 shared_playlists.push_back (playlist);
2946 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
2947 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
2948 shared_playlists.push_back (playlist);
2951 } else { /* NewPlaylist */
2955 if (node_copy.get_property (X_("audio-playlist"), pid)) {
2956 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::AUDIO, *this, name, false);
2957 node_copy.set_property (X_("audio-playlist"), playlist->id());
2960 if (node_copy.get_property (X_("midi-playlist"), pid)) {
2961 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::MIDI, *this, name, false);
2962 node_copy.set_property (X_("midi-playlist"), playlist->id());
2966 /* Fix up new name in the XML node */
2968 Route::set_name_in_state (node_copy, name);
2970 /* trim bitslots from listen sends so that new ones are used */
2971 XMLNodeList children = node_copy.children ();
2972 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2973 if ((*i)->name() == X_("Processor")) {
2974 /* ForceIDRegeneration does not catch the following */
2975 XMLProperty const * role = (*i)->property (X_("role"));
2976 XMLProperty const * type = (*i)->property (X_("type"));
2977 if (role && role->value() == X_("Aux")) {
2978 /* check if the target bus exists.
2979 * we should not save aux-sends in templates.
2981 XMLProperty const * target = (*i)->property (X_("target"));
2983 (*i)->set_property ("type", "dangling-aux-send");
2986 boost::shared_ptr<Route> r = route_by_id (target->value());
2987 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
2988 (*i)->set_property ("type", "dangling-aux-send");
2992 if (role && role->value() == X_("Listen")) {
2993 (*i)->remove_property (X_("bitslot"));
2995 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
2996 Delivery::Role xrole;
2997 uint32_t bitslot = 0;
2998 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
2999 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3000 (*i)->remove_property (X_("bitslot"));
3001 (*i)->remove_property (X_("name"));
3002 (*i)->set_property ("bitslot", bitslot);
3003 (*i)->set_property ("name", name);
3004 XMLNodeList io_kids = (*i)->children ();
3005 for (XMLNodeList::iterator j = io_kids.begin(); j != io_kids.end(); ++j) {
3006 if ((*j)->name() != X_("IO")) {
3009 (*j)->remove_property (X_("name"));
3010 (*j)->set_property ("name", name);
3013 else if (type && type->value() == X_("intreturn")) {
3014 (*i)->remove_property (X_("bitslot"));
3015 (*i)->set_property ("ignore-bitslot", "1");
3017 else if (type && type->value() == X_("return")) {
3018 // Return::set_state() generates a new one
3019 (*i)->remove_property (X_("bitslot"));
3021 else if (type && type->value() == X_("port")) {
3022 IOProcessor::prepare_for_reset (**i, name);
3027 /* new routes start off unsoloed to avoid issues related to
3028 upstream / downstream buses.
3030 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3032 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3035 error << _("Session: cannot create track/bus from template description") << endmsg;
3039 /* Fix up sharing of playlists with the new Route/Track */
3041 for (vector<boost::shared_ptr<Playlist> >::iterator sp = shared_playlists.begin(); sp != shared_playlists.end(); ++sp) {
3042 (*sp)->share_with (route->id());
3045 if (boost::dynamic_pointer_cast<Track>(route)) {
3046 /* force input/output change signals so that the new diskstream
3047 picks up the configuration of the route. During session
3048 loading this normally happens in a different way.
3051 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3053 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3054 change.after = route->input()->n_ports();
3055 route->input()->changed (change, this);
3056 change.after = route->output()->n_ports();
3057 route->output()->changed (change, this);
3060 ret.push_back (route);
3063 catch (failed_constructor &err) {
3064 error << _("Session: could not create new route from template") << endmsg;
3068 catch (AudioEngine::PortRegistrationFailure& pfe) {
3069 error << pfe.what() << endmsg;
3074 IO::enable_connecting ();
3083 StateProtector sp (this);
3084 if (Profile->get_trx()) {
3085 add_routes (ret, false, false, false, insert_at);
3087 add_routes (ret, true, true, false, insert_at);
3091 IO::enable_connecting ();
3097 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3100 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3101 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3104 error << _("Adding new tracks/busses failed") << endmsg;
3109 update_latency (false);
3110 update_latency (true);
3115 save_state (_current_snapshot_name);
3118 update_route_record_state ();
3120 RouteAdded (new_routes); /* EMIT SIGNAL */
3124 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3126 ChanCount existing_inputs;
3127 ChanCount existing_outputs;
3131 count_existing_track_channels (existing_inputs, existing_outputs);
3134 RCUWriter<RouteList> writer (routes);
3135 boost::shared_ptr<RouteList> r = writer.get_copy ();
3136 n_routes = r->size();
3137 r->insert (r->end(), new_routes.begin(), new_routes.end());
3139 /* if there is no control out and we're not in the middle of loading,
3140 * resort the graph here. if there is a control out, we will resort
3141 * toward the end of this method. if we are in the middle of loading,
3142 * we will resort when done.
3145 if (!_monitor_out && IO::connecting_legal) {
3146 resort_routes_using (r);
3150 /* monitor is not part of the order */
3152 assert (n_routes > 0);
3157 PresentationInfo::ChangeSuspender cs;
3158 ensure_route_presentation_info_gap (order, new_routes.size());
3160 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3162 boost::weak_ptr<Route> wpr (*x);
3163 boost::shared_ptr<Route> r (*x);
3165 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3166 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3167 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3169 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3170 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3171 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3173 if (r->is_master()) {
3177 if (r->is_monitor()) {
3181 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3183 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3184 track_playlist_changed (boost::weak_ptr<Track> (tr));
3185 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3187 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3189 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3190 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3191 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3195 if (!r->presentation_info().special (false)) {
3197 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3199 /* presentation info order may already have been set from XML */
3201 if (!r->presentation_info().order_set()) {
3202 if (order == PresentationInfo::max_order) {
3203 /* just add to the end */
3204 r->set_presentation_order (n_routes + added);
3205 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3207 r->set_presentation_order (order + added);
3208 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3211 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3215 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3216 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3217 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3219 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3221 r->presentation_info().order(),
3222 enum_2_string (r->presentation_info().flags()),
3223 r->presentation_info()));
3227 if (input_auto_connect || output_auto_connect) {
3228 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3229 existing_inputs += r->n_inputs();
3230 existing_outputs += r->n_outputs();
3235 ensure_stripable_sort_order ();
3238 if (_monitor_out && IO::connecting_legal) {
3239 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3241 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3242 if ((*x)->is_monitor()) {
3244 } else if ((*x)->is_master()) {
3247 (*x)->enable_monitor_send ();
3252 reassign_track_numbers ();
3256 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3258 boost::shared_ptr<RouteList> r = routes.reader ();
3259 boost::shared_ptr<Send> s;
3261 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3262 if ((s = (*i)->internal_send_for (dest)) != 0) {
3263 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3269 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3271 boost::shared_ptr<RouteList> r = routes.reader ();
3272 boost::shared_ptr<Send> s;
3274 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3275 if ((s = (*i)->internal_send_for (dest)) != 0) {
3276 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3282 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3284 boost::shared_ptr<RouteList> r = routes.reader ();
3285 boost::shared_ptr<Send> s;
3287 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3288 if ((s = (*i)->internal_send_for (dest)) != 0) {
3289 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3294 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3296 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3298 boost::shared_ptr<RouteList> r = routes.reader ();
3299 boost::shared_ptr<RouteList> t (new RouteList);
3301 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3302 /* no MIDI sends because there are no MIDI busses yet */
3303 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3308 add_internal_sends (dest, p, t);
3312 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3314 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3315 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3320 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3322 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3326 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3328 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3332 if (!dest->internal_return()) {
3333 dest->add_internal_return ();
3336 sender->add_aux_send (dest, before);
3342 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3344 bool mute_changed = false;
3345 bool send_selected = false;
3347 { // RCU Writer scope
3348 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3349 RCUWriter<RouteList> writer (routes);
3350 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3352 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3354 if (_selection->selected (*iter)) {
3355 send_selected = true;
3358 if (*iter == _master_out) {
3362 /* speed up session deletion, don't do the solo dance */
3363 if (!deletion_in_progress ()) {
3364 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3367 if ((*iter)->mute_control()->muted ()) {
3368 mute_changed = true;
3373 /* deleting the master out seems like a dumb
3374 idea, but its more of a UI policy issue
3378 if (*iter == _master_out) {
3379 _master_out = boost::shared_ptr<Route> ();
3382 if (*iter == _monitor_out) {
3383 _monitor_out.reset ();
3386 // We need to disconnect the route's inputs and outputs
3388 (*iter)->input()->disconnect (0);
3389 (*iter)->output()->disconnect (0);
3391 /* if the route had internal sends sending to it, remove them */
3393 if (!deletion_in_progress () && (*iter)->internal_return()) {
3395 boost::shared_ptr<RouteList> r = routes.reader ();
3396 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3397 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3399 (*i)->remove_processor (s);
3404 /* if the monitoring section had a pointer to this route, remove it */
3405 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3406 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3407 ProcessorChangeBlocker pcb (this, false);
3408 (*iter)->remove_aux_or_listen (_monitor_out);
3411 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3412 if (mt && mt->step_editing()) {
3413 if (_step_editors > 0) {
3419 /* writer goes out of scope, forces route list update */
3421 } // end of RCU Writer scope
3424 MuteChanged (); /* EMIT SIGNAL */
3427 update_route_solo_state ();
3428 update_latency_compensation ();
3431 /* Re-sort routes to remove the graph's current references to the one that is
3432 * going away, then flush old references out of the graph.
3435 routes.flush (); // maybe unsafe, see below.
3438 if (_process_graph && !deletion_in_progress() && _engine.running()) {
3439 _process_graph->clear_other_chain ();
3442 /* get rid of it from the dead wood collection in the route list manager */
3443 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3447 /* remove these routes from the selection if appropriate, and signal
3448 * the change *before* we call DropReferences for them.
3451 if (send_selected && !deletion_in_progress()) {
3452 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3453 _selection->remove_stripable_by_id ((*iter)->id());
3456 pc.add (Properties::selected);
3457 PresentationInfo::Change (pc);
3460 /* try to cause everyone to drop their references
3461 * and unregister ports from the backend
3464 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3465 (*iter)->drop_references ();
3468 if (deletion_in_progress()) {
3473 pc.add (Properties::order);
3474 PresentationInfo::Change (pc);
3476 /* save the new state of the world */
3478 if (save_state (_current_snapshot_name)) {
3479 save_history (_current_snapshot_name);
3482 update_route_record_state ();
3486 Session::remove_route (boost::shared_ptr<Route> route)
3488 boost::shared_ptr<RouteList> rl (new RouteList);
3489 rl->push_back (route);
3494 Session::route_mute_changed ()
3496 MuteChanged (); /* EMIT SIGNAL */
3501 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3503 boost::shared_ptr<Route> route (wpr.lock());
3509 assert (Config->get_solo_control_is_listen_control());
3511 if (route->solo_control()->soloed_by_self_or_masters()) {
3513 if (Config->get_exclusive_solo()) {
3515 RouteGroup* rg = route->route_group ();
3516 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3518 boost::shared_ptr<RouteList> r = routes.reader ();
3520 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3521 if ((*i) == route) {
3522 /* already changed */
3526 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3527 /* route does not get solo propagated to it */
3531 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3532 /* this route is a part of the same solo group as the route
3533 * that was changed. Changing that route did change or will
3534 * change all group members appropriately, so we can ignore it
3539 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3545 } else if (_listen_cnt > 0) {
3552 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3554 boost::shared_ptr<Route> route (wpr.lock());
3560 bool send_changed = false;
3562 if (route->solo_isolate_control()->solo_isolated()) {
3563 if (_solo_isolated_cnt == 0) {
3564 send_changed = true;
3566 _solo_isolated_cnt++;
3567 } else if (_solo_isolated_cnt > 0) {
3568 _solo_isolated_cnt--;
3569 if (_solo_isolated_cnt == 0) {
3570 send_changed = true;
3575 IsolatedChanged (); /* EMIT SIGNAL */
3580 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3582 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3584 boost::shared_ptr<Route> route (wpr.lock());
3590 if (Config->get_solo_control_is_listen_control()) {
3591 route_listen_changed (group_override, wpr);
3595 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()));
3597 if (route->solo_control()->transitioned_into_solo() == 0) {
3598 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3601 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()));
3605 boost::shared_ptr<RouteList> r = routes.reader ();
3606 int32_t delta = route->solo_control()->transitioned_into_solo ();
3608 /* the route may be a member of a group that has shared-solo
3609 * semantics. If so, then all members of that group should follow the
3610 * solo of the changed route. But ... this is optional, controlled by a
3611 * Controllable::GroupControlDisposition.
3613 * The first argument to the signal that this method is connected to is the
3614 * GroupControlDisposition value that was used to change solo.
3616 * If the solo change was done with group semantics (either InverseGroup
3617 * (force the entire group to change even if the group shared solo is
3618 * disabled) or UseGroup (use the group, which may or may not have the
3619 * shared solo property enabled)) then as we propagate the change to
3620 * the entire session we should IGNORE THE GROUP that the changed route
3624 RouteGroup* rg = route->route_group ();
3625 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3627 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
3629 if (delta == 1 && Config->get_exclusive_solo()) {
3631 /* new solo: disable all other solos, but not the group if its solo-enabled */
3633 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3635 if ((*i) == route) {
3636 /* already changed */
3640 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3641 /* route does not get solo propagated to it */
3645 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3646 /* this route is a part of the same solo group as the route
3647 * that was changed. Changing that route did change or will
3648 * change all group members appropriately, so we can ignore it
3654 (*i)->solo_control()->set_value (0.0, group_override);
3658 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3660 RouteList uninvolved;
3662 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3664 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3665 bool via_sends_only;
3666 bool in_signal_flow;
3668 if ((*i) == route) {
3669 /* already changed */
3673 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3674 /* route does not get solo propagated to it */
3675 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(),
3680 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3681 /* this route is a part of the same solo group as the route
3682 * that was changed. Changing that route did change or will
3683 * change all group members appropriately, so we can ignore it
3689 in_signal_flow = false;
3691 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3693 if ((*i)->feeds (route, &via_sends_only)) {
3694 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3695 if (!via_sends_only) {
3696 if (!route->soloed_by_others_upstream()) {
3697 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3699 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3702 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3704 in_signal_flow = true;
3706 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3709 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3711 if (route->feeds (*i, &via_sends_only)) {
3712 /* propagate solo upstream only if routing other than
3713 sends is involved, but do consider the other route
3714 (*i) to be part of the signal flow even if only
3717 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3721 route->soloed_by_others_downstream(),
3722 route->soloed_by_others_upstream()));
3723 if (!via_sends_only) {
3724 //NB. Triggers Invert Push, which handles soloed by downstream
3725 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3726 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3728 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3730 in_signal_flow = true;
3732 DEBUG_TRACE (DEBUG::Solo, string_compose("\tno feed to %1\n", (*i)->name()) );
3735 if (!in_signal_flow) {
3736 uninvolved.push_back (*i);
3740 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3742 /* now notify that the mute state of the routes not involved in the signal
3743 pathway of the just-solo-changed route may have altered.
3746 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3747 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3748 (*i)->act_on_mute ();
3749 /* Session will emit SoloChanged() after all solo changes are
3750 * complete, which should be used by UIs to update mute status
3756 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3758 /* now figure out if anything that matters is soloed (or is "listening")*/
3760 bool something_soloed = false;
3761 bool something_listening = false;
3762 uint32_t listeners = 0;
3763 uint32_t isolated = 0;
3766 r = routes.reader();
3769 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3770 if ((*i)->can_solo()) {
3771 if (Config->get_solo_control_is_listen_control()) {
3772 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
3774 something_listening = true;
3777 (*i)->set_listen (false);
3778 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
3779 something_soloed = true;
3784 if ((*i)->solo_isolate_control()->solo_isolated()) {
3789 if (something_soloed != _non_soloed_outs_muted) {
3790 _non_soloed_outs_muted = something_soloed;
3791 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3794 if (something_listening != _listening) {
3795 _listening = something_listening;
3796 SoloActive (_listening);
3799 _listen_cnt = listeners;
3801 if (isolated != _solo_isolated_cnt) {
3802 _solo_isolated_cnt = isolated;
3803 IsolatedChanged (); /* EMIT SIGNAL */
3806 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3807 something_soloed, listeners, isolated));
3810 SoloChanged (); /* EMIT SIGNAL */
3815 Session::muted () const
3817 // TODO consider caching the value on every MuteChanged signal,
3818 // Note that API users may also subscribe to MuteChanged and hence
3819 // this method needs to be called first.
3822 get_stripables (all);
3823 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
3824 assert (!(*i)->is_auditioner()); // XXX remove me
3825 if ((*i)->is_monitor()) {
3828 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
3829 if (r && !r->active()) {
3832 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
3833 if (mc && mc->muted ()) {
3841 std::vector<boost::weak_ptr<AutomationControl> >
3842 Session::cancel_all_mute ()
3845 get_stripables (all);
3846 std::vector<boost::weak_ptr<AutomationControl> > muted;
3847 boost::shared_ptr<ControlList> cl (new ControlList);
3848 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
3849 assert (!(*i)->is_auditioner());
3850 if ((*i)->is_monitor()) {
3853 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
3854 if (r && !r->active()) {
3857 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
3858 if (ac && ac->get_value () > 0) {
3860 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
3863 if (!cl->empty ()) {
3864 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
3870 Session::get_stripables (StripableList& sl, PresentationInfo::Flag fl) const
3872 boost::shared_ptr<RouteList> r = routes.reader ();
3873 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
3874 if ((*it)->presentation_info ().flags () & fl) {
3879 if (fl & PresentationInfo::VCA) {
3880 VCAList v = _vca_manager->vcas ();
3881 sl.insert (sl.end(), v.begin(), v.end());
3886 Session::get_stripables () const
3888 PresentationInfo::Flag fl = PresentationInfo::AllStripables;
3890 Session::get_stripables (rv, fl);
3891 rv.sort (Stripable::Sorter ());
3896 Session::get_routelist (bool mixer_order, PresentationInfo::Flag fl) const
3898 boost::shared_ptr<RouteList> r = routes.reader ();
3900 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
3901 if ((*it)->presentation_info ().flags () & fl) {
3905 rv.sort (Stripable::Sorter (mixer_order));
3909 boost::shared_ptr<RouteList>
3910 Session::get_routes_with_internal_returns() const
3912 boost::shared_ptr<RouteList> r = routes.reader ();
3913 boost::shared_ptr<RouteList> rl (new RouteList);
3915 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3916 if ((*i)->internal_return ()) {
3924 Session::io_name_is_legal (const std::string& name) const
3926 boost::shared_ptr<RouteList> r = routes.reader ();
3928 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
3929 if (name == reserved->first) {
3930 if (!route_by_name (reserved->first)) {
3931 /* first instance of a reserved name is allowed for some */
3932 return reserved->second;
3934 /* all other instances of a reserved name are not allowed */
3939 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3940 if ((*i)->name() == name) {
3944 if ((*i)->has_io_processor_named (name)) {
3953 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3956 vector<string> connections;
3958 /* if we are passed only a single route and we're not told to turn
3959 * others off, then just do the simple thing.
3962 if (flip_others == false && rl->size() == 1) {
3963 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3965 mt->set_input_active (onoff);
3970 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3972 PortSet& ps ((*rt)->input()->ports());
3974 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3975 p->get_connections (connections);
3978 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3979 routes_using_input_from (*s, rl2);
3982 /* scan all relevant routes to see if others are on or off */
3984 bool others_are_already_on = false;
3986 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3988 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3994 if ((*r) != (*rt)) {
3995 if (mt->input_active()) {
3996 others_are_already_on = true;
3999 /* this one needs changing */
4000 mt->set_input_active (onoff);
4006 /* globally reverse other routes */
4008 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4009 if ((*r) != (*rt)) {
4010 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4012 mt->set_input_active (!others_are_already_on);
4021 Session::routes_using_input_from (const string& str, RouteList& rl)
4023 boost::shared_ptr<RouteList> r = routes.reader();
4025 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4026 if ((*i)->input()->connected_to (str)) {
4032 boost::shared_ptr<Route>
4033 Session::route_by_name (string name) const
4035 boost::shared_ptr<RouteList> r = routes.reader ();
4037 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4038 if ((*i)->name() == name) {
4043 return boost::shared_ptr<Route> ((Route*) 0);
4046 boost::shared_ptr<Route>
4047 Session::route_by_id (PBD::ID id) const
4049 boost::shared_ptr<RouteList> r = routes.reader ();
4051 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4052 if ((*i)->id() == id) {
4057 return boost::shared_ptr<Route> ((Route*) 0);
4061 boost::shared_ptr<Stripable>
4062 Session::stripable_by_id (PBD::ID id) const
4065 get_stripables (sl);
4067 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4068 if ((*s)->id() == id) {
4073 return boost::shared_ptr<Stripable>();
4076 boost::shared_ptr<Processor>
4077 Session::processor_by_id (PBD::ID id) const
4079 boost::shared_ptr<RouteList> r = routes.reader ();
4081 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4082 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4088 return boost::shared_ptr<Processor> ();
4091 boost::shared_ptr<Route>
4092 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4094 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4097 boost::shared_ptr<Stripable>
4098 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4101 PresentationInfo::order_t match_cnt = 0;
4103 get_stripables (sl);
4104 sl.sort (Stripable::Sorter());
4106 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4108 if ((*s)->presentation_info().hidden()) {
4109 /* if the caller didn't explicitly ask for hidden
4110 stripables, ignore hidden ones. This matches
4111 the semantics of the pre-PresentationOrder
4112 "get by RID" logic of Ardour 4.x and earlier.
4114 XXX at some point we should likely reverse
4115 the logic of the flags, because asking for "the
4116 hidden stripables" is not going to be common,
4117 whereas asking for visible ones is normal.
4120 if (! (flags & PresentationInfo::Hidden)) {
4125 if ((*s)->presentation_info().flag_match (flags)) {
4126 if (match_cnt++ == n) {
4132 /* there is no nth stripable that matches the given flags */
4133 return boost::shared_ptr<Stripable>();
4136 boost::shared_ptr<Route>
4137 Session::route_by_selected_count (uint32_t id) const
4139 RouteList r (*(routes.reader ()));
4140 r.sort (Stripable::Sorter());
4142 RouteList::iterator i;
4144 for (i = r.begin(); i != r.end(); ++i) {
4145 if ((*i)->is_selected()) {
4153 return boost::shared_ptr<Route> ();
4157 Session::reassign_track_numbers ()
4161 RouteList r (*(routes.reader ()));
4162 r.sort (Stripable::Sorter());
4164 StateProtector sp (this);
4166 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4167 assert (!(*i)->is_auditioner());
4168 if (boost::dynamic_pointer_cast<Track> (*i)) {
4169 (*i)->set_track_number(++tn);
4171 else if (!(*i)->is_master() && !(*i)->is_monitor()) {
4172 (*i)->set_track_number(--bn);
4175 const uint32_t decimals = ceilf (log10f (tn + 1));
4176 const bool decimals_changed = _track_number_decimals != decimals;
4177 _track_number_decimals = decimals;
4179 if (decimals_changed && config.get_track_name_number ()) {
4180 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4181 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4183 t->resync_track_name();
4186 // trigger GUI re-layout
4187 config.ParameterChanged("track-name-number");
4191 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4192 boost::shared_ptr<RouteList> rl = routes.reader ();
4193 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4194 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4202 Session::playlist_region_added (boost::weak_ptr<Region> w)
4204 boost::shared_ptr<Region> r = w.lock ();
4209 /* These are the operations that are currently in progress... */
4210 list<GQuark> curr = _current_trans_quarks;
4213 /* ...and these are the operations during which we want to update
4214 the session range location markers.
4217 ops.push_back (Operations::capture);
4218 ops.push_back (Operations::paste);
4219 ops.push_back (Operations::duplicate_region);
4220 ops.push_back (Operations::insert_file);
4221 ops.push_back (Operations::insert_region);
4222 ops.push_back (Operations::drag_region_brush);
4223 ops.push_back (Operations::region_drag);
4224 ops.push_back (Operations::selection_grab);
4225 ops.push_back (Operations::region_fill);
4226 ops.push_back (Operations::fill_selection);
4227 ops.push_back (Operations::create_region);
4228 ops.push_back (Operations::region_copy);
4229 ops.push_back (Operations::fixed_time_region_copy);
4232 /* See if any of the current operations match the ones that we want */
4234 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4236 /* If so, update the session range markers */
4238 maybe_update_session_range (r->position (), r->last_sample ());
4242 /** Update the session range markers if a is before the current start or
4243 * b is after the current end.
4246 Session::maybe_update_session_range (samplepos_t a, samplepos_t b)
4252 samplepos_t session_end_marker_shift_samples = session_end_shift * _nominal_sample_rate;
4254 if (_session_range_location == 0) {
4256 set_session_range_location (a, b + session_end_marker_shift_samples);
4260 if (_session_range_is_free && (a < _session_range_location->start())) {
4261 _session_range_location->set_start (a);
4264 if (_session_range_is_free && (b > _session_range_location->end())) {
4265 _session_range_location->set_end (b);
4271 Session::set_session_range_is_free (bool yn)
4273 _session_range_is_free = yn;
4277 Session::playlist_ranges_moved (list<Evoral::RangeMove<samplepos_t> > const & ranges)
4279 for (list<Evoral::RangeMove<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4280 maybe_update_session_range (i->to, i->to + i->length);
4285 Session::playlist_regions_extended (list<Evoral::Range<samplepos_t> > const & ranges)
4287 for (list<Evoral::Range<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4288 maybe_update_session_range (i->from, i->to);
4292 /* Region management */
4294 boost::shared_ptr<Region>
4295 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4297 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4298 RegionFactory::RegionMap::const_iterator i;
4299 boost::shared_ptr<Region> region;
4301 Glib::Threads::Mutex::Lock lm (region_lock);
4303 for (i = regions.begin(); i != regions.end(); ++i) {
4307 if (region->whole_file()) {
4309 if (child->source_equivalent (region)) {
4315 return boost::shared_ptr<Region> ();
4319 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4321 set<boost::shared_ptr<Region> > relevant_regions;
4323 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4324 RegionFactory::get_regions_using_source (*s, relevant_regions);
4327 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4328 set<boost::shared_ptr<Region> >::iterator tmp;
4333 _playlists->destroy_region (*r);
4334 RegionFactory::map_remove (*r);
4336 (*r)->drop_sources ();
4337 (*r)->drop_references ();
4339 relevant_regions.erase (r);
4344 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4347 Glib::Threads::Mutex::Lock ls (source_lock);
4348 /* remove from the main source list */
4349 sources.erase ((*s)->id());
4352 (*s)->mark_for_remove ();
4353 (*s)->drop_references ();
4363 Session::remove_last_capture ()
4365 list<boost::shared_ptr<Source> > srcs;
4367 boost::shared_ptr<RouteList> rl = routes.reader ();
4368 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4369 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4374 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4377 srcs.insert (srcs.end(), l.begin(), l.end());
4382 destroy_sources (srcs);
4384 save_state (_current_snapshot_name);
4390 Session::get_last_capture_sources (std::list<boost::shared_ptr<Source> >& srcs)
4392 boost::shared_ptr<RouteList> rl = routes.reader ();
4393 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4394 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4399 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4402 srcs.insert (srcs.end(), l.begin(), l.end());
4408 /* Source Management */
4411 Session::add_source (boost::shared_ptr<Source> source)
4413 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4414 pair<SourceMap::iterator,bool> result;
4416 entry.first = source->id();
4417 entry.second = source;
4420 Glib::Threads::Mutex::Lock lm (source_lock);
4421 result = sources.insert (entry);
4424 if (result.second) {
4426 /* yay, new source */
4428 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4431 if (!fs->within_session()) {
4432 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4438 boost::shared_ptr<AudioFileSource> afs;
4440 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4441 if (Config->get_auto_analyse_audio()) {
4442 Analyser::queue_source_for_analysis (source, false);
4446 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4448 SourceAdded(source);
4453 Session::remove_source (boost::weak_ptr<Source> src)
4455 if (deletion_in_progress ()) {
4459 SourceMap::iterator i;
4460 boost::shared_ptr<Source> source = src.lock();
4467 Glib::Threads::Mutex::Lock lm (source_lock);
4469 if ((i = sources.find (source->id())) != sources.end()) {
4471 SourceRemoved(source);
4475 if (!in_cleanup () && !loading ()) {
4477 /* save state so we don't end up with a session file
4478 * referring to non-existent sources.
4481 save_state (_current_snapshot_name);
4485 boost::shared_ptr<Source>
4486 Session::source_by_id (const PBD::ID& id)
4488 Glib::Threads::Mutex::Lock lm (source_lock);
4489 SourceMap::iterator i;
4490 boost::shared_ptr<Source> source;
4492 if ((i = sources.find (id)) != sources.end()) {
4499 boost::shared_ptr<AudioFileSource>
4500 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4502 /* Restricted to audio files because only audio sources have channel
4506 Glib::Threads::Mutex::Lock lm (source_lock);
4508 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4509 boost::shared_ptr<AudioFileSource> afs
4510 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4512 if (afs && afs->path() == path && chn == afs->channel()) {
4517 return boost::shared_ptr<AudioFileSource>();
4520 boost::shared_ptr<MidiSource>
4521 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4523 /* Restricted to MIDI files because audio sources require a channel
4524 for unique identification, in addition to a path.
4527 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4528 if (need_source_lock) {
4532 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4533 boost::shared_ptr<MidiSource> ms
4534 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4535 boost::shared_ptr<FileSource> fs
4536 = boost::dynamic_pointer_cast<FileSource>(s->second);
4538 if (ms && fs && fs->path() == path) {
4543 return boost::shared_ptr<MidiSource>();
4547 Session::count_sources_by_origin (const string& path)
4550 Glib::Threads::Mutex::Lock lm (source_lock);
4552 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4553 boost::shared_ptr<FileSource> fs
4554 = boost::dynamic_pointer_cast<FileSource>(i->second);
4556 if (fs && fs->origin() == path) {
4565 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4567 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4568 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4570 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4575 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4577 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4579 if (Glib::path_is_absolute (filepath)) {
4581 /* rip the session dir from the audiofile source */
4583 string session_path;
4584 bool in_another_session = true;
4586 if (filepath.find (interchange_dir_string) != string::npos) {
4588 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4589 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4590 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4591 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4593 /* see if it is within our session */
4595 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4596 if (i->path == session_path) {
4597 in_another_session = false;
4602 in_another_session = false;
4606 if (in_another_session) {
4607 SessionDirectory sd (session_path);
4608 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4612 /* 1) if file belongs to this session
4613 * it may be a relative path (interchange/...)
4614 * or just basename (session_state, remove source)
4615 * -> just use the basename
4617 std::string filename = Glib::path_get_basename (filepath);
4620 /* 2) if the file is outside our session dir:
4621 * (imported but not copied) add the path for check-summming */
4623 path = Glib::path_get_dirname (filepath);
4626 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4630 Session::new_audio_source_path_for_embedded (const std::string& path)
4634 * we know that the filename is already unique because it exists
4635 * out in the filesystem.
4637 * However, when we bring it into the session, we could get a
4640 * Eg. two embedded files:
4645 * When merged into session, these collide.
4647 * There will not be a conflict with in-memory sources
4648 * because when the source was created we already picked
4649 * a unique name for it.
4651 * This collision is not likely to be common, but we have to guard
4652 * against it. So, if there is a collision, take the md5 hash of the
4653 * the path, and use that as the filename instead.
4656 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4657 string base = Glib::path_get_basename (path);
4658 string newpath = Glib::build_filename (sdir.sound_path(), base);
4660 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4664 md5.digestString (path.c_str());
4665 md5.writeToString ();
4666 base = md5.digestChars;
4668 string ext = get_suffix (path);
4675 newpath = Glib::build_filename (sdir.sound_path(), base);
4677 /* if this collides, we're screwed */
4679 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4680 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4689 /** Return true if there are no audio file sources that use @param name as
4690 * the filename component of their path.
4692 * Return false otherwise.
4694 * This method MUST ONLY be used to check in-session, mono files since it
4695 * hard-codes the channel of the audio file source we are looking for as zero.
4697 * If/when Ardour supports native files in non-mono formats, the logic here
4698 * will need to be revisited.
4701 Session::audio_source_name_is_unique (const string& name)
4703 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4704 vector<space_and_path>::iterator i;
4705 uint32_t existing = 0;
4707 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4709 /* note that we search *without* the extension so that
4710 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4711 in the event that this new name is required for
4712 a file format change.
4715 const string spath = *i;
4717 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4722 /* it is possible that we have the path already
4723 * assigned to a source that has not yet been written
4724 * (ie. the write source for a diskstream). we have to
4725 * check this in order to make sure that our candidate
4726 * path isn't used again, because that can lead to
4727 * two Sources point to the same file with different
4728 * notions of their removability.
4732 string possible_path = Glib::build_filename (spath, name);
4734 if (audio_source_by_path_and_channel (possible_path, 0)) {
4740 return (existing == 0);
4744 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)
4747 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4749 if (Profile->get_trx() && destructive) {
4751 sstr << setfill ('0') << setw (4) << cnt;
4752 sstr << legalized_base;
4754 sstr << legalized_base;
4756 if (take_required || related_exists) {
4768 } else if (nchan > 2) {
4773 /* XXX what? more than 26 channels! */
4784 /** Return a unique name based on \a base for a new internal audio source */
4786 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4789 string possible_name;
4790 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4792 bool some_related_source_name_exists = false;
4794 legalized = legalize_for_path (base);
4796 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4798 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4800 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4802 if (audio_source_name_is_unique (possible_name)) {
4806 some_related_source_name_exists = true;
4809 error << string_compose(
4810 _("There are already %1 recordings for %2, which I consider too many."),
4811 limit, base) << endmsg;
4813 throw failed_constructor();
4817 /* We've established that the new name does not exist in any session
4818 * directory, so now find out which one we should use for this new
4822 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4824 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4829 /** Return a unique name based on `base` for a new internal MIDI source */
4831 Session::new_midi_source_path (const string& base, bool need_lock)
4833 string possible_path;
4834 string possible_name;
4836 possible_name = legalize_for_path (base);
4838 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4839 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4841 /* - the main session folder is the first in the vector.
4842 * - after checking all locations for file-name uniqueness,
4843 * we keep the one from the last iteration as new file name
4844 * - midi files are small and should just be kept in the main session-folder
4846 * -> reverse the array, check main session folder last and use that as location
4849 std::reverse(sdirs.begin(), sdirs.end());
4852 possible_name = bump_name_once (possible_name, '-');
4854 vector<space_and_path>::iterator i;
4855 uint32_t existing = 0;
4857 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4859 possible_path = Glib::build_filename (*i, possible_name + ".mid");
4861 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4865 if (midi_source_by_path (possible_path, need_lock)) {
4870 if (possible_path.size () >= PATH_MAX) {
4871 error << string_compose(
4872 _("There are already many recordings for %1, resulting in a too long file-path %2."),
4873 base, possible_path) << endmsg;
4878 if (existing == 0) {
4883 /* No need to "find best location" for software/app-based RAID, because
4884 MIDI is so small that we always put it in the same place.
4887 return possible_path;
4891 /** Create a new within-session audio source */
4892 boost::shared_ptr<AudioFileSource>
4893 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4895 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4897 if (!path.empty()) {
4898 return boost::dynamic_pointer_cast<AudioFileSource> (
4899 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, sample_rate(), true, true));
4901 throw failed_constructor ();
4905 /** Create a new within-session MIDI source */
4906 boost::shared_ptr<MidiSource>
4907 Session::create_midi_source_for_session (string const & basic_name)
4909 const string path = new_midi_source_path (basic_name);
4911 if (!path.empty()) {
4912 return boost::dynamic_pointer_cast<SMFSource> (
4913 SourceFactory::createWritable (
4914 DataType::MIDI, *this, path, false, sample_rate()));
4916 throw failed_constructor ();
4920 /** Create a new within-session MIDI source */
4921 boost::shared_ptr<MidiSource>
4922 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4924 /* the caller passes in the track the source will be used in,
4925 so that we can keep the numbering sane.
4927 Rationale: a track with the name "Foo" that has had N
4928 captures carried out so far will ALREADY have a write source
4929 named "Foo-N+1.mid" waiting to be used for the next capture.
4931 If we call new_midi_source_name() we will get "Foo-N+2". But
4932 there is no region corresponding to "Foo-N+1", so when
4933 "Foo-N+2" appears in the track, the gap presents the user
4934 with odd behaviour - why did it skip past Foo-N+1?
4936 We could explain this to the user in some odd way, but
4937 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4940 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4943 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4945 std::string name = track->steal_write_source_name ();
4948 return boost::shared_ptr<MidiSource>();
4951 /* MIDI files are small, just put them in the first location of the
4952 session source search path.
4955 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4957 return boost::dynamic_pointer_cast<SMFSource> (
4958 SourceFactory::createWritable (
4959 DataType::MIDI, *this, path, false, sample_rate()));
4963 Session::playlist_is_active (boost::shared_ptr<Playlist> playlist)
4965 Glib::Threads::Mutex::Lock lm (_playlists->lock);
4966 for (SessionPlaylists::List::iterator i = _playlists->playlists.begin(); i != _playlists->playlists.end(); i++) {
4967 if ( (*i) == playlist ) {
4975 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4977 if (playlist->hidden()) {
4981 _playlists->add (playlist);
4984 playlist->release();
4991 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4993 if (deletion_in_progress ()) {
4997 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5003 _playlists->remove (playlist);
5009 Session::set_audition (boost::shared_ptr<Region> r)
5011 pending_audition_region = r;
5012 add_post_transport_work (PostTransportAudition);
5013 _butler->schedule_transport_work ();
5017 Session::audition_playlist ()
5019 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5020 ev->region.reset ();
5026 Session::register_lua_function (
5027 const std::string& name,
5028 const std::string& script,
5029 const LuaScriptParamList& args
5032 Glib::Threads::Mutex::Lock lm (lua_lock);
5034 lua_State* L = lua.getState();
5036 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5037 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5038 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5039 if ((*i)->optional && !(*i)->is_set) { continue; }
5040 tbl_arg[(*i)->name] = (*i)->value;
5042 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5045 LuaScriptsChanged (); /* EMIT SIGNAL */
5050 Session::unregister_lua_function (const std::string& name)
5052 Glib::Threads::Mutex::Lock lm (lua_lock);
5053 (*_lua_del)(name); // throws luabridge::LuaException
5054 lua.collect_garbage ();
5057 LuaScriptsChanged (); /* EMIT SIGNAL */
5061 std::vector<std::string>
5062 Session::registered_lua_functions ()
5064 Glib::Threads::Mutex::Lock lm (lua_lock);
5065 std::vector<std::string> rv;
5068 luabridge::LuaRef list ((*_lua_list)());
5069 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5070 if (!i.key ().isString ()) { assert(0); continue; }
5071 rv.push_back (i.key ().cast<std::string> ());
5078 static void _lua_print (std::string s) {
5079 std::cout << "SessionLua: " << s << "\n";
5084 Session::try_run_lua (pframes_t nframes)
5086 if (_n_lua_scripts == 0) return;
5087 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5089 try { (*_lua_run)(nframes); } catch (...) { }
5090 lua.collect_garbage_step ();
5095 Session::setup_lua ()
5098 lua.Print.connect (&_lua_print);
5102 "function ArdourSession ()"
5103 " local self = { scripts = {}, instances = {} }"
5105 " local remove = function (n)"
5106 " self.scripts[n] = nil"
5107 " self.instances[n] = nil"
5108 " Session:scripts_changed()" // call back
5111 " local addinternal = function (n, f, a)"
5112 " assert(type(n) == 'string', 'function-name must be string')"
5113 " assert(type(f) == 'function', 'Given script is a not a function')"
5114 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5115 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5116 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5117 " 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 }"
5118 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5119 " Session:scripts_changed()" // call back
5122 " local add = function (n, b, a)"
5123 " assert(type(b) == 'string', 'ByteCode must be string')"
5124 " load (b)()" // assigns f
5125 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5126 " addinternal (n, load(f), a)"
5129 " local run = function (...)"
5130 " for n, s in pairs (self.instances) do"
5131 " local status, err = pcall (s, ...)"
5132 " if not status then"
5133 " print ('fn \"'.. n .. '\": ', err)"
5140 " local cleanup = function ()"
5141 " self.scripts = nil"
5142 " self.instances = nil"
5145 " local list = function ()"
5147 " for n, _ in pairs (self.scripts) do"
5153 " local function basic_serialize (o)"
5154 " if type(o) == \"number\" then"
5155 " return tostring(o)"
5157 " return string.format(\"%q\", o)"
5161 " local function serialize (name, value)"
5162 " local rv = name .. ' = '"
5164 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5165 " return rv .. basic_serialize(value) .. ' '"
5166 " elseif type(value) == \"table\" then"
5168 " for k,v in pairs(value) do"
5169 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5170 " rv = rv .. serialize(fieldname, v) .. ' '"
5171 " collectgarbage()" // string concatenation allocates a new string :(
5174 " elseif type(value) == \"function\" then"
5175 " return rv .. string.format(\"%q\", string.dump(value, true))"
5177 " error('cannot save a ' .. type(value))"
5182 " local save = function ()"
5183 " return (serialize('scripts', self.scripts))"
5186 " local restore = function (state)"
5187 " self.scripts = {}"
5189 " for n, s in pairs (scripts) do"
5190 " addinternal (n, load(s['f']), s['a'])"
5194 " return { run = run, add = add, remove = remove,"
5195 " list = list, restore = restore, save = save, cleanup = cleanup}"
5198 " sess = ArdourSession ()"
5199 " ArdourSession = nil"
5201 "function ardour () end"
5204 lua_State* L = lua.getState();
5207 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5208 lua.do_command ("sess = nil"); // hide it.
5209 lua.do_command ("collectgarbage()");
5211 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5212 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5213 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5214 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5215 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5216 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5217 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5218 } catch (luabridge::LuaException const& e) {
5219 fatal << string_compose (_("programming error: %1"),
5220 std::string ("Failed to setup session Lua interpreter") + e.what ())
5222 abort(); /*NOTREACHED*/
5224 fatal << string_compose (_("programming error: %1"),
5225 X_("Failed to setup session Lua interpreter"))
5227 abort(); /*NOTREACHED*/
5231 LuaBindings::stddef (L);
5232 LuaBindings::common (L);
5233 LuaBindings::dsp (L);
5235 luabridge::push <Session *> (L, this);
5236 lua_setglobal (L, "Session");
5240 Session::scripts_changed ()
5242 assert (!lua_lock.trylock()); // must hold lua_lock
5245 luabridge::LuaRef list ((*_lua_list)());
5247 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5248 if (!i.key ().isString ()) { assert(0); continue; }
5251 _n_lua_scripts = cnt;
5252 } catch (luabridge::LuaException const& e) {
5253 fatal << string_compose (_("programming error: %1"),
5254 std::string ("Indexing Lua Session Scripts failed.") + e.what ())
5256 abort(); /*NOTREACHED*/
5258 fatal << string_compose (_("programming error: %1"),
5259 X_("Indexing Lua Session Scripts failed."))
5261 abort(); /*NOTREACHED*/
5266 Session::non_realtime_set_audition ()
5268 assert (pending_audition_region);
5269 auditioner->audition_region (pending_audition_region);
5270 pending_audition_region.reset ();
5271 AuditionActive (true); /* EMIT SIGNAL */
5275 Session::audition_region (boost::shared_ptr<Region> r)
5277 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5283 Session::cancel_audition ()
5288 if (auditioner->auditioning()) {
5289 auditioner->cancel_audition ();
5290 AuditionActive (false); /* EMIT SIGNAL */
5295 Session::is_auditioning () const
5297 /* can be called before we have an auditioner object */
5299 return auditioner->auditioning();
5306 Session::graph_reordered ()
5308 /* don't do this stuff if we are setting up connections
5309 from a set_state() call or creating new tracks. Ditto for deletion.
5312 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5318 /* force all diskstreams to update their capture offset values to
5319 * reflect any changes in latencies within the graph.
5321 update_route_latency (false, true);
5324 /** @return Number of samples that there is disk space available to write,
5327 boost::optional<samplecnt_t>
5328 Session::available_capture_duration ()
5330 Glib::Threads::Mutex::Lock lm (space_lock);
5332 if (_total_free_4k_blocks_uncertain) {
5333 return boost::optional<samplecnt_t> ();
5336 float sample_bytes_on_disk = 4.0; // keep gcc happy
5338 switch (config.get_native_file_data_format()) {
5340 sample_bytes_on_disk = 4.0;
5344 sample_bytes_on_disk = 3.0;
5348 sample_bytes_on_disk = 2.0;
5352 /* impossible, but keep some gcc versions happy */
5353 fatal << string_compose (_("programming error: %1"),
5354 X_("illegal native file data format"))
5356 abort(); /*NOTREACHED*/
5359 double scale = 4096.0 / sample_bytes_on_disk;
5361 if (_total_free_4k_blocks * scale > (double) max_samplecnt) {
5362 return max_samplecnt;
5365 return (samplecnt_t) floor (_total_free_4k_blocks * scale);
5369 Session::tempo_map_changed (const PropertyChange&)
5373 _playlists->update_after_tempo_map_change ();
5375 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5381 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5383 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5384 (*i)->recompute_samples_from_beat ();
5388 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5389 * the given count with the current block size.
5392 Session::ensure_buffers (ChanCount howmany)
5394 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5398 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5400 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5401 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5406 Session::next_insert_id ()
5408 /* this doesn't really loop forever. just think about it */
5411 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5412 if (!insert_bitset[n]) {
5413 insert_bitset[n] = true;
5419 /* none available, so resize and try again */
5421 insert_bitset.resize (insert_bitset.size() + 16, false);
5426 Session::next_send_id ()
5428 /* this doesn't really loop forever. just think about it */
5431 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5432 if (!send_bitset[n]) {
5433 send_bitset[n] = true;
5439 /* none available, so resize and try again */
5441 send_bitset.resize (send_bitset.size() + 16, false);
5446 Session::next_aux_send_id ()
5448 /* this doesn't really loop forever. just think about it */
5451 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5452 if (!aux_send_bitset[n]) {
5453 aux_send_bitset[n] = true;
5459 /* none available, so resize and try again */
5461 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5466 Session::next_return_id ()
5468 /* this doesn't really loop forever. just think about it */
5471 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5472 if (!return_bitset[n]) {
5473 return_bitset[n] = true;
5479 /* none available, so resize and try again */
5481 return_bitset.resize (return_bitset.size() + 16, false);
5486 Session::mark_send_id (uint32_t id)
5488 if (id >= send_bitset.size()) {
5489 send_bitset.resize (id+16, false);
5491 if (send_bitset[id]) {
5492 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5494 send_bitset[id] = true;
5498 Session::mark_aux_send_id (uint32_t id)
5500 if (id >= aux_send_bitset.size()) {
5501 aux_send_bitset.resize (id+16, false);
5503 if (aux_send_bitset[id]) {
5504 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5506 aux_send_bitset[id] = true;
5510 Session::mark_return_id (uint32_t id)
5512 if (id >= return_bitset.size()) {
5513 return_bitset.resize (id+16, false);
5515 if (return_bitset[id]) {
5516 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5518 return_bitset[id] = true;
5522 Session::mark_insert_id (uint32_t id)
5524 if (id >= insert_bitset.size()) {
5525 insert_bitset.resize (id+16, false);
5527 if (insert_bitset[id]) {
5528 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5530 insert_bitset[id] = true;
5534 Session::unmark_send_id (uint32_t id)
5536 if (id < send_bitset.size()) {
5537 send_bitset[id] = false;
5542 Session::unmark_aux_send_id (uint32_t id)
5544 if (id < aux_send_bitset.size()) {
5545 aux_send_bitset[id] = false;
5550 Session::unmark_return_id (uint32_t id)
5552 if (deletion_in_progress ()) {
5555 if (id < return_bitset.size()) {
5556 return_bitset[id] = false;
5561 Session::unmark_insert_id (uint32_t id)
5563 if (id < insert_bitset.size()) {
5564 insert_bitset[id] = false;
5569 Session::reset_native_file_format ()
5571 boost::shared_ptr<RouteList> rl = routes.reader ();
5573 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5574 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5576 /* don't save state as we do this, there's no point */
5577 _state_of_the_state = StateOfTheState (_state_of_the_state | InCleanup);
5578 tr->reset_write_sources (false);
5579 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5585 Session::route_name_unique (string n) const
5587 boost::shared_ptr<RouteList> r = routes.reader ();
5589 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5590 if ((*i)->name() == n) {
5599 Session::route_name_internal (string n) const
5601 if (auditioner && auditioner->name() == n) {
5605 if (_click_io && _click_io->name() == n) {
5613 Session::freeze_all (InterThreadInfo& itt)
5615 boost::shared_ptr<RouteList> r = routes.reader ();
5617 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5619 boost::shared_ptr<Track> t;
5621 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5622 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5632 boost::shared_ptr<Region>
5633 Session::write_one_track (Track& track, samplepos_t start, samplepos_t end,
5634 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5635 InterThreadInfo& itt,
5636 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5637 bool for_export, bool for_freeze)
5639 boost::shared_ptr<Region> result;
5640 boost::shared_ptr<Playlist> playlist;
5641 boost::shared_ptr<Source> source;
5642 ChanCount diskstream_channels (track.n_channels());
5643 samplepos_t position;
5644 samplecnt_t this_chunk;
5646 samplepos_t latency_skip;
5648 samplepos_t len = end - start;
5649 bool need_block_size_reset = false;
5650 ChanCount const max_proc = track.max_processor_streams ();
5651 string legal_playlist_name;
5652 string possible_path;
5654 DataType data_type = track.data_type();
5657 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5658 end, start) << endmsg;
5662 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5663 include_endpoint, for_export, for_freeze);
5665 if (data_type == DataType::MIDI && endpoint && !for_export && !for_freeze && diskstream_channels.n(DataType::AUDIO) > 0) {
5666 data_type = DataType::AUDIO;
5669 if (diskstream_channels.n(data_type) < 1) {
5670 error << _("Cannot write a range with no data.") << endmsg;
5674 // block all process callback handling
5676 block_processing ();
5679 // synchronize with AudioEngine::process_callback()
5680 // make sure processing is not currently running
5681 // and processing_blocked() is honored before
5682 // acquiring thread buffers
5683 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5686 _bounce_processing_active = true;
5688 /* call tree *MUST* hold route_lock */
5690 if ((playlist = track.playlist()) == 0) {
5694 legal_playlist_name = "(bounce)" + legalize_for_path (playlist->name());
5696 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(data_type); ++chan_n) {
5698 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5699 string path = ((data_type == DataType::AUDIO)
5700 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5701 : new_midi_source_path (legal_playlist_name));
5708 source = SourceFactory::createWritable (data_type, *this, path, false, sample_rate());
5711 catch (failed_constructor& err) {
5712 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5716 srcs.push_back (source);
5719 /* tell redirects that care that we are about to use a much larger
5720 * blocksize. this will flush all plugins too, so that they are ready
5721 * to be used for this process.
5724 need_block_size_reset = true;
5725 track.set_block_size (bounce_chunk_size);
5726 _engine.main_thread()->get_buffers ();
5730 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5732 /* create a set of reasonably-sized buffers */
5733 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5734 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5736 buffers.set_count (max_proc);
5738 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5739 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5740 boost::shared_ptr<MidiSource> ms;
5742 afs->prepare_for_peakfile_writes ();
5743 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5744 Source::Lock lock(ms->mutex());
5745 ms->mark_streaming_write_started(lock);
5749 while (to_do && !itt.cancel) {
5751 this_chunk = min (to_do, bounce_chunk_size);
5753 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5757 start += this_chunk;
5758 to_do -= this_chunk;
5759 itt.progress = (float) (1.0 - ((double) to_do / len));
5761 if (latency_skip >= bounce_chunk_size) {
5762 latency_skip -= bounce_chunk_size;
5766 const samplecnt_t current_chunk = this_chunk - latency_skip;
5769 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5770 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5771 boost::shared_ptr<MidiSource> ms;
5774 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5777 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5778 Source::Lock lock(ms->mutex());
5780 const MidiBuffer& buf = buffers.get_midi(0);
5781 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5782 Evoral::Event<samplepos_t> ev = *i;
5783 if (!endpoint || for_export) {
5784 ev.set_time(ev.time() - position);
5786 ms->append_event_samples(lock, ev, ms->natural_position());
5793 /* post-roll, pick up delayed processor output */
5794 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5796 while (latency_skip && !itt.cancel) {
5797 this_chunk = min (latency_skip, bounce_chunk_size);
5798 latency_skip -= this_chunk;
5800 buffers.silence (this_chunk, 0);
5801 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5804 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5805 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5808 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5820 xnow = localtime (&now);
5822 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5823 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5824 boost::shared_ptr<MidiSource> ms;
5827 afs->update_header (position, *xnow, now);
5828 afs->flush_header ();
5829 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5830 Source::Lock lock(ms->mutex());
5831 ms->mark_streaming_write_completed(lock);
5835 /* construct a region to represent the bounced material */
5839 plist.add (Properties::start, 0);
5840 plist.add (Properties::whole_file, true);
5841 plist.add (Properties::length, srcs.front()->length(srcs.front()->natural_position()));
5842 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5844 result = RegionFactory::create (srcs, plist, true);
5850 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5851 (*src)->mark_for_remove ();
5852 (*src)->drop_references ();
5856 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5857 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5860 afs->done_with_peakfile_writes ();
5864 _bounce_processing_active = false;
5866 if (need_block_size_reset) {
5867 _engine.main_thread()->drop_buffers ();
5868 track.set_block_size (get_block_size());
5871 unblock_processing ();
5877 Session::gain_automation_buffer() const
5879 return ProcessThread::gain_automation_buffer ();
5883 Session::trim_automation_buffer() const
5885 return ProcessThread::trim_automation_buffer ();
5889 Session::send_gain_automation_buffer() const
5891 return ProcessThread::send_gain_automation_buffer ();
5895 Session::scratch_automation_buffer() const
5897 return ProcessThread::scratch_automation_buffer ();
5901 Session::pan_automation_buffer() const
5903 return ProcessThread::pan_automation_buffer ();
5907 Session::get_silent_buffers (ChanCount count)
5909 return ProcessThread::get_silent_buffers (count);
5913 Session::get_scratch_buffers (ChanCount count, bool silence)
5915 return ProcessThread::get_scratch_buffers (count, silence);
5919 Session::get_noinplace_buffers (ChanCount count)
5921 return ProcessThread::get_noinplace_buffers (count);
5925 Session::get_route_buffers (ChanCount count, bool silence)
5927 return ProcessThread::get_route_buffers (count, silence);
5932 Session::get_mix_buffers (ChanCount count)
5934 return ProcessThread::get_mix_buffers (count);
5938 Session::ntracks () const
5941 boost::shared_ptr<RouteList> r = routes.reader ();
5943 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5944 if (boost::dynamic_pointer_cast<Track> (*i)) {
5953 Session::nbusses () const
5956 boost::shared_ptr<RouteList> r = routes.reader ();
5958 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5959 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5968 Session::nstripables (bool with_monitor) const
5970 uint32_t rv = routes.reader()->size ();
5971 rv += _vca_manager->vcas ().size ();
5985 Session::plot_process_graph (std::string const& file_name) const {
5986 return _process_graph ? _process_graph->plot (file_name) : false;
5990 Session::add_automation_list(AutomationList *al)
5992 automation_lists[al->id()] = al;
5995 /** @return true if there is at least one record-enabled track, otherwise false */
5997 Session::have_rec_enabled_track () const
5999 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6003 Session::have_rec_disabled_track () const
6005 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6008 /** Update the state of our rec-enabled tracks flag */
6010 Session::update_route_record_state ()
6012 boost::shared_ptr<RouteList> rl = routes.reader ();
6013 RouteList::iterator i = rl->begin();
6014 while (i != rl->end ()) {
6016 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6017 if (tr && tr->rec_enable_control()->get_value()) {
6024 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6026 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6028 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6029 RecordStateChanged (); /* EMIT SIGNAL */
6032 for (i = rl->begin(); i != rl->end (); ++i) {
6033 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6034 if (tr && !tr->rec_enable_control()->get_value()) {
6039 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6041 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6043 if (record_status() == Recording && record_arm_state_changed ) {
6044 RecordArmStateChanged ();
6050 Session::listen_position_changed ()
6053 /* skip duing session restore (already taken care of) */
6056 ProcessorChangeBlocker pcb (this);
6057 boost::shared_ptr<RouteList> r = routes.reader ();
6058 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6059 (*i)->listen_position_changed ();
6064 Session::solo_control_mode_changed ()
6066 if (soloing() || listening()) {
6068 /* We can't use ::clear_all_solo_state() here because during
6069 session loading at program startup, that will queue a call
6070 to rt_clear_all_solo_state() that will not execute until
6071 AFTER solo states have been established (thus throwing away
6072 the session's saved solo state). So just explicitly turn
6075 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6077 clear_all_solo_state (get_routes());
6082 /** Called when a property of one of our route groups changes */
6084 Session::route_group_property_changed (RouteGroup* rg)
6086 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6089 /** Called when a route is added to one of our route groups */
6091 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6093 RouteAddedToRouteGroup (rg, r);
6096 /** Called when a route is removed from one of our route groups */
6098 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6100 update_route_record_state ();
6101 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6103 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6104 remove_route_group (*rg);
6108 boost::shared_ptr<AudioTrack>
6109 Session::get_nth_audio_track (int nth) const
6111 boost::shared_ptr<RouteList> rl = routes.reader ();
6112 rl->sort (Stripable::Sorter ());
6114 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6115 if (!boost::dynamic_pointer_cast<AudioTrack> (*r)) {
6122 return boost::dynamic_pointer_cast<AudioTrack> (*r);
6124 return boost::shared_ptr<AudioTrack> ();
6127 boost::shared_ptr<RouteList>
6128 Session::get_tracks () const
6130 boost::shared_ptr<RouteList> rl = routes.reader ();
6131 boost::shared_ptr<RouteList> tl (new RouteList);
6133 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6134 if (boost::dynamic_pointer_cast<Track> (*r)) {
6135 assert (!(*r)->is_auditioner()); // XXX remove me
6142 boost::shared_ptr<RouteList>
6143 Session::get_routes_with_regions_at (samplepos_t const p) const
6145 boost::shared_ptr<RouteList> r = routes.reader ();
6146 boost::shared_ptr<RouteList> rl (new RouteList);
6148 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6149 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6154 boost::shared_ptr<Playlist> pl = tr->playlist ();
6159 if (pl->has_region_at (p)) {
6168 Session::goto_end ()
6170 if (_session_range_location) {
6171 request_locate (_session_range_location->end(), false);
6173 request_locate (0, false);
6178 Session::goto_start (bool and_roll)
6180 if (_session_range_location) {
6181 request_locate (_session_range_location->start(), and_roll);
6183 request_locate (0, and_roll);
6188 Session::current_start_sample () const
6190 return _session_range_location ? _session_range_location->start() : 0;
6194 Session::current_end_sample () const
6196 return _session_range_location ? _session_range_location->end() : 0;
6200 Session::set_session_range_location (samplepos_t start, samplepos_t end)
6202 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6203 _locations->add (_session_range_location);
6207 Session::step_edit_status_change (bool yn)
6213 send = (_step_editors == 0);
6218 send = (_step_editors == 1);
6221 if (_step_editors > 0) {
6227 StepEditStatusChange (val);
6233 Session::start_time_changed (samplepos_t old)
6235 /* Update the auto loop range to match the session range
6236 (unless the auto loop range has been changed by the user)
6239 Location* s = _locations->session_range_location ();
6244 Location* l = _locations->auto_loop_location ();
6246 if (l && l->start() == old) {
6247 l->set_start (s->start(), true);
6253 Session::end_time_changed (samplepos_t old)
6255 /* Update the auto loop range to match the session range
6256 (unless the auto loop range has been changed by the user)
6259 Location* s = _locations->session_range_location ();
6264 Location* l = _locations->auto_loop_location ();
6266 if (l && l->end() == old) {
6267 l->set_end (s->end(), true);
6272 std::vector<std::string>
6273 Session::source_search_path (DataType type) const
6277 if (session_dirs.size() == 1) {
6279 case DataType::AUDIO:
6280 sp.push_back (_session_dir->sound_path());
6282 case DataType::MIDI:
6283 sp.push_back (_session_dir->midi_path());
6287 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6288 SessionDirectory sdir (i->path);
6290 case DataType::AUDIO:
6291 sp.push_back (sdir.sound_path());
6293 case DataType::MIDI:
6294 sp.push_back (sdir.midi_path());
6300 if (type == DataType::AUDIO) {
6301 const string sound_path_2X = _session_dir->sound_path_2X();
6302 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6303 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6304 sp.push_back (sound_path_2X);
6309 // now check the explicit (possibly user-specified) search path
6312 case DataType::AUDIO:
6313 sp += Searchpath(config.get_audio_search_path ());
6315 case DataType::MIDI:
6316 sp += Searchpath(config.get_midi_search_path ());
6324 Session::ensure_search_path_includes (const string& path, DataType type)
6333 case DataType::AUDIO:
6334 sp += Searchpath(config.get_audio_search_path ());
6336 case DataType::MIDI:
6337 sp += Searchpath (config.get_midi_search_path ());
6341 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6342 /* No need to add this new directory if it has the same inode as
6343 an existing one; checking inode rather than name prevents duplicated
6344 directories when we are using symlinks.
6346 On Windows, I think we could just do if (*i == path) here.
6348 if (PBD::equivalent_paths (*i, path)) {
6356 case DataType::AUDIO:
6357 config.set_audio_search_path (sp.to_string());
6359 case DataType::MIDI:
6360 config.set_midi_search_path (sp.to_string());
6366 Session::remove_dir_from_search_path (const string& dir, DataType type)
6371 case DataType::AUDIO:
6372 sp = Searchpath(config.get_audio_search_path ());
6374 case DataType::MIDI:
6375 sp = Searchpath (config.get_midi_search_path ());
6382 case DataType::AUDIO:
6383 config.set_audio_search_path (sp.to_string());
6385 case DataType::MIDI:
6386 config.set_midi_search_path (sp.to_string());
6392 boost::shared_ptr<Speakers>
6393 Session::get_speakers()
6399 Session::unknown_processors () const
6403 boost::shared_ptr<RouteList> r = routes.reader ();
6404 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6405 list<string> t = (*i)->unknown_processors ();
6406 copy (t.begin(), t.end(), back_inserter (p));
6416 Session::set_worst_io_latencies_x (IOChange, void *)
6418 set_worst_io_latencies ();
6422 Session::send_latency_compensation_change ()
6424 /* As a result of Send::set_output_latency()
6425 * or InternalReturn::set_playback_offset ()
6426 * the send's own latency can change (source track
6427 * is aligned with target bus).
6429 * This can only happen be triggered by
6430 * Route::update_signal_latency ()
6431 * when updating the processor latency.
6433 * We need to walk the graph again to take those changes into account
6434 * (we should probably recurse or process the graph in a 2 step process).
6436 ++_send_latency_changes;
6440 Session::update_route_latency (bool playback, bool apply_to_delayline)
6442 /* Note: RouteList is process-graph sorted */
6443 boost::shared_ptr<RouteList> r = routes.reader ();
6446 /* reverse the list so that we work backwards from the last route to run to the first,
6447 * this is not needed, but can help to reduce the iterations for aux-sends.
6449 RouteList* rl = routes.reader().get();
6450 r.reset (new RouteList (*rl));
6451 reverse (r->begin(), r->end());
6454 bool changed = false;
6457 _send_latency_changes = 0;
6458 _worst_route_latency = 0;
6460 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6461 // if (!(*i)->active()) { continue ; } // TODO
6463 if ((*i)->signal_latency () != (l = (*i)->update_signal_latency (apply_to_delayline))) {
6466 _worst_route_latency = std::max (l, _worst_route_latency);
6469 if (_send_latency_changes > 0) {
6470 // only 1 extra iteration is needed (we allow only 1 level of aux-sends)
6471 // BUT.. jack'n'sends'n'bugs
6472 if (++bailout < 5) {
6473 cerr << "restarting Session::update_latency. # of send changes: " << _send_latency_changes << " iteration: " << bailout << endl;
6478 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_route_latency, (changed ? "yes" : "no")));
6484 Session::update_latency (bool playback)
6486 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6488 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _route_deletion_in_progress) {
6491 if (!_engine.running()) {
6495 /* Note; RouteList is sorted as process-graph */
6496 boost::shared_ptr<RouteList> r = routes.reader ();
6499 /* reverse the list so that we work backwards from the last route to run to the first */
6500 RouteList* rl = routes.reader().get();
6501 r.reset (new RouteList (*rl));
6502 reverse (r->begin(), r->end());
6505 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6506 samplecnt_t latency = (*i)->set_private_port_latencies (playback);
6507 (*i)->set_public_port_latencies (latency, playback);
6511 set_worst_output_latency ();
6512 update_route_latency (true, true);
6514 set_worst_input_latency ();
6515 update_route_latency (false, false);
6518 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6522 Session::initialize_latencies ()
6525 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6526 update_latency (false);
6527 update_latency (true);
6530 set_worst_io_latencies ();
6534 Session::set_worst_io_latencies ()
6536 set_worst_output_latency ();
6537 set_worst_input_latency ();
6541 Session::set_worst_output_latency ()
6543 if (inital_connect_or_deletion_in_progress ()) {
6547 _worst_output_latency = 0;
6549 if (!_engine.running()) {
6553 boost::shared_ptr<RouteList> r = routes.reader ();
6555 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6556 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6559 _worst_output_latency = max (_worst_output_latency, _click_io->latency());
6561 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6565 Session::set_worst_input_latency ()
6567 if (inital_connect_or_deletion_in_progress ()) {
6571 _worst_input_latency = 0;
6573 if (!_engine.running()) {
6577 boost::shared_ptr<RouteList> r = routes.reader ();
6579 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6580 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6583 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6587 Session::update_latency_compensation (bool force_whole_graph)
6589 if (inital_connect_or_deletion_in_progress ()) {
6592 /* this lock is not usually contended, but under certain conditions,
6593 * update_latency_compensation may be called concurrently.
6594 * e.g. drag/drop copy a latent plugin while rolling.
6595 * GUI thread (via route_processors_changed) and
6596 * auto_connect_thread_run may race.
6598 Glib::Threads::Mutex::Lock lx (_update_latency_lock, Glib::Threads::TRY_LOCK);
6600 /* no need to do this twice */
6604 bool some_track_latency_changed = update_route_latency (false, false);
6606 if (some_track_latency_changed || force_whole_graph) {
6607 _engine.update_latencies ();
6608 /* above call will ask the backend up update its latencies, which
6609 * eventually will trigger AudioEngine::latency_callback () and
6610 * call Session::update_latency ()
6613 boost::shared_ptr<RouteList> r = routes.reader ();
6614 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6615 (*i)->apply_latency_compensation ();
6621 Session::session_name_is_legal (const string& path)
6623 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6625 for (int i = 0; illegal_chars[i]; ++i) {
6626 if (path.find (illegal_chars[i]) != string::npos) {
6627 return illegal_chars[i];
6635 Session::notify_presentation_info_change ()
6637 if (deletion_in_progress()) {
6641 reassign_track_numbers();
6645 Session::operation_in_progress (GQuark op) const
6647 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6650 boost::shared_ptr<Port>
6651 Session::ltc_output_port () const
6653 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
6657 Session::reconnect_ltc_output ()
6661 string src = Config->get_ltc_output_port();
6663 _ltc_output->disconnect (this);
6665 if (src != _("None") && !src.empty()) {
6666 _ltc_output->nth (0)->connect (src);
6672 Session::set_range_selection (samplepos_t start, samplepos_t end)
6674 _range_selection = Evoral::Range<samplepos_t> (start, end);
6678 Session::set_object_selection (samplepos_t start, samplepos_t end)
6680 _object_selection = Evoral::Range<samplepos_t> (start, end);
6684 Session::clear_range_selection ()
6686 _range_selection = Evoral::Range<samplepos_t> (-1,-1);
6690 Session::clear_object_selection ()
6692 _object_selection = Evoral::Range<samplepos_t> (-1,-1);
6696 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6697 const ChanCount& input_start,
6698 const ChanCount& output_start,
6699 const ChanCount& input_offset,
6700 const ChanCount& output_offset)
6702 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6703 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6704 input_start, output_start,
6705 input_offset, output_offset));
6707 auto_connect_thread_wakeup ();
6711 Session::auto_connect_thread_wakeup ()
6713 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6714 pthread_cond_signal (&_auto_connect_cond);
6715 pthread_mutex_unlock (&_auto_connect_mutex);
6720 Session::queue_latency_recompute ()
6722 g_atomic_int_inc (&_latency_recompute_pending);
6723 auto_connect_thread_wakeup ();
6727 Session::auto_connect (const AutoConnectRequest& ar)
6729 boost::shared_ptr<Route> route = ar.route.lock();
6731 if (!route) { return; }
6733 if (!IO::connecting_legal) {
6737 /* If both inputs and outputs are auto-connected to physical ports,
6738 * use the max of input and output offsets to ensure auto-connected
6739 * port numbers always match up (e.g. the first audio input and the
6740 * first audio output of the route will have the same physical
6741 * port number). Otherwise just use the lowest input or output
6745 const bool in_out_physical =
6746 (Config->get_input_auto_connect() & AutoConnectPhysical)
6747 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6748 && ar.connect_inputs;
6750 const ChanCount in_offset = in_out_physical
6751 ? ChanCount::max(ar.input_offset, ar.output_offset)
6754 const ChanCount out_offset = in_out_physical
6755 ? ChanCount::max(ar.input_offset, ar.output_offset)
6758 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6759 vector<string> physinputs;
6760 vector<string> physoutputs;
6763 /* for connecting track inputs we only want MIDI ports marked
6767 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
6769 if (!physinputs.empty() && ar.connect_inputs) {
6770 uint32_t nphysical_in = physinputs.size();
6772 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6775 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6776 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6779 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6785 if (!physoutputs.empty()) {
6786 uint32_t nphysical_out = physoutputs.size();
6787 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6791 * do not create new connections if we reached the limit of physical outputs
6794 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6795 ARDOUR::Profile->get_trx () &&
6796 ar.output_offset.get(*t) == nphysical_out ) {
6800 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6801 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6802 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6803 /* master bus is audio only */
6804 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6805 port = _master_out->input()->ports().port(*t,
6806 i % _master_out->input()->n_ports().get(*t))->name();
6810 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6819 Session::auto_connect_thread_start ()
6821 if (g_atomic_int_get (&_ac_thread_active)) {
6825 while (!_auto_connect_queue.empty ()) {
6826 _auto_connect_queue.pop ();
6829 g_atomic_int_set (&_ac_thread_active, 1);
6830 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6831 g_atomic_int_set (&_ac_thread_active, 0);
6836 Session::auto_connect_thread_terminate ()
6838 if (!g_atomic_int_get (&_ac_thread_active)) {
6843 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6844 while (!_auto_connect_queue.empty ()) {
6845 _auto_connect_queue.pop ();
6849 /* cannot use auto_connect_thread_wakeup() because that is allowed to
6850 * fail to wakeup the thread.
6853 pthread_mutex_lock (&_auto_connect_mutex);
6854 g_atomic_int_set (&_ac_thread_active, 0);
6855 pthread_cond_signal (&_auto_connect_cond);
6856 pthread_mutex_unlock (&_auto_connect_mutex);
6859 pthread_join (_auto_connect_thread, &status);
6863 Session::auto_connect_thread (void *arg)
6865 Session *s = static_cast<Session *>(arg);
6866 s->auto_connect_thread_run ();
6872 Session::auto_connect_thread_run ()
6874 pthread_set_name (X_("autoconnect"));
6875 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6876 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6877 pthread_mutex_lock (&_auto_connect_mutex);
6878 while (g_atomic_int_get (&_ac_thread_active)) {
6880 if (!_auto_connect_queue.empty ()) {
6881 // Why would we need the process lock ??
6882 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
6883 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
6884 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
6885 // We have control over those, but what does jack do?
6886 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6888 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6889 while (!_auto_connect_queue.empty ()) {
6890 const AutoConnectRequest ar (_auto_connect_queue.front());
6891 _auto_connect_queue.pop ();
6898 if (!actively_recording ()) { // might not be needed,
6899 /* this is only used for updating plugin latencies, the
6900 * graph does not change. so it's safe in general.
6902 * update_latency_compensation ()
6903 * calls DiskWriter::set_capture_offset () which
6904 * modifies the capture-offset, which can be a problem.
6906 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
6907 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6908 update_latency_compensation ();
6913 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
6914 // jack1 cannot cope with removing ports while processing
6915 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6916 AudioEngine::instance()->clear_pending_port_deletions ();
6919 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
6921 pthread_mutex_unlock (&_auto_connect_mutex);
6925 Session::cancel_all_solo ()
6929 get_stripables (sl);
6931 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
6932 clear_all_solo_state (routes.reader());
6936 Session::maybe_update_tempo_from_midiclock_tempo (float bpm)
6938 if (_tempo_map->n_tempos() == 1) {
6939 TempoSection& ts (_tempo_map->tempo_section_at_sample (0));
6940 if (fabs (ts.note_types_per_minute() - bpm) > (0.01 * ts.note_types_per_minute())) {
6941 const Tempo tempo (bpm, 4.0, bpm);
6942 std::cerr << "new tempo " << bpm << " old " << ts.note_types_per_minute() << std::endl;
6943 _tempo_map->replace_tempo (ts, tempo, 0.0, 0.0, AudioTime);