2 Copyright (C) 1999-2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
36 #include <boost/algorithm/string/erase.hpp>
38 #include "pbd/basename.h"
39 #include "pbd/convert.h"
40 #include "pbd/convert.h"
41 #include "pbd/error.h"
42 #include "pbd/file_utils.h"
44 #include "pbd/pthread_utils.h"
45 #include "pbd/search_path.h"
46 #include "pbd/stacktrace.h"
47 #include "pbd/stl_delete.h"
48 #include "pbd/replace_all.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/boost_debug.h"
62 #include "ardour/buffer_manager.h"
63 #include "ardour/buffer_set.h"
64 #include "ardour/bundle.h"
65 #include "ardour/butler.h"
66 #include "ardour/click.h"
67 #include "ardour/control_protocol_manager.h"
68 #include "ardour/data_type.h"
69 #include "ardour/debug.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
74 #include "ardour/filename_extensions.h"
75 #include "ardour/gain_control.h"
76 #include "ardour/graph.h"
77 #include "ardour/luabindings.h"
78 #include "ardour/midiport_manager.h"
79 #include "ardour/scene_changer.h"
80 #include "ardour/midi_patch_manager.h"
81 #include "ardour/midi_track.h"
82 #include "ardour/midi_ui.h"
83 #include "ardour/operations.h"
84 #include "ardour/playlist.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/revision.h"
94 #include "ardour/route_graph.h"
95 #include "ardour/route_group.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/solo_isolate_control.h"
102 #include "ardour/source_factory.h"
103 #include "ardour/speakers.h"
104 #include "ardour/tempo.h"
105 #include "ardour/ticker.h"
106 #include "ardour/track.h"
107 #include "ardour/user_bundle.h"
108 #include "ardour/utils.h"
109 #include "ardour/vca_manager.h"
110 #include "ardour/vca.h"
112 #include "midi++/port.h"
113 #include "midi++/mmc.h"
115 #include "LuaBridge/LuaBridge.h"
119 #include <glibmm/checksum.h>
128 using namespace ARDOUR;
131 bool Session::_disable_all_loaded_plugins = false;
132 bool Session::_bypass_all_loaded_plugins = false;
133 guint Session::_name_id_counter = 0;
135 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
136 PBD::Signal1<void,std::string> Session::Dialog;
137 PBD::Signal0<int> Session::AskAboutPendingState;
138 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
139 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
140 PBD::Signal0<void> Session::SendFeedback;
141 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
143 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
144 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
145 PBD::Signal2<void,std::string, std::string> Session::Exported;
146 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
147 PBD::Signal0<void> Session::Quit;
148 PBD::Signal0<void> Session::FeedbackDetected;
149 PBD::Signal0<void> Session::SuccessfulGraphSort;
150 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
152 const framecnt_t Session::bounce_chunk_size = 8192;
153 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
154 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
156 // seconds should be added after the region exceeds end marker
157 #ifdef USE_TRACKS_CODE_FEATURES
158 const uint32_t Session::session_end_shift = 5;
160 const uint32_t Session::session_end_shift = 0;
163 /** @param snapshot_name Snapshot name, without .ardour suffix */
164 Session::Session (AudioEngine &eng,
165 const string& fullpath,
166 const string& snapshot_name,
167 BusProfile* bus_profile,
169 : playlists (new SessionPlaylists)
171 , process_function (&Session::process_with_events)
172 , _bounce_processing_active (false)
173 , waiting_for_sync_offset (false)
174 , _base_frame_rate (0)
175 , _nominal_frame_rate (0)
176 , _current_frame_rate (0)
177 , transport_sub_state (0)
178 , _record_status (Disabled)
179 , _transport_frame (0)
180 , _session_range_location (0)
181 , _session_range_end_is_free (true)
184 , _transport_speed (0)
185 , _default_transport_speed (1.0)
186 , _last_transport_speed (0)
187 , _target_transport_speed (0.0)
188 , auto_play_legal (false)
189 , _last_slave_transport_frame (0)
190 , maximum_output_latency (0)
191 , _requested_return_frame (-1)
192 , current_block_size (0)
193 , _worst_output_latency (0)
194 , _worst_input_latency (0)
195 , _worst_track_latency (0)
196 , _have_captured (false)
197 , _non_soloed_outs_muted (false)
200 , _solo_isolated_cnt (0)
202 , _was_seamless (Config->get_seamless_loop ())
203 , _under_nsm_control (false)
205 , delta_accumulator_cnt (0)
206 , average_slave_delta (1800) // !!! why 1800 ???
208 , have_first_delta_accumulator (false)
209 , _slave_state (Stopped)
210 , _mtc_active (false)
211 , _ltc_active (false)
212 , post_export_sync (false)
213 , post_export_position (0)
215 , _export_rolling (false)
216 , _export_preroll (0)
217 , _export_latency (0)
218 , _pre_export_mmc_enabled (false)
219 , _name (snapshot_name)
221 , _send_qf_mtc (false)
222 , _pframes_since_last_mtc (0)
223 , session_midi_feedback (0)
225 , loop_changing (false)
227 , _session_dir (new SessionDirectory (fullpath))
228 , _current_snapshot_name (snapshot_name)
230 , state_was_pending (false)
231 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
233 , _save_queued (false)
234 , _last_roll_location (0)
235 , _last_roll_or_reversal_location (0)
236 , _last_record_location (0)
237 , pending_locate_roll (false)
238 , pending_locate_frame (0)
239 , pending_locate_flush (false)
240 , pending_abort (false)
241 , pending_auto_loop (false)
242 , _mempool ("Session", 2097152)
243 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
245 , _butler (new Butler (*this))
246 , _post_transport_work (0)
247 , cumulative_rf_motion (0)
249 , _locations (new Locations (*this))
250 , _ignore_skips_updates (false)
251 , _rt_thread_active (false)
252 , _rt_emit_pending (false)
253 , _ac_thread_active (false)
254 , _latency_recompute_pending (0)
256 , outbound_mtc_timecode_frame (0)
257 , next_quarter_frame_to_send (-1)
258 , _frames_per_timecode_frame (0)
259 , _frames_per_hour (0)
260 , _timecode_frames_per_hour (0)
261 , last_timecode_valid (false)
262 , last_timecode_when (0)
263 , _send_timecode_update (false)
275 , ltc_timecode_offset (0)
276 , ltc_timecode_negative_offset (false)
277 , midi_control_ui (0)
279 , _all_route_group (new RouteGroup (*this, "all"))
280 , routes (new RouteList)
281 , _adding_routes_in_progress (false)
282 , _reconnecting_routes_in_progress (false)
283 , _route_deletion_in_progress (false)
284 , destructive_index (0)
285 , _track_number_decimals(1)
286 , default_fade_steepness (0)
287 , default_fade_msecs (0)
288 , _total_free_4k_blocks (0)
289 , _total_free_4k_blocks_uncertain (false)
290 , no_questions_about_missing_files (false)
293 , _bundles (new BundleList)
294 , _bundle_xml_node (0)
298 , click_emphasis_data (0)
300 , click_emphasis_length (0)
301 , _clicks_cleared (0)
302 , _play_range (false)
303 , _range_selection (-1,-1)
304 , _object_selection (-1,-1)
306 , first_file_data_format_reset (true)
307 , first_file_header_format_reset (true)
308 , have_looped (false)
309 , _have_rec_enabled_track (false)
310 , _have_rec_disabled_track (true)
312 , _suspend_timecode_transmission (0)
313 , _speakers (new Speakers)
314 , ignore_route_processor_changes (false)
319 , _vca_manager (new VCAManager (*this))
323 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
325 pthread_mutex_init (&_rt_emit_mutex, 0);
326 pthread_cond_init (&_rt_emit_cond, 0);
328 pthread_mutex_init (&_auto_connect_mutex, 0);
329 pthread_cond_init (&_auto_connect_cond, 0);
331 init_name_id_counter (1); // reset for new sessions, start at 1
332 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
334 pre_engine_init (fullpath);
340 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
342 #ifdef USE_TRACKS_CODE_FEATURES
343 sr = EngineStateController::instance()->get_current_sample_rate();
345 if (ensure_engine (sr, true)) {
347 throw SessionException (_("Cannot connect to audio/midi engine"));
350 // set samplerate for plugins added early
351 // e.g from templates or MB channelstrip
352 set_block_size (_engine.samples_per_cycle());
353 set_frame_rate (_engine.sample_rate());
355 if (create (mix_template, bus_profile)) {
357 throw SessionException (_("Session initialization failed"));
360 /* if a mix template was provided, then ::create() will
361 * have copied it into the session and we need to load it
362 * so that we have the state ready for ::set_state()
363 * after the engine is started.
365 * Note that we do NOT try to get the sample rate from
366 * the template at this time, though doing so would
367 * be easy if we decided this was an appropriate part
371 if (!mix_template.empty()) {
372 if (load_state (_current_snapshot_name)) {
373 throw SessionException (_("Failed to load template/snapshot state"));
375 store_recent_templates (mix_template);
378 /* load default session properties - if any */
383 if (load_state (_current_snapshot_name)) {
384 throw SessionException (_("Failed to load state"));
387 /* try to get sample rate from XML state so that we
388 * can influence the SR if we set up the audio
393 XMLProperty const * prop;
394 XMLNode const * root (state_tree->root());
395 if ((prop = root->property (X_("sample-rate"))) != 0) {
396 sr = atoi (prop->value());
400 if (ensure_engine (sr, false)) {
402 throw SessionException (_("Cannot connect to audio/midi engine"));
406 if (post_engine_init ()) {
408 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
411 store_recent_sessions (_name, _path);
413 bool was_dirty = dirty();
415 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
417 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
418 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
421 DirtyChanged (); /* EMIT SIGNAL */
424 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
425 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
427 emit_thread_start ();
428 auto_connect_thread_start ();
430 /* hook us up to the engine since we are now completely constructed */
432 BootMessage (_("Connect to engine"));
434 _engine.set_session (this);
435 _engine.reset_timebase ();
437 #ifdef USE_TRACKS_CODE_FEATURES
439 EngineStateController::instance()->set_session(this);
442 if ( ARDOUR::Profile->get_trx () ) {
444 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
445 * each available input must have corresponding track when session starts.
448 uint32_t how_many (0);
450 std::vector<std::string> inputs;
451 EngineStateController::instance()->get_physical_audio_inputs(inputs);
453 how_many = inputs.size();
455 list<boost::shared_ptr<AudioTrack> > tracks;
457 // Track names after driver
458 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
459 string track_name = "";
460 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
462 track_name = inputs[i];
463 replace_all (track_name, "system:capture", "");
465 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
466 tracks.insert(tracks.begin(), single_track.front());
468 } else { // Default track names
469 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
472 if (tracks.size() != how_many) {
474 throw failed_constructor ();
483 BootMessage (_("Session loading complete"));
495 Session::next_name_id ()
497 return g_atomic_int_add (&_name_id_counter, 1);
501 Session::name_id_counter ()
503 return g_atomic_int_get (&_name_id_counter);
507 Session::init_name_id_counter (guint n)
509 g_atomic_int_set (&_name_id_counter, n);
513 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
515 if (_engine.current_backend() == 0) {
516 /* backend is unknown ... */
517 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
518 if (r.get_value_or (-1) != 0) {
521 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
523 } else if (_engine.setup_required()) {
524 /* backend is known, but setup is needed */
525 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
526 if (r.get_value_or (-1) != 0) {
529 } else if (!_engine.running()) {
530 if (_engine.start()) {
535 /* at this point the engine should be running */
537 if (!_engine.running()) {
541 return immediately_post_engine ();
546 Session::immediately_post_engine ()
548 /* Do various initializations that should take place directly after we
549 * know that the engine is running, but before we either create a
550 * session or set state for an existing one.
553 if (how_many_dsp_threads () > 1) {
554 /* For now, only create the graph if we are using >1 DSP threads, as
555 it is a bit slower than the old code with 1 thread.
557 _process_graph.reset (new Graph (*this));
560 /* every time we reconnect, recompute worst case output latencies */
562 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
564 if (synced_to_engine()) {
565 _engine.transport_stop ();
568 if (config.get_jack_time_master()) {
569 _engine.transport_locate (_transport_frame);
574 BootMessage (_("Set up LTC"));
576 BootMessage (_("Set up Click"));
578 BootMessage (_("Set up standard connections"));
582 catch (failed_constructor& err) {
586 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
588 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
596 vector<void*> debug_pointers;
598 /* if we got to here, leaving pending capture state around
602 remove_pending_capture_state ();
606 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
608 /* stop autoconnecting */
609 auto_connect_thread_terminate ();
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 ControlProtocolManager::instance().drop_protocols ();
622 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
624 _engine.remove_session ();
626 #ifdef USE_TRACKS_CODE_FEATURES
627 EngineStateController::instance()->remove_session();
630 /* deregister all ports - there will be no process or any other
631 * callbacks from the engine any more.
634 Port::PortDrop (); /* EMIT SIGNAL */
638 /* clear history so that no references to objects are held any more */
642 /* clear state tree so that no references to objects are held any more */
647 // unregister all lua functions, drop held references (if any)
649 lua.do_command ("Session = nil");
657 lua.collect_garbage ();
659 /* reset dynamic state version back to default */
660 Stateful::loading_state_version = 0;
662 _butler->drop_references ();
666 delete _all_route_group;
668 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
669 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
673 if (click_data != default_click) {
674 delete [] click_data;
677 if (click_emphasis_data != default_click_emphasis) {
678 delete [] click_emphasis_data;
683 /* need to remove auditioner before monitoring section
684 * otherwise it is re-connected */
687 /* drop references to routes held by the monitoring section
688 * specifically _monitor_out aux/listen references */
689 remove_monitor_section();
691 /* clear out any pending dead wood from RCU managed objects */
696 AudioDiskstream::free_working_buffers();
698 /* tell everyone who is still standing that we're about to die */
701 /* tell everyone to drop references and delete objects as we go */
703 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
704 RegionFactory::delete_all_regions ();
706 /* Do this early so that VCAs no longer hold references to routes */
708 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
711 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
713 /* reset these three references to special routes before we do the usual route delete thing */
715 _master_out.reset ();
716 _monitor_out.reset ();
719 RCUWriter<RouteList> writer (routes);
720 boost::shared_ptr<RouteList> r = writer.get_copy ();
722 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
723 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
724 (*i)->drop_references ();
728 /* writer goes out of scope and updates master */
733 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
734 Glib::Threads::Mutex::Lock lm (source_lock);
735 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
736 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
737 i->second->drop_references ();
743 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
746 emit_thread_terminate ();
748 pthread_cond_destroy (&_rt_emit_cond);
749 pthread_mutex_destroy (&_rt_emit_mutex);
751 pthread_cond_destroy (&_auto_connect_cond);
752 pthread_mutex_destroy (&_auto_connect_mutex);
754 delete _scene_changer; _scene_changer = 0;
755 delete midi_control_ui; midi_control_ui = 0;
757 delete _mmc; _mmc = 0;
758 delete _midi_ports; _midi_ports = 0;
759 delete _locations; _locations = 0;
764 /* clear event queue, the session is gone, nobody is interested in
765 * those anymore, but they do leak memory if not removed
767 while (!immediate_events.empty ()) {
768 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
769 SessionEvent *ev = immediate_events.front ();
770 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
771 immediate_events.pop_front ();
775 case SessionEvent::AutoLoop:
776 case SessionEvent::AutoLoopDeclick:
777 case SessionEvent::Skip:
778 case SessionEvent::PunchIn:
779 case SessionEvent::PunchOut:
780 case SessionEvent::StopOnce:
781 case SessionEvent::RangeStop:
782 case SessionEvent::RangeLocate:
786 case SessionEvent::RealTimeOperation:
793 del = del && !_remove_event (ev);
800 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
802 BOOST_SHOW_POINTERS ();
806 Session::setup_ltc ()
810 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
811 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
813 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
814 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
817 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
818 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
820 reconnect_ltc_input ();
823 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
824 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
827 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
828 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
830 reconnect_ltc_output ();
833 /* fix up names of LTC ports because we don't want the normal
834 * IO style of NAME/TYPE-{in,out}N
837 _ltc_input->nth (0)->set_name (X_("LTC-in"));
838 _ltc_output->nth (0)->set_name (X_("LTC-out"));
842 Session::setup_click ()
846 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
847 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
849 _click_io.reset (new ClickIO (*this, X_("Click")));
850 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
851 _click_gain->activate ();
853 setup_click_state (state_tree->root());
855 setup_click_state (0);
860 Session::setup_click_state (const XMLNode* node)
862 const XMLNode* child = 0;
864 if (node && (child = find_named_node (*node, "Click")) != 0) {
866 /* existing state for Click */
869 if (Stateful::loading_state_version < 3000) {
870 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
872 const XMLNodeList& children (child->children());
873 XMLNodeList::const_iterator i = children.begin();
874 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
876 if (i != children.end()) {
877 c = _click_gain->set_state (**i, Stateful::loading_state_version);
883 _clicking = Config->get_clicking ();
887 error << _("could not setup Click I/O") << endmsg;
894 /* default state for Click: dual-mono to first 2 physical outputs */
897 _engine.get_physical_outputs (DataType::AUDIO, outs);
899 for (uint32_t physport = 0; physport < 2; ++physport) {
900 if (outs.size() > physport) {
901 if (_click_io->add_port (outs[physport], this)) {
902 // relax, even though its an error
907 if (_click_io->n_ports () > ChanCount::ZERO) {
908 _clicking = Config->get_clicking ();
914 Session::setup_bundles ()
918 RCUWriter<BundleList> writer (_bundles);
919 boost::shared_ptr<BundleList> b = writer.get_copy ();
920 for (BundleList::iterator i = b->begin(); i != b->end();) {
921 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
929 vector<string> inputs[DataType::num_types];
930 vector<string> outputs[DataType::num_types];
931 for (uint32_t i = 0; i < DataType::num_types; ++i) {
932 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
933 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
936 /* Create a set of Bundle objects that map
937 to the physical I/O currently available. We create both
938 mono and stereo bundles, so that the common cases of mono
939 and stereo tracks get bundles to put in their mixer strip
940 in / out menus. There may be a nicer way of achieving that;
941 it doesn't really scale that well to higher channel counts
944 /* mono output bundles */
946 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
948 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
950 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
952 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
955 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
956 c->add_channel (_("mono"), DataType::AUDIO);
957 c->set_port (0, outputs[DataType::AUDIO][np]);
959 add_bundle (c, false);
962 /* stereo output bundles */
964 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
965 if (np + 1 < outputs[DataType::AUDIO].size()) {
967 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
968 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
969 c->add_channel (_("L"), DataType::AUDIO);
970 c->set_port (0, outputs[DataType::AUDIO][np]);
971 c->add_channel (_("R"), DataType::AUDIO);
972 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
974 add_bundle (c, false);
978 /* mono input bundles */
980 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
982 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
984 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
986 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
989 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
990 c->add_channel (_("mono"), DataType::AUDIO);
991 c->set_port (0, inputs[DataType::AUDIO][np]);
993 add_bundle (c, false);
996 /* stereo input bundles */
998 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
999 if (np + 1 < inputs[DataType::AUDIO].size()) {
1001 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1003 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1004 c->add_channel (_("L"), DataType::AUDIO);
1005 c->set_port (0, inputs[DataType::AUDIO][np]);
1006 c->add_channel (_("R"), DataType::AUDIO);
1007 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1009 add_bundle (c, false);
1013 /* MIDI input bundles */
1015 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1016 string n = inputs[DataType::MIDI][np];
1017 std::string pn = _engine.get_pretty_name_by_name (n);
1021 boost::erase_first (n, X_("alsa_pcm:"));
1023 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1024 c->add_channel ("", DataType::MIDI);
1025 c->set_port (0, inputs[DataType::MIDI][np]);
1026 add_bundle (c, false);
1029 /* MIDI output bundles */
1031 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1032 string n = outputs[DataType::MIDI][np];
1033 std::string pn = _engine.get_pretty_name_by_name (n);
1037 boost::erase_first (n, X_("alsa_pcm:"));
1039 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1040 c->add_channel ("", DataType::MIDI);
1041 c->set_port (0, outputs[DataType::MIDI][np]);
1042 add_bundle (c, false);
1045 // we trust the backend to only calls us if there's a change
1046 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1050 Session::auto_connect_master_bus ()
1052 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1056 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1057 // In this case it means "Multi Out" output mode
1058 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1062 /* if requested auto-connect the outputs to the first N physical ports.
1065 uint32_t limit = _master_out->n_outputs().n_total();
1066 vector<string> outputs[DataType::num_types];
1068 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1069 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1072 for (uint32_t n = 0; n < limit; ++n) {
1073 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1075 if (outputs[p->type()].size() > n) {
1076 connect_to = outputs[p->type()][n];
1079 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1080 if (_master_out->output()->connect (p, connect_to, this)) {
1081 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1090 Session::remove_monitor_section ()
1092 if (!_monitor_out || Profile->get_trx()) {
1096 /* force reversion to Solo-In-Place */
1097 Config->set_solo_control_is_listen_control (false);
1099 /* if we are auditioning, cancel it ... this is a workaround
1100 to a problem (auditioning does not execute the process graph,
1101 which is needed to remove routes when using >1 core for processing)
1106 /* Hold process lock while doing this so that we don't hear bits and
1107 * pieces of audio as we work on each route.
1110 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1112 /* Connect tracks to monitor section. Note that in an
1113 existing session, the internal sends will already exist, but we want the
1114 routes to notice that they connect to the control out specifically.
1118 boost::shared_ptr<RouteList> r = routes.reader ();
1119 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1121 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1123 if ((*x)->is_monitor()) {
1125 } else if ((*x)->is_master()) {
1128 (*x)->remove_aux_or_listen (_monitor_out);
1133 remove_route (_monitor_out);
1134 if (_state_of_the_state & Deletion) {
1138 auto_connect_master_bus ();
1141 auditioner->connect ();
1144 Config->ParameterChanged ("use-monitor-bus");
1148 Session::add_monitor_section ()
1152 if (_monitor_out || !_master_out || Profile->get_trx()) {
1156 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1162 BOOST_MARK_ROUTE(r);
1165 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1166 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1167 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1169 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1174 add_routes (rl, false, false, false, 0);
1176 assert (_monitor_out);
1178 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1179 are undefined, at best.
1182 uint32_t limit = _monitor_out->n_inputs().n_audio();
1186 /* connect the inputs to the master bus outputs. this
1187 * represents a separate data feed from the internal sends from
1188 * each route. as of jan 2011, it allows the monitor section to
1189 * conditionally ignore either the internal sends or the normal
1190 * input feed, but we should really find a better way to do
1194 _master_out->output()->disconnect (this);
1196 for (uint32_t n = 0; n < limit; ++n) {
1197 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1198 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1201 string connect_to = o->name();
1202 if (_monitor_out->input()->connect (p, connect_to, this)) {
1203 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1211 /* if monitor section is not connected, connect it to physical outs
1214 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1216 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1218 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1221 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1223 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1224 Config->get_monitor_bus_preferred_bundle())
1230 /* Monitor bus is audio only */
1232 vector<string> outputs[DataType::num_types];
1234 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1235 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1238 uint32_t mod = outputs[DataType::AUDIO].size();
1239 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1243 for (uint32_t n = 0; n < limit; ++n) {
1245 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1247 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1248 connect_to = outputs[DataType::AUDIO][n % mod];
1251 if (!connect_to.empty()) {
1252 if (_monitor_out->output()->connect (p, connect_to, this)) {
1253 error << string_compose (
1254 _("cannot connect control output %1 to %2"),
1265 /* Hold process lock while doing this so that we don't hear bits and
1266 * pieces of audio as we work on each route.
1269 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1271 /* Connect tracks to monitor section. Note that in an
1272 existing session, the internal sends will already exist, but we want the
1273 routes to notice that they connect to the control out specifically.
1277 boost::shared_ptr<RouteList> rls = routes.reader ();
1279 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1281 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1283 if ((*x)->is_monitor()) {
1285 } else if ((*x)->is_master()) {
1288 (*x)->enable_monitor_send ();
1293 auditioner->connect ();
1295 Config->ParameterChanged ("use-monitor-bus");
1299 Session::reset_monitor_section ()
1301 /* Process lock should be held by the caller.*/
1303 if (!_monitor_out || Profile->get_trx()) {
1307 uint32_t limit = _master_out->n_outputs().n_audio();
1309 /* connect the inputs to the master bus outputs. this
1310 * represents a separate data feed from the internal sends from
1311 * each route. as of jan 2011, it allows the monitor section to
1312 * conditionally ignore either the internal sends or the normal
1313 * input feed, but we should really find a better way to do
1317 _master_out->output()->disconnect (this);
1318 _monitor_out->output()->disconnect (this);
1320 // monitor section follow master bus - except midi
1321 ChanCount mon_chn (_master_out->output()->n_ports());
1322 mon_chn.set_midi (0);
1324 _monitor_out->input()->ensure_io (mon_chn, false, this);
1325 _monitor_out->output()->ensure_io (mon_chn, false, this);
1327 for (uint32_t n = 0; n < limit; ++n) {
1328 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1329 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1332 string connect_to = o->name();
1333 if (_monitor_out->input()->connect (p, connect_to, this)) {
1334 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1341 /* connect monitor section to physical outs
1344 if (Config->get_auto_connect_standard_busses()) {
1346 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1348 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1351 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1353 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1354 Config->get_monitor_bus_preferred_bundle())
1360 /* Monitor bus is audio only */
1362 vector<string> outputs[DataType::num_types];
1364 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1365 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1368 uint32_t mod = outputs[DataType::AUDIO].size();
1369 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1373 for (uint32_t n = 0; n < limit; ++n) {
1375 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1377 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1378 connect_to = outputs[DataType::AUDIO][n % mod];
1381 if (!connect_to.empty()) {
1382 if (_monitor_out->output()->connect (p, connect_to, this)) {
1383 error << string_compose (
1384 _("cannot connect control output %1 to %2"),
1395 /* Connect tracks to monitor section. Note that in an
1396 existing session, the internal sends will already exist, but we want the
1397 routes to notice that they connect to the control out specifically.
1401 boost::shared_ptr<RouteList> rls = routes.reader ();
1403 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1405 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1407 if ((*x)->is_monitor()) {
1409 } else if ((*x)->is_master()) {
1412 (*x)->enable_monitor_send ();
1418 Session::hookup_io ()
1420 /* stop graph reordering notifications from
1421 causing resorts, etc.
1424 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1428 /* we delay creating the auditioner till now because
1429 it makes its own connections to ports.
1433 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1435 throw failed_constructor ();
1437 a->use_new_diskstream ();
1441 catch (failed_constructor& err) {
1442 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1446 /* load bundles, which we may have postponed earlier on */
1447 if (_bundle_xml_node) {
1448 load_bundles (*_bundle_xml_node);
1449 delete _bundle_xml_node;
1452 /* Tell all IO objects to connect themselves together */
1454 IO::enable_connecting ();
1456 /* Now tell all "floating" ports to connect to whatever
1457 they should be connected to.
1460 AudioEngine::instance()->reconnect_ports ();
1462 /* Anyone who cares about input state, wake up and do something */
1464 IOConnectionsComplete (); /* EMIT SIGNAL */
1466 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1468 /* now handle the whole enchilada as if it was one
1469 graph reorder event.
1474 /* update the full solo state, which can't be
1475 correctly determined on a per-route basis, but
1476 needs the global overview that only the session
1480 update_route_solo_state ();
1484 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1486 boost::shared_ptr<Track> track = wp.lock ();
1491 boost::shared_ptr<Playlist> playlist;
1493 if ((playlist = track->playlist()) != 0) {
1494 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1495 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1496 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1501 Session::record_enabling_legal () const
1503 /* this used to be in here, but survey says.... we don't need to restrict it */
1504 // if (record_status() == Recording) {
1508 if (Config->get_all_safe()) {
1515 Session::set_track_monitor_input_status (bool yn)
1517 boost::shared_ptr<RouteList> rl = routes.reader ();
1518 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1519 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1520 if (tr && tr->rec_enable_control()->get_value()) {
1521 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1522 tr->request_input_monitoring (yn);
1528 Session::auto_punch_start_changed (Location* location)
1530 replace_event (SessionEvent::PunchIn, location->start());
1532 if (get_record_enabled() && config.get_punch_in()) {
1533 /* capture start has been changed, so save new pending state */
1534 save_state ("", true);
1539 Session::auto_punch_end_changed (Location* location)
1541 framepos_t when_to_stop = location->end();
1542 // when_to_stop += _worst_output_latency + _worst_input_latency;
1543 replace_event (SessionEvent::PunchOut, when_to_stop);
1547 Session::auto_punch_changed (Location* location)
1549 framepos_t when_to_stop = location->end();
1551 replace_event (SessionEvent::PunchIn, location->start());
1552 //when_to_stop += _worst_output_latency + _worst_input_latency;
1553 replace_event (SessionEvent::PunchOut, when_to_stop);
1556 /** @param loc A loop location.
1557 * @param pos Filled in with the start time of the required fade-out (in session frames).
1558 * @param length Filled in with the length of the required fade-out.
1561 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1563 pos = max (loc->start(), loc->end() - 64);
1564 length = loc->end() - pos;
1568 Session::auto_loop_changed (Location* location)
1570 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1573 auto_loop_declick_range (location, dcp, dcl);
1575 if (transport_rolling() && play_loop) {
1577 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1579 // if (_transport_frame > location->end()) {
1581 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1582 // relocate to beginning of loop
1583 clear_events (SessionEvent::LocateRoll);
1585 request_locate (location->start(), true);
1588 else if (Config->get_seamless_loop() && !loop_changing) {
1590 // schedule a locate-roll to refill the diskstreams at the
1591 // previous loop end
1592 loop_changing = true;
1594 if (location->end() > last_loopend) {
1595 clear_events (SessionEvent::LocateRoll);
1596 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1602 clear_events (SessionEvent::AutoLoopDeclick);
1603 clear_events (SessionEvent::AutoLoop);
1606 /* possibly move playhead if not rolling; if we are rolling we'll move
1607 to the loop start on stop if that is appropriate.
1612 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1613 if (pos == location->start()) {
1614 request_locate (pos);
1619 last_loopend = location->end();
1624 Session::set_auto_punch_location (Location* location)
1628 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1629 punch_connections.drop_connections();
1630 existing->set_auto_punch (false, this);
1631 remove_event (existing->start(), SessionEvent::PunchIn);
1632 clear_events (SessionEvent::PunchOut);
1633 auto_punch_location_changed (0);
1638 if (location == 0) {
1642 if (location->end() <= location->start()) {
1643 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1647 punch_connections.drop_connections ();
1649 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1650 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1651 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1653 location->set_auto_punch (true, this);
1655 auto_punch_changed (location);
1657 auto_punch_location_changed (location);
1661 Session::set_session_extents (framepos_t start, framepos_t end)
1664 if ((existing = _locations->session_range_location()) == 0) {
1665 //if there is no existing session, we need to make a new session location (should never happen)
1666 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1670 error << _("Session: you can't use that location for session start/end)") << endmsg;
1674 existing->set( start, end );
1680 Session::set_auto_loop_location (Location* location)
1684 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1685 loop_connections.drop_connections ();
1686 existing->set_auto_loop (false, this);
1687 remove_event (existing->end(), SessionEvent::AutoLoop);
1690 auto_loop_declick_range (existing, dcp, dcl);
1691 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1692 auto_loop_location_changed (0);
1697 if (location == 0) {
1701 if (location->end() <= location->start()) {
1702 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1706 last_loopend = location->end();
1708 loop_connections.drop_connections ();
1710 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1711 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1712 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1713 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1715 location->set_auto_loop (true, this);
1717 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1718 // set all tracks to use internal looping
1719 boost::shared_ptr<RouteList> rl = routes.reader ();
1720 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1721 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1722 if (tr && !tr->hidden()) {
1723 tr->set_loop (location);
1728 /* take care of our stuff first */
1730 auto_loop_changed (location);
1732 /* now tell everyone else */
1734 auto_loop_location_changed (location);
1738 Session::update_marks (Location*)
1744 Session::update_skips (Location* loc, bool consolidate)
1746 if (_ignore_skips_updates) {
1750 Locations::LocationList skips;
1753 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1754 consolidate_skips (loc);
1757 sync_locations_to_skips ();
1763 Session::consolidate_skips (Location* loc)
1765 Locations::LocationList all_locations = _locations->list ();
1767 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1769 if (!(*l)->is_skip ()) {
1774 /* don't test against self */
1781 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1782 case Evoral::OverlapInternal:
1783 case Evoral::OverlapExternal:
1784 case Evoral::OverlapStart:
1785 case Evoral::OverlapEnd:
1786 /* adjust new location to cover existing one */
1787 loc->set_start (min (loc->start(), (*l)->start()));
1788 loc->set_end (max (loc->end(), (*l)->end()));
1789 /* we don't need this one any more */
1790 _locations->remove (*l);
1791 /* the location has been deleted, so remove reference to it in our local list */
1792 l = all_locations.erase (l);
1795 case Evoral::OverlapNone:
1803 Session::sync_locations_to_skips ()
1805 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1806 * Session::_sync_locations_to_skips() from the audioengine thread.
1808 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1812 Session::_sync_locations_to_skips ()
1814 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1816 Locations::LocationList const & locs (_locations->list());
1818 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1820 Location* location = *i;
1822 if (location->is_skip() && location->is_skipping()) {
1823 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1831 Session::location_added (Location *location)
1833 if (location->is_auto_punch()) {
1834 set_auto_punch_location (location);
1837 if (location->is_auto_loop()) {
1838 set_auto_loop_location (location);
1841 if (location->is_session_range()) {
1842 /* no need for any signal handling or event setting with the session range,
1843 because we keep a direct reference to it and use its start/end directly.
1845 _session_range_location = location;
1848 if (location->is_mark()) {
1849 /* listen for per-location signals that require us to do any * global updates for marks */
1851 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1852 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1853 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1854 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1857 if (location->is_skip()) {
1858 /* listen for per-location signals that require us to update skip-locate events */
1860 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1861 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1862 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1863 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1865 update_skips (location, true);
1872 Session::location_removed (Location *location)
1874 if (location->is_auto_loop()) {
1875 set_auto_loop_location (0);
1876 set_track_loop (false);
1879 if (location->is_auto_punch()) {
1880 set_auto_punch_location (0);
1883 if (location->is_session_range()) {
1884 /* this is never supposed to happen */
1885 error << _("programming error: session range removed!") << endl;
1888 if (location->is_skip()) {
1890 update_skips (location, false);
1897 Session::locations_changed ()
1899 _locations->apply (*this, &Session::_locations_changed);
1903 Session::_locations_changed (const Locations::LocationList& locations)
1905 /* There was some mass-change in the Locations object.
1907 We might be re-adding a location here but it doesn't actually matter
1908 for all the locations that the Session takes an interest in.
1912 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1913 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1914 location_added (*i);
1918 update_skips (NULL, false);
1922 Session::enable_record ()
1924 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1925 /* no recording at anything except normal speed */
1930 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1932 if (rs == Recording) {
1936 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1938 _last_record_location = _transport_frame;
1939 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1941 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1942 set_track_monitor_input_status (true);
1945 RecordStateChanged ();
1952 Session::set_all_tracks_record_enabled (bool enable )
1954 boost::shared_ptr<RouteList> rl = routes.reader();
1955 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1959 Session::disable_record (bool rt_context, bool force)
1963 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1965 if (!Config->get_latched_record_enable () || force) {
1966 g_atomic_int_set (&_record_status, Disabled);
1967 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1969 if (rs == Recording) {
1970 g_atomic_int_set (&_record_status, Enabled);
1974 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1975 set_track_monitor_input_status (false);
1978 RecordStateChanged (); /* emit signal */
1981 remove_pending_capture_state ();
1987 Session::step_back_from_record ()
1989 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1991 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1992 set_track_monitor_input_status (false);
1995 RecordStateChanged (); /* emit signal */
2000 Session::maybe_enable_record ()
2002 if (_step_editors > 0) {
2006 g_atomic_int_set (&_record_status, Enabled);
2008 /* This function is currently called from somewhere other than an RT thread.
2009 This save_state() call therefore doesn't impact anything. Doing it here
2010 means that we save pending state of which sources the next record will use,
2011 which gives us some chance of recovering from a crash during the record.
2014 save_state ("", true);
2016 if (_transport_speed) {
2017 if (!config.get_punch_in()) {
2021 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2022 RecordStateChanged (); /* EMIT SIGNAL */
2029 Session::audible_frame () const
2035 offset = worst_playback_latency ();
2037 if (synced_to_engine()) {
2038 /* Note: this is basically just sync-to-JACK */
2039 tf = _engine.transport_frame();
2041 tf = _transport_frame;
2046 if (!non_realtime_work_pending()) {
2050 /* Check to see if we have passed the first guaranteed
2051 audible frame past our last start position. if not,
2052 return that last start point because in terms
2053 of audible frames, we have not moved yet.
2055 `Start position' in this context means the time we last
2056 either started, located, or changed transport direction.
2059 if (_transport_speed > 0.0f) {
2061 if (!play_loop || !have_looped) {
2062 if (tf < _last_roll_or_reversal_location + offset) {
2063 return _last_roll_or_reversal_location;
2071 } else if (_transport_speed < 0.0f) {
2073 /* XXX wot? no backward looping? */
2075 if (tf > _last_roll_or_reversal_location - offset) {
2076 return _last_roll_or_reversal_location;
2088 Session::set_frame_rate (framecnt_t frames_per_second)
2090 /** \fn void Session::set_frame_size(framecnt_t)
2091 the AudioEngine object that calls this guarantees
2092 that it will not be called while we are also in
2093 ::process(). Its fine to do things that block
2097 if (_base_frame_rate == 0) {
2098 _base_frame_rate = frames_per_second;
2100 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2101 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2103 _nominal_frame_rate = frames_per_second;
2108 reset_write_sources (false);
2110 // XXX we need some equivalent to this, somehow
2111 // SndFileSource::setup_standard_crossfades (frames_per_second);
2115 /* XXX need to reset/reinstantiate all LADSPA plugins */
2119 Session::set_block_size (pframes_t nframes)
2121 /* the AudioEngine guarantees
2122 that it will not be called while we are also in
2123 ::process(). It is therefore fine to do things that block
2128 current_block_size = nframes;
2132 boost::shared_ptr<RouteList> r = routes.reader ();
2134 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2135 (*i)->set_block_size (nframes);
2138 boost::shared_ptr<RouteList> rl = routes.reader ();
2139 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2140 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2142 tr->set_block_size (nframes);
2146 set_worst_io_latencies ();
2152 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2154 boost::shared_ptr<Route> r2;
2156 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2157 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2161 /* make a copy of the existing list of routes that feed r1 */
2163 Route::FedBy existing (r1->fed_by());
2165 /* for each route that feeds r1, recurse, marking it as feeding
2169 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2170 if (!(r2 = i->r.lock ())) {
2171 /* (*i) went away, ignore it */
2175 /* r2 is a route that feeds r1 which somehow feeds base. mark
2176 base as being fed by r2
2179 rbase->add_fed_by (r2, i->sends_only);
2183 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2187 if (r1->feeds (r2) && r2->feeds (r1)) {
2191 /* now recurse, so that we can mark base as being fed by
2192 all routes that feed r2
2195 trace_terminal (r2, rbase);
2202 Session::resort_routes ()
2204 /* don't do anything here with signals emitted
2205 by Routes during initial setup or while we
2206 are being destroyed.
2209 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2213 if (_route_deletion_in_progress) {
2218 RCUWriter<RouteList> writer (routes);
2219 boost::shared_ptr<RouteList> r = writer.get_copy ();
2220 resort_routes_using (r);
2221 /* writer goes out of scope and forces update */
2225 if (DEBUG_ENABLED(DEBUG::Graph)) {
2226 boost::shared_ptr<RouteList> rl = routes.reader ();
2227 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2228 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2230 const Route::FedBy& fb ((*i)->fed_by());
2232 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2233 boost::shared_ptr<Route> sf = f->r.lock();
2235 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2244 /** This is called whenever we need to rebuild the graph of how we will process
2246 * @param r List of routes, in any order.
2250 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2252 /* We are going to build a directed graph of our routes;
2253 this is where the edges of that graph are put.
2258 /* Go through all routes doing two things:
2260 * 1. Collect the edges of the route graph. Each of these edges
2261 * is a pair of routes, one of which directly feeds the other
2262 * either by a JACK connection or by an internal send.
2264 * 2. Begin the process of making routes aware of which other
2265 * routes directly or indirectly feed them. This information
2266 * is used by the solo code.
2269 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2271 /* Clear out the route's list of direct or indirect feeds */
2272 (*i)->clear_fed_by ();
2274 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2276 bool via_sends_only;
2278 /* See if this *j feeds *i according to the current state of the JACK
2279 connections and internal sends.
2281 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2282 /* add the edge to the graph (part #1) */
2283 edges.add (*j, *i, via_sends_only);
2284 /* tell the route (for part #2) */
2285 (*i)->add_fed_by (*j, via_sends_only);
2290 /* Attempt a topological sort of the route graph */
2291 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2293 if (sorted_routes) {
2294 /* We got a satisfactory topological sort, so there is no feedback;
2297 Note: the process graph rechain does not require a
2298 topologically-sorted list, but hey ho.
2300 if (_process_graph) {
2301 _process_graph->rechain (sorted_routes, edges);
2304 _current_route_graph = edges;
2306 /* Complete the building of the routes' lists of what directly
2307 or indirectly feeds them.
2309 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2310 trace_terminal (*i, *i);
2313 *r = *sorted_routes;
2316 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2317 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2318 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2322 SuccessfulGraphSort (); /* EMIT SIGNAL */
2325 /* The topological sort failed, so we have a problem. Tell everyone
2326 and stick to the old graph; this will continue to be processed, so
2327 until the feedback is fixed, what is played back will not quite
2328 reflect what is actually connected. Note also that we do not
2329 do trace_terminal here, as it would fail due to an endless recursion,
2330 so the solo code will think that everything is still connected
2334 FeedbackDetected (); /* EMIT SIGNAL */
2339 /** Find a route name starting with \a base, maybe followed by the
2340 * lowest \a id. \a id will always be added if \a definitely_add_number
2341 * is true on entry; otherwise it will only be added if required
2342 * to make the name unique.
2344 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2345 * The available route name with the lowest ID will be used, and \a id
2346 * will be set to the ID.
2348 * \return false if a route name could not be found, and \a track_name
2349 * and \a id do not reflect a free route name.
2352 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2354 /* the base may conflict with ports that do not belong to existing
2355 routes, but hidden objects like the click track. So check port names
2356 before anything else.
2359 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2360 if (base == *reserved) {
2361 /* Check if this reserved name already exists, and if
2362 so, disallow it without a numeric suffix.
2364 if (route_by_name (*reserved)) {
2365 definitely_add_number = true;
2374 if (!definitely_add_number && route_by_name (base) == 0) {
2375 /* juse use the base */
2381 name = string_compose ("%1 %2", base, id);
2383 if (route_by_name (name) == 0) {
2389 } while (id < (UINT_MAX-1));
2394 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2396 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2398 in = ChanCount::ZERO;
2399 out = ChanCount::ZERO;
2401 boost::shared_ptr<RouteList> r = routes.reader ();
2403 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2404 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2405 if (tr && !tr->is_auditioner()) {
2406 in += tr->n_inputs();
2407 out += tr->n_outputs();
2413 Session::default_track_name_pattern (DataType t)
2416 case DataType::AUDIO:
2417 if (Profile->get_trx()) {
2424 case DataType::MIDI:
2431 /** Caller must not hold process lock
2432 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2433 * @param instrument plugin info for the instrument to insert pre-fader, if any
2435 list<boost::shared_ptr<MidiTrack> >
2436 Session::new_midi_track (const ChanCount& input, const ChanCount& output,
2437 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2438 RouteGroup* route_group, uint32_t how_many, string name_template, PresentationInfo::order_t order,
2442 uint32_t track_id = 0;
2444 RouteList new_routes;
2445 list<boost::shared_ptr<MidiTrack> > ret;
2447 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2448 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2451 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2452 error << "cannot find name for new midi track" << endmsg;
2456 boost::shared_ptr<MidiTrack> track;
2459 track.reset (new MidiTrack (*this, track_name, mode));
2461 if (track->init ()) {
2465 if (Profile->get_mixbus ()) {
2466 track->set_strict_io (true);
2469 track->use_new_diskstream();
2471 BOOST_MARK_TRACK (track);
2474 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2475 if (track->input()->ensure_io (input, false, this)) {
2476 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2480 if (track->output()->ensure_io (output, false, this)) {
2481 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2486 track->non_realtime_input_change();
2489 route_group->add (track);
2492 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2494 new_routes.push_back (track);
2495 ret.push_back (track);
2498 catch (failed_constructor &err) {
2499 error << _("Session: could not create new midi track.") << endmsg;
2503 catch (AudioEngine::PortRegistrationFailure& pfe) {
2505 error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
2513 if (!new_routes.empty()) {
2514 StateProtector sp (this);
2515 if (Profile->get_trx()) {
2516 add_routes (new_routes, false, false, false, order);
2518 add_routes (new_routes, true, true, false, order);
2522 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2523 PluginPtr plugin = instrument->load (*this);
2525 plugin->load_preset (*pset);
2527 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2528 (*r)->add_processor (p, PreFader);
2538 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2539 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2542 uint32_t bus_id = 0;
2546 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2549 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2550 error << "cannot find name for new midi bus" << endmsg;
2555 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2561 if (Profile->get_mixbus ()) {
2562 bus->set_strict_io (true);
2565 BOOST_MARK_ROUTE(bus);
2568 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2570 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2571 error << _("cannot configure new midi bus input") << endmsg;
2576 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2577 error << _("cannot configure new midi bus output") << endmsg;
2583 route_group->add (bus);
2586 bus->add_internal_return ();
2587 ret.push_back (bus);
2590 catch (failed_constructor &err) {
2591 error << _("Session: could not create new audio route.") << endmsg;
2595 catch (AudioEngine::PortRegistrationFailure& pfe) {
2596 error << pfe.what() << endmsg;
2606 StateProtector sp (this);
2607 add_routes (ret, false, false, false, order);
2610 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2611 PluginPtr plugin = instrument->load (*this);
2613 plugin->load_preset (*pset);
2615 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2616 (*r)->add_processor (p, PreFader);
2627 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2629 boost::shared_ptr<Route> midi_track (wmt.lock());
2635 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2637 if (change.after.n_audio() <= change.before.n_audio()) {
2641 /* new audio ports: make sure the audio goes somewhere useful,
2642 * unless the user has no-auto-connect selected.
2644 * The existing ChanCounts don't matter for this call as they are only
2645 * to do with matching input and output indices, and we are only changing
2648 auto_connect_route (midi_track, false, ChanCount(), change.before);
2652 #ifdef USE_TRACKS_CODE_FEATURES
2655 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2657 return route1->remote_control_id() < route2->remote_control_id();
2661 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2663 // it is not allowed to perform connection
2664 if (!IO::connecting_legal) {
2668 // if we are deleting routes we will call this once at the end
2669 if (_route_deletion_in_progress) {
2673 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2679 // We need to disconnect the route's inputs and outputs first
2680 // basing on autoconnect configuration
2681 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2682 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2684 ChanCount existing_inputs;
2685 ChanCount existing_outputs;
2686 count_existing_track_channels (existing_inputs, existing_outputs);
2688 //ChanCount inputs = ChanCount::ZERO;
2689 //ChanCount outputs = ChanCount::ZERO;
2691 RouteList existing_routes = *routes.reader ();
2692 existing_routes.sort (compare_routes_by_remote_id);
2695 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2697 vector<string> physinputs;
2698 vector<string> physoutputs;
2700 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2701 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2703 uint32_t input_n = 0;
2704 uint32_t output_n = 0;
2705 RouteList::iterator rIter = existing_routes.begin();
2706 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2707 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2708 for (; rIter != existing_routes.end(); ++rIter) {
2709 if (*rIter == _master_out || *rIter == _monitor_out ) {
2713 if (current_output_auto_connection == AutoConnectPhysical) {
2714 (*rIter)->amp()->deactivate();
2715 } else if (current_output_auto_connection == AutoConnectMaster) {
2716 (*rIter)->amp()->activate();
2719 if (reconnectIputs) {
2720 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2722 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2724 if (current_input_auto_connection & AutoConnectPhysical) {
2726 if ( input_n == physinputs.size() ) {
2730 string port = physinputs[input_n];
2732 if (port.empty() ) {
2733 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2736 //GZ: check this; could be heavy
2737 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2743 if (reconnectOutputs) {
2745 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2746 if (current_output_auto_connection & AutoConnectPhysical) {
2748 //GZ: check this; could be heavy
2749 (*rIter)->output()->disconnect (this);
2750 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2752 //GZ: check this; could be heavy
2753 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2755 } else if (current_output_auto_connection & AutoConnectMaster){
2757 if (!reconnect_master) {
2761 //GZ: check this; could be heavy
2762 (*rIter)->output()->disconnect (this);
2765 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2766 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2768 error << error << "Master bus is not available" << endmsg;
2773 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2774 if (current_output_auto_connection & AutoConnectPhysical) {
2776 if ( output_n == physoutputs.size() ) {
2780 string port = physoutputs[output_n];
2782 if (port.empty() ) {
2783 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2786 //GZ: check this; could be heavy
2787 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2790 } else if (current_output_auto_connection & AutoConnectMaster) {
2792 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2796 // connect to master bus
2797 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2799 if (port.empty() ) {
2800 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2804 //GZ: check this; could be heavy
2805 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2812 _master_out->output()->disconnect (this);
2813 auto_connect_master_bus ();
2818 session_routes_reconnected (); /* EMIT SIGNAL */
2822 Session::reconnect_midi_scene_ports(bool inputs)
2826 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2828 scene_in_ptr->disconnect_all ();
2830 std::vector<EngineStateController::MidiPortState> midi_port_states;
2831 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2833 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2835 for (; state_iter != midi_port_states.end(); ++state_iter) {
2836 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2837 scene_in_ptr->connect (state_iter->name);
2844 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2846 if (scene_out_ptr ) {
2847 scene_out_ptr->disconnect_all ();
2849 std::vector<EngineStateController::MidiPortState> midi_port_states;
2850 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2852 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2854 for (; state_iter != midi_port_states.end(); ++state_iter) {
2855 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2856 scene_out_ptr->connect (state_iter->name);
2864 Session::reconnect_mtc_ports ()
2866 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2872 mtc_in_ptr->disconnect_all ();
2874 std::vector<EngineStateController::MidiPortState> midi_port_states;
2875 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2877 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2879 for (; state_iter != midi_port_states.end(); ++state_iter) {
2880 if (state_iter->available && state_iter->mtc_in) {
2881 mtc_in_ptr->connect (state_iter->name);
2885 if (!_midi_ports->mtc_input_port ()->connected () &&
2886 config.get_external_sync () &&
2887 (Config->get_sync_source () == MTC) ) {
2888 config.set_external_sync (false);
2891 if ( ARDOUR::Profile->get_trx () ) {
2892 // Tracks need this signal to update timecode_source_dropdown
2893 MtcOrLtcInputPortChanged (); //emit signal
2898 Session::reconnect_mmc_ports(bool inputs)
2900 if (inputs ) { // get all enabled midi input ports
2902 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2904 mmc_in_ptr->disconnect_all ();
2905 std::vector<std::string> enabled_midi_inputs;
2906 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2908 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2910 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2911 mmc_in_ptr->connect (*port_iter);
2915 } else { // get all enabled midi output ports
2917 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2919 mmc_out_ptr->disconnect_all ();
2920 std::vector<std::string> enabled_midi_outputs;
2921 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2923 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2925 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2926 mmc_out_ptr->connect (*port_iter);
2935 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
2937 if (first_new_order == PresentationInfo::max_order) {
2938 /* adding at end, no worries */
2942 /* create a gap in the presentation info to accomodate @param how_many
2946 get_stripables (sl);
2948 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
2949 boost::shared_ptr<Stripable> s (*si);
2951 if (s->is_monitor() || s->is_auditioner()) {
2955 if (s->presentation_info().order () >= first_new_order) {
2956 s->set_presentation_order (s->presentation_info().order () + how_many);
2961 /** Caller must not hold process lock
2962 * @param name_template string to use for the start of the name, or "" to use "Audio".
2964 list< boost::shared_ptr<AudioTrack> >
2965 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
2966 uint32_t how_many, string name_template, PresentationInfo::order_t order,
2970 uint32_t track_id = 0;
2972 RouteList new_routes;
2973 list<boost::shared_ptr<AudioTrack> > ret;
2975 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2976 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2980 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2981 error << "cannot find name for new audio track" << endmsg;
2985 boost::shared_ptr<AudioTrack> track;
2988 track.reset (new AudioTrack (*this, track_name, mode));
2990 if (track->init ()) {
2994 if (Profile->get_mixbus ()) {
2995 track->set_strict_io (true);
2998 if (ARDOUR::Profile->get_trx ()) {
2999 // TRACKS considers it's not a USE CASE, it's
3000 // a piece of behavior of the session model:
3002 // Gain for a newly created route depends on
3003 // the current output_auto_connect mode:
3005 // 0 for Stereo Out mode
3007 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3008 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3012 track->use_new_diskstream();
3014 BOOST_MARK_TRACK (track);
3017 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3019 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3020 error << string_compose (
3021 _("cannot configure %1 in/%2 out configuration for new audio track"),
3022 input_channels, output_channels)
3027 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3028 error << string_compose (
3029 _("cannot configure %1 in/%2 out configuration for new audio track"),
3030 input_channels, output_channels)
3037 route_group->add (track);
3040 track->non_realtime_input_change();
3042 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3044 new_routes.push_back (track);
3045 ret.push_back (track);
3048 catch (failed_constructor &err) {
3049 error << _("Session: could not create new audio track.") << endmsg;
3053 catch (AudioEngine::PortRegistrationFailure& pfe) {
3055 error << pfe.what() << endmsg;
3063 if (!new_routes.empty()) {
3064 StateProtector sp (this);
3065 if (Profile->get_trx()) {
3066 add_routes (new_routes, false, false, false, order);
3068 add_routes (new_routes, true, true, false, order);
3075 /** Caller must not hold process lock.
3076 * @param name_template string to use for the start of the name, or "" to use "Bus".
3079 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3080 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3083 uint32_t bus_id = 0;
3087 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3090 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3091 error << "cannot find name for new audio bus" << endmsg;
3096 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3102 if (Profile->get_mixbus ()) {
3103 bus->set_strict_io (true);
3106 BOOST_MARK_ROUTE(bus);
3109 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3111 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3112 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3113 input_channels, output_channels)
3119 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3120 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3121 input_channels, output_channels)
3128 route_group->add (bus);
3131 bus->add_internal_return ();
3132 ret.push_back (bus);
3135 catch (failed_constructor &err) {
3136 error << _("Session: could not create new audio route.") << endmsg;
3140 catch (AudioEngine::PortRegistrationFailure& pfe) {
3141 error << pfe.what() << endmsg;
3151 StateProtector sp (this);
3152 if (Profile->get_trx()) {
3153 add_routes (ret, false, false, false, order);
3155 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3164 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3168 if (!tree.read (template_path.c_str())) {
3172 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3176 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3179 uint32_t number = 0;
3180 const uint32_t being_added = how_many;
3181 /* This will prevent the use of any existing XML-provided PBD::ID
3184 Stateful::ForceIDRegeneration force_ids;
3185 IO::disable_connecting ();
3189 /* We're going to modify the node contents a bit so take a
3190 * copy. The node may be re-used when duplicating more than once.
3193 XMLNode node_copy (node);
3198 if (!name_base.empty()) {
3200 /* if we're adding more than one routes, force
3201 * all the names of the new routes to be
3202 * numbered, via the final parameter.
3205 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3206 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3212 string const route_name = node_copy.property(X_("name"))->value ();
3214 /* generate a new name by adding a number to the end of the template name */
3215 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3216 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3217 abort(); /*NOTREACHED*/
3221 /* set this name in the XML description that we are about to use */
3223 bool rename_playlist;
3226 rename_playlist = true;
3231 rename_playlist = false;
3234 Route::set_name_in_state (node_copy, name, rename_playlist);
3236 /* trim bitslots from listen sends so that new ones are used */
3237 XMLNodeList children = node_copy.children ();
3238 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3239 if ((*i)->name() == X_("Processor")) {
3240 /* ForceIDRegeneration does not catch the following */
3241 XMLProperty const * role = (*i)->property (X_("role"));
3242 XMLProperty const * type = (*i)->property (X_("type"));
3243 if (role && role->value() == X_("Aux")) {
3244 /* check if the target bus exists.
3245 * we should not save aux-sends in templates.
3247 XMLProperty const * target = (*i)->property (X_("target"));
3249 (*i)->add_property ("type", "dangling-aux-send");
3252 boost::shared_ptr<Route> r = route_by_id (target->value());
3253 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3254 (*i)->add_property ("type", "dangling-aux-send");
3258 if (role && role->value() == X_("Listen")) {
3259 (*i)->remove_property (X_("bitslot"));
3261 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3263 Delivery::Role xrole;
3264 uint32_t bitslot = 0;
3265 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3266 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3267 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3268 (*i)->remove_property (X_("bitslot"));
3269 (*i)->remove_property (X_("name"));
3270 (*i)->add_property ("bitslot", buf);
3271 (*i)->add_property ("name", name);
3273 else if (type && type->value() == X_("intreturn")) {
3274 (*i)->remove_property (X_("bitslot"));
3275 (*i)->add_property ("ignore-bitslot", "1");
3277 else if (type && type->value() == X_("return")) {
3278 // Return::set_state() generates a new one
3279 (*i)->remove_property (X_("bitslot"));
3281 else if (type && type->value() == X_("port")) {
3282 // PortInsert::set_state() handles the bitslot
3283 (*i)->remove_property (X_("bitslot"));
3284 (*i)->add_property ("ignore-name", "1");
3289 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3292 error << _("Session: cannot create track/bus from template description") << endmsg;
3296 if (boost::dynamic_pointer_cast<Track>(route)) {
3297 /* force input/output change signals so that the new diskstream
3298 picks up the configuration of the route. During session
3299 loading this normally happens in a different way.
3302 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3304 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3305 change.after = route->input()->n_ports();
3306 route->input()->changed (change, this);
3307 change.after = route->output()->n_ports();
3308 route->output()->changed (change, this);
3311 boost::shared_ptr<Track> track;
3313 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3316 track->use_new_playlist ();
3319 track->use_copy_playlist ();
3326 ret.push_back (route);
3329 catch (failed_constructor &err) {
3330 error << _("Session: could not create new route from template") << endmsg;
3334 catch (AudioEngine::PortRegistrationFailure& pfe) {
3335 error << pfe.what() << endmsg;
3344 StateProtector sp (this);
3345 if (Profile->get_trx()) {
3346 add_routes (ret, false, false, false, PresentationInfo::max_order);
3348 add_routes (ret, true, true, false, PresentationInfo::max_order);
3350 IO::enable_connecting ();
3357 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3360 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3361 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3364 error << _("Adding new tracks/busses failed") << endmsg;
3369 update_latency (true);
3370 update_latency (false);
3375 save_state (_current_snapshot_name);
3378 update_route_record_state ();
3380 RouteAdded (new_routes); /* EMIT SIGNAL */
3384 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3386 ChanCount existing_inputs;
3387 ChanCount existing_outputs;
3391 count_existing_track_channels (existing_inputs, existing_outputs);
3394 RCUWriter<RouteList> writer (routes);
3395 boost::shared_ptr<RouteList> r = writer.get_copy ();
3396 r->insert (r->end(), new_routes.begin(), new_routes.end());
3397 n_routes = r->size();
3399 /* if there is no control out and we're not in the middle of loading,
3400 * resort the graph here. if there is a control out, we will resort
3401 * toward the end of this method. if we are in the middle of loading,
3402 * we will resort when done.
3405 if (!_monitor_out && IO::connecting_legal) {
3406 resort_routes_using (r);
3410 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3411 ensure_route_presentation_info_gap (order, new_routes.size());
3413 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3415 boost::weak_ptr<Route> wpr (*x);
3416 boost::shared_ptr<Route> r (*x);
3418 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3419 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3420 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3422 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3423 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3424 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3426 if (r->is_master()) {
3430 if (r->is_monitor()) {
3434 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3436 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3437 track_playlist_changed (boost::weak_ptr<Track> (tr));
3438 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3440 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3442 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3443 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3447 if (!r->presentation_info().special()) {
3449 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3451 /* presentation info order may already have been set from XML */
3453 if (!r->presentation_info().order_set()) {
3455 if (order == PresentationInfo::max_order) {
3456 /* just add to the end */
3457 r->set_presentation_order (n_routes + added, false);
3458 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3460 r->set_presentation_order (order + added);
3461 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3464 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3468 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3469 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3470 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3472 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3474 r->presentation_info().order(),
3475 enum_2_string (r->presentation_info().flags()),
3476 r->presentation_info()));
3480 if (input_auto_connect || output_auto_connect) {
3481 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3482 existing_inputs += r->n_inputs();
3483 existing_outputs += r->n_outputs();
3489 if (_monitor_out && IO::connecting_legal) {
3490 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3492 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3493 if ((*x)->is_monitor()) {
3495 } else if ((*x)->is_master()) {
3498 (*x)->enable_monitor_send ();
3503 reassign_track_numbers ();
3507 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3509 boost::shared_ptr<RouteList> r = routes.reader ();
3510 boost::shared_ptr<Send> s;
3512 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3513 if ((s = (*i)->internal_send_for (dest)) != 0) {
3514 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3520 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3522 boost::shared_ptr<RouteList> r = routes.reader ();
3523 boost::shared_ptr<Send> s;
3525 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3526 if ((s = (*i)->internal_send_for (dest)) != 0) {
3527 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3533 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3535 boost::shared_ptr<RouteList> r = routes.reader ();
3536 boost::shared_ptr<Send> s;
3538 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3539 if ((s = (*i)->internal_send_for (dest)) != 0) {
3540 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3545 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3547 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3549 boost::shared_ptr<RouteList> r = routes.reader ();
3550 boost::shared_ptr<RouteList> t (new RouteList);
3552 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3553 /* no MIDI sends because there are no MIDI busses yet */
3554 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3559 add_internal_sends (dest, p, t);
3563 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3565 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3566 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3571 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3573 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3577 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3579 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3583 if (!dest->internal_return()) {
3584 dest->add_internal_return ();
3587 sender->add_aux_send (dest, before);
3593 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3595 { // RCU Writer scope
3596 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3597 RCUWriter<RouteList> writer (routes);
3598 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3601 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3603 if (*iter == _master_out) {
3607 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3611 /* deleting the master out seems like a dumb
3612 idea, but its more of a UI policy issue
3616 if (*iter == _master_out) {
3617 _master_out = boost::shared_ptr<Route> ();
3620 if (*iter == _monitor_out) {
3621 _monitor_out.reset ();
3624 // We need to disconnect the route's inputs and outputs
3626 (*iter)->input()->disconnect (0);
3627 (*iter)->output()->disconnect (0);
3629 /* if the route had internal sends sending to it, remove them */
3630 if ((*iter)->internal_return()) {
3632 boost::shared_ptr<RouteList> r = routes.reader ();
3633 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3634 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3636 (*i)->remove_processor (s);
3641 /* if the monitoring section had a pointer to this route, remove it */
3642 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3643 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3644 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3645 (*iter)->remove_aux_or_listen (_monitor_out);
3648 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3649 if (mt && mt->step_editing()) {
3650 if (_step_editors > 0) {
3656 /* writer goes out of scope, forces route list update */
3658 } // end of RCU Writer scope
3660 update_route_solo_state ();
3661 update_latency_compensation ();
3664 /* Re-sort routes to remove the graph's current references to the one that is
3665 * going away, then flush old references out of the graph.
3666 * Wave Tracks: reconnect routes
3669 #ifdef USE_TRACKS_CODE_FEATURES
3670 reconnect_existing_routes(true, false);
3672 routes.flush (); // maybe unsafe, see below.
3676 if (_process_graph && !(_state_of_the_state & Deletion)) {
3677 _process_graph->clear_other_chain ();
3680 /* get rid of it from the dead wood collection in the route list manager */
3681 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3685 /* try to cause everyone to drop their references
3686 * and unregister ports from the backend
3689 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3690 (*iter)->drop_references ();
3693 if (_state_of_the_state & Deletion) {
3697 PresentationInfo::Change(); /* EMIT SIGNAL */
3699 /* save the new state of the world */
3701 if (save_state (_current_snapshot_name)) {
3702 save_history (_current_snapshot_name);
3705 update_route_record_state ();
3709 Session::remove_route (boost::shared_ptr<Route> route)
3711 boost::shared_ptr<RouteList> rl (new RouteList);
3712 rl->push_back (route);
3717 Session::route_mute_changed ()
3723 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3725 boost::shared_ptr<Route> route (wpr.lock());
3731 assert (Config->get_solo_control_is_listen_control());
3733 if (route->solo_control()->soloed_by_self_or_masters()) {
3735 if (Config->get_exclusive_solo()) {
3737 RouteGroup* rg = route->route_group ();
3738 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3740 boost::shared_ptr<RouteList> r = routes.reader ();
3742 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3743 if ((*i) == route) {
3744 /* already changed */
3748 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3749 /* route does not get solo propagated to it */
3753 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3754 /* this route is a part of the same solo group as the route
3755 * that was changed. Changing that route did change or will
3756 * change all group members appropriately, so we can ignore it
3761 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3767 } else if (_listen_cnt > 0) {
3772 update_route_solo_state ();
3776 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3778 boost::shared_ptr<Route> route (wpr.lock());
3784 bool send_changed = false;
3786 if (route->solo_isolate_control()->solo_isolated()) {
3787 if (_solo_isolated_cnt == 0) {
3788 send_changed = true;
3790 _solo_isolated_cnt++;
3791 } else if (_solo_isolated_cnt > 0) {
3792 _solo_isolated_cnt--;
3793 if (_solo_isolated_cnt == 0) {
3794 send_changed = true;
3799 IsolatedChanged (); /* EMIT SIGNAL */
3804 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3806 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_changed));
3808 boost::shared_ptr<Route> route (wpr.lock());
3814 if (Config->get_solo_control_is_listen_control()) {
3815 route_listen_changed (group_override, wpr);
3819 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()));
3821 if (route->solo_control()->transitioned_into_solo() == 0) {
3822 /* route solo changed by upstream/downstream; not interesting
3825 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()));
3829 if (route->solo_control()->transitioned_into_solo() == 0) {
3830 /* reason for being soloed changed (e.g. master went away, we
3831 * took over the master state), but actual status did
3832 * not. nothing to do.
3834 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: solo change was change in reason, not status\n", route->name()));
3837 boost::shared_ptr<RouteList> r = routes.reader ();
3838 int32_t delta = route->solo_control()->transitioned_into_solo ();
3840 /* the route may be a member of a group that has shared-solo
3841 * semantics. If so, then all members of that group should follow the
3842 * solo of the changed route. But ... this is optional, controlled by a
3843 * Controllable::GroupControlDisposition.
3845 * The first argument to the signal that this method is connected to is the
3846 * GroupControlDisposition value that was used to change solo.
3848 * If the solo change was done with group semantics (either InverseGroup
3849 * (force the entire group to change even if the group shared solo is
3850 * disabled) or UseGroup (use the group, which may or may not have the
3851 * shared solo property enabled)) then as we propagate the change to
3852 * the entire session we should IGNORE THE GROUP that the changed route
3856 RouteGroup* rg = route->route_group ();
3857 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3859 if (delta == 1 && Config->get_exclusive_solo()) {
3861 /* new solo: disable all other solos, but not the group if its solo-enabled */
3863 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3865 if ((*i) == route) {
3866 /* already changed */
3870 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3871 /* route does not get solo propagated to it */
3875 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3876 /* this route is a part of the same solo group as the route
3877 * that was changed. Changing that route did change or will
3878 * change all group members appropriately, so we can ignore it
3884 (*i)->solo_control()->set_value (0.0, group_override);
3888 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3890 RouteList uninvolved;
3892 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3894 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3895 bool via_sends_only;
3896 bool in_signal_flow;
3898 if ((*i) == route) {
3899 /* already changed */
3903 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3904 /* route does not get solo propagated to it */
3908 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3909 /* this route is a part of the same solo group as the route
3910 * that was changed. Changing that route did change or will
3911 * change all group members appropriately, so we can ignore it
3917 in_signal_flow = false;
3919 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3921 if ((*i)->feeds (route, &via_sends_only)) {
3922 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3923 if (!via_sends_only) {
3924 if (!route->soloed_by_others_upstream()) {
3925 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3927 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3930 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3932 in_signal_flow = true;
3934 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3937 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3939 if (route->feeds (*i, &via_sends_only)) {
3940 /* propagate solo upstream only if routing other than
3941 sends is involved, but do consider the other route
3942 (*i) to be part of the signal flow even if only
3945 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3949 route->soloed_by_others_downstream(),
3950 route->soloed_by_others_upstream()));
3951 if (!via_sends_only) {
3952 //NB. Triggers Invert Push, which handles soloed by downstream
3953 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3954 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3956 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3958 in_signal_flow = true;
3960 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3963 if (!in_signal_flow) {
3964 uninvolved.push_back (*i);
3968 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3970 update_route_solo_state (r);
3972 /* now notify that the mute state of the routes not involved in the signal
3973 pathway of the just-solo-changed route may have altered.
3976 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3977 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3978 (*i)->act_on_mute ();
3979 (*i)->mute_control()->Changed (false, Controllable::NoGroup);
3982 SoloChanged (); /* EMIT SIGNAL */
3987 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3989 /* now figure out if anything that matters is soloed (or is "listening")*/
3991 bool something_soloed = false;
3992 bool something_listening = false;
3993 uint32_t listeners = 0;
3994 uint32_t isolated = 0;
3997 r = routes.reader();
4000 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4001 if ((*i)->can_solo()) {
4002 if (Config->get_solo_control_is_listen_control()) {
4003 if ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value()) {
4005 something_listening = true;
4008 (*i)->set_listen (false);
4009 if ((*i)->can_solo() && ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value())) {
4010 something_soloed = true;
4015 if ((*i)->solo_isolate_control()->solo_isolated()) {
4020 if (something_soloed != _non_soloed_outs_muted) {
4021 _non_soloed_outs_muted = something_soloed;
4022 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4025 if (something_listening != _listening) {
4026 _listening = something_listening;
4027 SoloActive (_listening);
4030 _listen_cnt = listeners;
4032 if (isolated != _solo_isolated_cnt) {
4033 _solo_isolated_cnt = isolated;
4034 IsolatedChanged (); /* EMIT SIGNAL */
4037 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4038 something_soloed, listeners, isolated));
4042 Session::get_stripables (StripableList& sl) const
4044 boost::shared_ptr<RouteList> r = routes.reader ();
4045 sl.insert (sl.end(), r->begin(), r->end());
4047 VCAList v = _vca_manager->vcas ();
4048 sl.insert (sl.end(), v.begin(), v.end());
4051 boost::shared_ptr<RouteList>
4052 Session::get_routes_with_internal_returns() const
4054 boost::shared_ptr<RouteList> r = routes.reader ();
4055 boost::shared_ptr<RouteList> rl (new RouteList);
4057 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4058 if ((*i)->internal_return ()) {
4066 Session::io_name_is_legal (const std::string& name) const
4068 boost::shared_ptr<RouteList> r = routes.reader ();
4070 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4071 if (name == *reserved) {
4072 if (!route_by_name (*reserved)) {
4073 /* first instance of a reserved name is allowed */
4076 /* all other instances of a reserved name are not allowed */
4081 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4082 if ((*i)->name() == name) {
4086 if ((*i)->has_io_processor_named (name)) {
4095 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4098 vector<string> connections;
4100 /* if we are passed only a single route and we're not told to turn
4101 * others off, then just do the simple thing.
4104 if (flip_others == false && rl->size() == 1) {
4105 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4107 mt->set_input_active (onoff);
4112 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4114 PortSet& ps ((*rt)->input()->ports());
4116 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4117 p->get_connections (connections);
4120 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4121 routes_using_input_from (*s, rl2);
4124 /* scan all relevant routes to see if others are on or off */
4126 bool others_are_already_on = false;
4128 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4130 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4136 if ((*r) != (*rt)) {
4137 if (mt->input_active()) {
4138 others_are_already_on = true;
4141 /* this one needs changing */
4142 mt->set_input_active (onoff);
4148 /* globally reverse other routes */
4150 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4151 if ((*r) != (*rt)) {
4152 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4154 mt->set_input_active (!others_are_already_on);
4163 Session::routes_using_input_from (const string& str, RouteList& rl)
4165 boost::shared_ptr<RouteList> r = routes.reader();
4167 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4168 if ((*i)->input()->connected_to (str)) {
4174 boost::shared_ptr<Route>
4175 Session::route_by_name (string name) const
4177 boost::shared_ptr<RouteList> r = routes.reader ();
4179 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4180 if ((*i)->name() == name) {
4185 return boost::shared_ptr<Route> ((Route*) 0);
4188 boost::shared_ptr<Route>
4189 Session::route_by_id (PBD::ID id) const
4191 boost::shared_ptr<RouteList> r = routes.reader ();
4193 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4194 if ((*i)->id() == id) {
4199 return boost::shared_ptr<Route> ((Route*) 0);
4202 boost::shared_ptr<Processor>
4203 Session::processor_by_id (PBD::ID id) const
4205 boost::shared_ptr<RouteList> r = routes.reader ();
4207 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4208 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4214 return boost::shared_ptr<Processor> ();
4217 boost::shared_ptr<Track>
4218 Session::track_by_diskstream_id (PBD::ID id) const
4220 boost::shared_ptr<RouteList> r = routes.reader ();
4222 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4223 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4224 if (t && t->using_diskstream_id (id)) {
4229 return boost::shared_ptr<Track> ();
4232 boost::shared_ptr<Route>
4233 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4235 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4238 boost::shared_ptr<Stripable>
4239 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4242 PresentationInfo::order_t match_cnt = 0;
4244 get_stripables (sl);
4245 sl.sort (Stripable::PresentationOrderSorter());
4247 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4248 if ((*s)->presentation_info().flag_match (flags)) {
4249 if (match_cnt++ == n) {
4255 /* there is no nth stripable that matches the given flags */
4256 return boost::shared_ptr<Stripable>();
4259 boost::shared_ptr<Route>
4260 Session::route_by_selected_count (uint32_t id) const
4262 boost::shared_ptr<RouteList> r = routes.reader ();
4264 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4265 /* NOT IMPLEMENTED */
4268 return boost::shared_ptr<Route> ((Route*) 0);
4271 struct PresentationOrderSorter {
4272 bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4273 if (a->presentation_info().special() && !b->presentation_info().special()) {
4274 /* a is not ordered, b is; b comes before a */
4276 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4277 /* b is not ordered, a is; a comes before b */
4280 return a->presentation_info().order() < b->presentation_info().order();
4286 Session::reassign_track_numbers ()
4290 RouteList r (*(routes.reader ()));
4291 PresentationOrderSorter sorter;
4294 StateProtector sp (this);
4296 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4297 if (boost::dynamic_pointer_cast<Track> (*i)) {
4298 (*i)->set_track_number(++tn);
4300 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4301 (*i)->set_track_number(--bn);
4304 const uint32_t decimals = ceilf (log10f (tn + 1));
4305 const bool decimals_changed = _track_number_decimals != decimals;
4306 _track_number_decimals = decimals;
4308 if (decimals_changed && config.get_track_name_number ()) {
4309 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4310 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4312 t->resync_track_name();
4315 // trigger GUI re-layout
4316 config.ParameterChanged("track-name-number");
4320 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4321 boost::shared_ptr<RouteList> rl = routes.reader ();
4322 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4323 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4331 Session::playlist_region_added (boost::weak_ptr<Region> w)
4333 boost::shared_ptr<Region> r = w.lock ();
4338 /* These are the operations that are currently in progress... */
4339 list<GQuark> curr = _current_trans_quarks;
4342 /* ...and these are the operations during which we want to update
4343 the session range location markers.
4346 ops.push_back (Operations::capture);
4347 ops.push_back (Operations::paste);
4348 ops.push_back (Operations::duplicate_region);
4349 ops.push_back (Operations::insert_file);
4350 ops.push_back (Operations::insert_region);
4351 ops.push_back (Operations::drag_region_brush);
4352 ops.push_back (Operations::region_drag);
4353 ops.push_back (Operations::selection_grab);
4354 ops.push_back (Operations::region_fill);
4355 ops.push_back (Operations::fill_selection);
4356 ops.push_back (Operations::create_region);
4357 ops.push_back (Operations::region_copy);
4358 ops.push_back (Operations::fixed_time_region_copy);
4361 /* See if any of the current operations match the ones that we want */
4363 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4365 /* If so, update the session range markers */
4367 maybe_update_session_range (r->position (), r->last_frame ());
4371 /** Update the session range markers if a is before the current start or
4372 * b is after the current end.
4375 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4377 if (_state_of_the_state & Loading) {
4381 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4383 if (_session_range_location == 0) {
4385 set_session_range_location (a, b + session_end_marker_shift_samples);
4389 if (a < _session_range_location->start()) {
4390 _session_range_location->set_start (a);
4393 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4394 _session_range_location->set_end (b);
4400 Session::set_end_is_free (bool yn)
4402 _session_range_end_is_free = yn;
4406 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4408 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4409 maybe_update_session_range (i->to, i->to + i->length);
4414 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4416 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4417 maybe_update_session_range (i->from, i->to);
4421 /* Region management */
4423 boost::shared_ptr<Region>
4424 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4426 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4427 RegionFactory::RegionMap::const_iterator i;
4428 boost::shared_ptr<Region> region;
4430 Glib::Threads::Mutex::Lock lm (region_lock);
4432 for (i = regions.begin(); i != regions.end(); ++i) {
4436 if (region->whole_file()) {
4438 if (child->source_equivalent (region)) {
4444 return boost::shared_ptr<Region> ();
4448 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4450 set<boost::shared_ptr<Region> > relevant_regions;
4452 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4453 RegionFactory::get_regions_using_source (*s, relevant_regions);
4456 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4457 set<boost::shared_ptr<Region> >::iterator tmp;
4462 playlists->destroy_region (*r);
4463 RegionFactory::map_remove (*r);
4465 (*r)->drop_sources ();
4466 (*r)->drop_references ();
4468 relevant_regions.erase (r);
4473 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4476 Glib::Threads::Mutex::Lock ls (source_lock);
4477 /* remove from the main source list */
4478 sources.erase ((*s)->id());
4481 (*s)->mark_for_remove ();
4482 (*s)->drop_references ();
4491 Session::remove_last_capture ()
4493 list<boost::shared_ptr<Source> > srcs;
4495 boost::shared_ptr<RouteList> rl = routes.reader ();
4496 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4497 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4502 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4505 srcs.insert (srcs.end(), l.begin(), l.end());
4510 destroy_sources (srcs);
4512 save_state (_current_snapshot_name);
4517 /* Source Management */
4520 Session::add_source (boost::shared_ptr<Source> source)
4522 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4523 pair<SourceMap::iterator,bool> result;
4525 entry.first = source->id();
4526 entry.second = source;
4529 Glib::Threads::Mutex::Lock lm (source_lock);
4530 result = sources.insert (entry);
4533 if (result.second) {
4535 /* yay, new source */
4537 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4540 if (!fs->within_session()) {
4541 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4547 boost::shared_ptr<AudioFileSource> afs;
4549 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4550 if (Config->get_auto_analyse_audio()) {
4551 Analyser::queue_source_for_analysis (source, false);
4555 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4560 Session::remove_source (boost::weak_ptr<Source> src)
4562 if (_state_of_the_state & Deletion) {
4566 SourceMap::iterator i;
4567 boost::shared_ptr<Source> source = src.lock();
4574 Glib::Threads::Mutex::Lock lm (source_lock);
4576 if ((i = sources.find (source->id())) != sources.end()) {
4581 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4583 /* save state so we don't end up with a session file
4584 referring to non-existent sources.
4587 save_state (_current_snapshot_name);
4591 boost::shared_ptr<Source>
4592 Session::source_by_id (const PBD::ID& id)
4594 Glib::Threads::Mutex::Lock lm (source_lock);
4595 SourceMap::iterator i;
4596 boost::shared_ptr<Source> source;
4598 if ((i = sources.find (id)) != sources.end()) {
4605 boost::shared_ptr<AudioFileSource>
4606 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4608 /* Restricted to audio files because only audio sources have channel
4612 Glib::Threads::Mutex::Lock lm (source_lock);
4614 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4615 boost::shared_ptr<AudioFileSource> afs
4616 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4618 if (afs && afs->path() == path && chn == afs->channel()) {
4623 return boost::shared_ptr<AudioFileSource>();
4626 boost::shared_ptr<MidiSource>
4627 Session::midi_source_by_path (const std::string& path) const
4629 /* Restricted to MIDI files because audio sources require a channel
4630 for unique identification, in addition to a path.
4633 Glib::Threads::Mutex::Lock lm (source_lock);
4635 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4636 boost::shared_ptr<MidiSource> ms
4637 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4638 boost::shared_ptr<FileSource> fs
4639 = boost::dynamic_pointer_cast<FileSource>(s->second);
4641 if (ms && fs && fs->path() == path) {
4646 return boost::shared_ptr<MidiSource>();
4650 Session::count_sources_by_origin (const string& path)
4653 Glib::Threads::Mutex::Lock lm (source_lock);
4655 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4656 boost::shared_ptr<FileSource> fs
4657 = boost::dynamic_pointer_cast<FileSource>(i->second);
4659 if (fs && fs->origin() == path) {
4668 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4670 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4671 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4673 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4678 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4680 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4682 if (Glib::path_is_absolute (filepath)) {
4684 /* rip the session dir from the audiofile source */
4686 string session_path;
4687 bool in_another_session = true;
4689 if (filepath.find (interchange_dir_string) != string::npos) {
4691 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4692 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4693 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4694 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4696 /* see if it is within our session */
4698 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4699 if (i->path == session_path) {
4700 in_another_session = false;
4705 in_another_session = false;
4709 if (in_another_session) {
4710 SessionDirectory sd (session_path);
4711 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4715 /* 1) if file belongs to this session
4716 * it may be a relative path (interchange/...)
4717 * or just basename (session_state, remove source)
4718 * -> just use the basename
4720 std::string filename = Glib::path_get_basename (filepath);
4723 /* 2) if the file is outside our session dir:
4724 * (imported but not copied) add the path for check-summming */
4726 path = Glib::path_get_dirname (filepath);
4729 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4733 Session::new_audio_source_path_for_embedded (const std::string& path)
4737 * we know that the filename is already unique because it exists
4738 * out in the filesystem.
4740 * However, when we bring it into the session, we could get a
4743 * Eg. two embedded files:
4748 * When merged into session, these collide.
4750 * There will not be a conflict with in-memory sources
4751 * because when the source was created we already picked
4752 * a unique name for it.
4754 * This collision is not likely to be common, but we have to guard
4755 * against it. So, if there is a collision, take the md5 hash of the
4756 * the path, and use that as the filename instead.
4759 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4760 string base = Glib::path_get_basename (path);
4761 string newpath = Glib::build_filename (sdir.sound_path(), base);
4763 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4767 md5.digestString (path.c_str());
4768 md5.writeToString ();
4769 base = md5.digestChars;
4771 string ext = get_suffix (path);
4778 newpath = Glib::build_filename (sdir.sound_path(), base);
4780 /* if this collides, we're screwed */
4782 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4783 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4792 /** Return true if there are no audio file sources that use @param name as
4793 * the filename component of their path.
4795 * Return false otherwise.
4797 * This method MUST ONLY be used to check in-session, mono files since it
4798 * hard-codes the channel of the audio file source we are looking for as zero.
4800 * If/when Ardour supports native files in non-mono formats, the logic here
4801 * will need to be revisited.
4804 Session::audio_source_name_is_unique (const string& name)
4806 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4807 vector<space_and_path>::iterator i;
4808 uint32_t existing = 0;
4810 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4812 /* note that we search *without* the extension so that
4813 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4814 in the event that this new name is required for
4815 a file format change.
4818 const string spath = *i;
4820 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4825 /* it is possible that we have the path already
4826 * assigned to a source that has not yet been written
4827 * (ie. the write source for a diskstream). we have to
4828 * check this in order to make sure that our candidate
4829 * path isn't used again, because that can lead to
4830 * two Sources point to the same file with different
4831 * notions of their removability.
4835 string possible_path = Glib::build_filename (spath, name);
4837 if (audio_source_by_path_and_channel (possible_path, 0)) {
4843 return (existing == 0);
4847 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)
4850 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4852 if (Profile->get_trx() && destructive) {
4854 sstr << setfill ('0') << setw (4) << cnt;
4855 sstr << legalized_base;
4857 sstr << legalized_base;
4859 if (take_required || related_exists) {
4871 } else if (nchan > 2) {
4876 /* XXX what? more than 26 channels! */
4887 /** Return a unique name based on \a base for a new internal audio source */
4889 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4892 string possible_name;
4893 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4895 bool some_related_source_name_exists = false;
4897 legalized = legalize_for_path (base);
4899 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4901 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4903 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4905 if (audio_source_name_is_unique (possible_name)) {
4909 some_related_source_name_exists = true;
4912 error << string_compose(
4913 _("There are already %1 recordings for %2, which I consider too many."),
4914 limit, base) << endmsg;
4916 throw failed_constructor();
4920 /* We've established that the new name does not exist in any session
4921 * directory, so now find out which one we should use for this new
4925 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4927 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4932 /** Return a unique name based on `base` for a new internal MIDI source */
4934 Session::new_midi_source_path (const string& base)
4937 char buf[PATH_MAX+1];
4938 const uint32_t limit = 10000;
4940 string possible_path;
4941 string possible_name;
4944 legalized = legalize_for_path (base);
4946 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4947 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4949 /* - the main session folder is the first in the vector.
4950 * - after checking all locations for file-name uniqueness,
4951 * we keep the one from the last iteration as new file name
4952 * - midi files are small and should just be kept in the main session-folder
4954 * -> reverse the array, check main session folder last and use that as location
4957 std::reverse(sdirs.begin(), sdirs.end());
4959 for (cnt = 1; cnt <= limit; ++cnt) {
4961 vector<space_and_path>::iterator i;
4962 uint32_t existing = 0;
4964 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4966 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4967 possible_name = buf;
4969 possible_path = Glib::build_filename (*i, possible_name);
4971 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4975 if (midi_source_by_path (possible_path)) {
4980 if (existing == 0) {
4985 error << string_compose(
4986 _("There are already %1 recordings for %2, which I consider too many."),
4987 limit, base) << endmsg;
4993 /* No need to "find best location" for software/app-based RAID, because
4994 MIDI is so small that we always put it in the same place.
4997 return possible_path;
5001 /** Create a new within-session audio source */
5002 boost::shared_ptr<AudioFileSource>
5003 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5005 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5007 if (!path.empty()) {
5008 return boost::dynamic_pointer_cast<AudioFileSource> (
5009 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5011 throw failed_constructor ();
5015 /** Create a new within-session MIDI source */
5016 boost::shared_ptr<MidiSource>
5017 Session::create_midi_source_for_session (string const & basic_name)
5019 const string path = new_midi_source_path (basic_name);
5021 if (!path.empty()) {
5022 return boost::dynamic_pointer_cast<SMFSource> (
5023 SourceFactory::createWritable (
5024 DataType::MIDI, *this, path, false, frame_rate()));
5026 throw failed_constructor ();
5030 /** Create a new within-session MIDI source */
5031 boost::shared_ptr<MidiSource>
5032 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5034 /* the caller passes in the track the source will be used in,
5035 so that we can keep the numbering sane.
5037 Rationale: a track with the name "Foo" that has had N
5038 captures carried out so far will ALREADY have a write source
5039 named "Foo-N+1.mid" waiting to be used for the next capture.
5041 If we call new_midi_source_name() we will get "Foo-N+2". But
5042 there is no region corresponding to "Foo-N+1", so when
5043 "Foo-N+2" appears in the track, the gap presents the user
5044 with odd behaviour - why did it skip past Foo-N+1?
5046 We could explain this to the user in some odd way, but
5047 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5050 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5053 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5055 std::string name = track->steal_write_source_name ();
5058 return boost::shared_ptr<MidiSource>();
5061 /* MIDI files are small, just put them in the first location of the
5062 session source search path.
5065 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5067 return boost::dynamic_pointer_cast<SMFSource> (
5068 SourceFactory::createWritable (
5069 DataType::MIDI, *this, path, false, frame_rate()));
5074 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5076 if (playlist->hidden()) {
5080 playlists->add (playlist);
5083 playlist->release();
5090 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5092 if (_state_of_the_state & Deletion) {
5096 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5102 playlists->remove (playlist);
5108 Session::set_audition (boost::shared_ptr<Region> r)
5110 pending_audition_region = r;
5111 add_post_transport_work (PostTransportAudition);
5112 _butler->schedule_transport_work ();
5116 Session::audition_playlist ()
5118 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5119 ev->region.reset ();
5125 Session::register_lua_function (
5126 const std::string& name,
5127 const std::string& script,
5128 const LuaScriptParamList& args
5131 Glib::Threads::Mutex::Lock lm (lua_lock);
5133 lua_State* L = lua.getState();
5135 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5136 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5137 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5138 if ((*i)->optional && !(*i)->is_set) { continue; }
5139 tbl_arg[(*i)->name] = (*i)->value;
5141 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5146 Session::unregister_lua_function (const std::string& name)
5148 Glib::Threads::Mutex::Lock lm (lua_lock);
5149 (*_lua_del)(name); // throws luabridge::LuaException
5150 lua.collect_garbage ();
5154 std::vector<std::string>
5155 Session::registered_lua_functions ()
5157 Glib::Threads::Mutex::Lock lm (lua_lock);
5158 std::vector<std::string> rv;
5161 luabridge::LuaRef list ((*_lua_list)());
5162 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5163 if (!i.key ().isString ()) { assert(0); continue; }
5164 rv.push_back (i.key ().cast<std::string> ());
5166 } catch (luabridge::LuaException const& e) { }
5171 static void _lua_print (std::string s) {
5172 std::cout << "SessionLua: " << s << "\n";
5177 Session::try_run_lua (pframes_t nframes)
5179 if (_n_lua_scripts == 0) return;
5180 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5182 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5183 lua.collect_garbage_step ();
5188 Session::setup_lua ()
5191 lua.Print.connect (&_lua_print);
5195 "function ArdourSession ()"
5196 " local self = { scripts = {}, instances = {} }"
5198 " local remove = function (n)"
5199 " self.scripts[n] = nil"
5200 " self.instances[n] = nil"
5201 " Session:scripts_changed()" // call back
5204 " local addinternal = function (n, f, a)"
5205 " assert(type(n) == 'string', 'function-name must be string')"
5206 " assert(type(f) == 'function', 'Given script is a not a function')"
5207 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5208 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5209 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5210 " local env = _ENV; env.f = nil env.io = nil env.os = nil env.loadfile = nil env.require = nil env.dofile = nil env.package = nil env.debug = nil"
5211 " local env = { print = print, tostring = tostring, assert = assert, ipairs = ipairs, error = error, select = select, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall, Session = Session, PBD = PBD, Timecode = Timecode, Evoral = Evoral, C = C, ARDOUR = ARDOUR }"
5212 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5213 " Session:scripts_changed()" // call back
5216 " local add = function (n, b, a)"
5217 " assert(type(b) == 'string', 'ByteCode must be string')"
5218 " load (b)()" // assigns f
5219 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5220 " addinternal (n, load(f), a)"
5223 " local run = function (...)"
5224 " for n, s in pairs (self.instances) do"
5225 " local status, err = pcall (s, ...)"
5226 " if not status then"
5227 " print ('fn \"'.. n .. '\": ', err)"
5234 " local cleanup = function ()"
5235 " self.scripts = nil"
5236 " self.instances = nil"
5239 " local list = function ()"
5241 " for n, _ in pairs (self.scripts) do"
5247 " local function basic_serialize (o)"
5248 " if type(o) == \"number\" then"
5249 " return tostring(o)"
5251 " return string.format(\"%q\", o)"
5255 " local function serialize (name, value)"
5256 " local rv = name .. ' = '"
5258 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5259 " return rv .. basic_serialize(value) .. ' '"
5260 " elseif type(value) == \"table\" then"
5262 " for k,v in pairs(value) do"
5263 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5264 " rv = rv .. serialize(fieldname, v) .. ' '"
5265 " collectgarbage()" // string concatenation allocates a new string :(
5268 " elseif type(value) == \"function\" then"
5269 " return rv .. string.format(\"%q\", string.dump(value, true))"
5271 " error('cannot save a ' .. type(value))"
5276 " local save = function ()"
5277 " return (serialize('scripts', self.scripts))"
5280 " local restore = function (state)"
5281 " self.scripts = {}"
5283 " for n, s in pairs (scripts) do"
5284 " addinternal (n, load(s['f']), s['a'])"
5288 " return { run = run, add = add, remove = remove,"
5289 " list = list, restore = restore, save = save, cleanup = cleanup}"
5292 " sess = ArdourSession ()"
5293 " ArdourSession = nil"
5295 "function ardour () end"
5298 lua_State* L = lua.getState();
5301 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5302 lua.do_command ("sess = nil"); // hide it.
5303 lua.do_command ("collectgarbage()");
5305 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5306 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5307 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5308 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5309 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5310 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5311 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5312 } catch (luabridge::LuaException const& e) {
5313 fatal << string_compose (_("programming error: %1"),
5314 X_("Failed to setup Lua interpreter"))
5316 abort(); /*NOTREACHED*/
5319 LuaBindings::stddef (L);
5320 LuaBindings::common (L);
5321 LuaBindings::dsp (L);
5322 luabridge::push <Session *> (L, this);
5323 lua_setglobal (L, "Session");
5327 Session::scripts_changed ()
5329 assert (!lua_lock.trylock()); // must hold lua_lock
5332 luabridge::LuaRef list ((*_lua_list)());
5334 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5335 if (!i.key ().isString ()) { assert(0); continue; }
5338 _n_lua_scripts = cnt;
5339 } catch (luabridge::LuaException const& e) {
5340 fatal << string_compose (_("programming error: %1"),
5341 X_("Indexing Lua Session Scripts failed."))
5343 abort(); /*NOTREACHED*/
5348 Session::non_realtime_set_audition ()
5350 assert (pending_audition_region);
5351 auditioner->audition_region (pending_audition_region);
5352 pending_audition_region.reset ();
5353 AuditionActive (true); /* EMIT SIGNAL */
5357 Session::audition_region (boost::shared_ptr<Region> r)
5359 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5365 Session::cancel_audition ()
5370 if (auditioner->auditioning()) {
5371 auditioner->cancel_audition ();
5372 AuditionActive (false); /* EMIT SIGNAL */
5377 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5379 if (a->is_monitor()) {
5382 if (b->is_monitor()) {
5385 return a->presentation_info().order() < b->presentation_info().order();
5389 Session::is_auditioning () const
5391 /* can be called before we have an auditioner object */
5393 return auditioner->auditioning();
5400 Session::graph_reordered ()
5402 /* don't do this stuff if we are setting up connections
5403 from a set_state() call or creating new tracks. Ditto for deletion.
5406 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5410 /* every track/bus asked for this to be handled but it was deferred because
5411 we were connecting. do it now.
5414 request_input_change_handling ();
5418 /* force all diskstreams to update their capture offset values to
5419 reflect any changes in latencies within the graph.
5422 boost::shared_ptr<RouteList> rl = routes.reader ();
5423 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5424 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5426 tr->set_capture_offset ();
5431 /** @return Number of frames that there is disk space available to write,
5434 boost::optional<framecnt_t>
5435 Session::available_capture_duration ()
5437 Glib::Threads::Mutex::Lock lm (space_lock);
5439 if (_total_free_4k_blocks_uncertain) {
5440 return boost::optional<framecnt_t> ();
5443 float sample_bytes_on_disk = 4.0; // keep gcc happy
5445 switch (config.get_native_file_data_format()) {
5447 sample_bytes_on_disk = 4.0;
5451 sample_bytes_on_disk = 3.0;
5455 sample_bytes_on_disk = 2.0;
5459 /* impossible, but keep some gcc versions happy */
5460 fatal << string_compose (_("programming error: %1"),
5461 X_("illegal native file data format"))
5463 abort(); /*NOTREACHED*/
5466 double scale = 4096.0 / sample_bytes_on_disk;
5468 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5469 return max_framecnt;
5472 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5476 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5479 RCUWriter<BundleList> writer (_bundles);
5480 boost::shared_ptr<BundleList> b = writer.get_copy ();
5481 b->push_back (bundle);
5485 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5492 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5494 bool removed = false;
5497 RCUWriter<BundleList> writer (_bundles);
5498 boost::shared_ptr<BundleList> b = writer.get_copy ();
5499 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5501 if (i != b->end()) {
5508 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5514 boost::shared_ptr<Bundle>
5515 Session::bundle_by_name (string name) const
5517 boost::shared_ptr<BundleList> b = _bundles.reader ();
5519 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5520 if ((*i)->name() == name) {
5525 return boost::shared_ptr<Bundle> ();
5529 Session::tempo_map_changed (const PropertyChange&)
5533 playlists->update_after_tempo_map_change ();
5535 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5541 Session::gui_tempo_map_changed ()
5545 playlists->update_after_tempo_map_change ();
5547 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5551 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5553 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5554 (*i)->recompute_frames_from_bbt ();
5558 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5559 * the given count with the current block size.
5562 Session::ensure_buffers (ChanCount howmany)
5564 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5568 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5570 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5571 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5576 Session::next_insert_id ()
5578 /* this doesn't really loop forever. just think about it */
5581 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5582 if (!insert_bitset[n]) {
5583 insert_bitset[n] = true;
5589 /* none available, so resize and try again */
5591 insert_bitset.resize (insert_bitset.size() + 16, false);
5596 Session::next_send_id ()
5598 /* this doesn't really loop forever. just think about it */
5601 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5602 if (!send_bitset[n]) {
5603 send_bitset[n] = true;
5609 /* none available, so resize and try again */
5611 send_bitset.resize (send_bitset.size() + 16, false);
5616 Session::next_aux_send_id ()
5618 /* this doesn't really loop forever. just think about it */
5621 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5622 if (!aux_send_bitset[n]) {
5623 aux_send_bitset[n] = true;
5629 /* none available, so resize and try again */
5631 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5636 Session::next_return_id ()
5638 /* this doesn't really loop forever. just think about it */
5641 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5642 if (!return_bitset[n]) {
5643 return_bitset[n] = true;
5649 /* none available, so resize and try again */
5651 return_bitset.resize (return_bitset.size() + 16, false);
5656 Session::mark_send_id (uint32_t id)
5658 if (id >= send_bitset.size()) {
5659 send_bitset.resize (id+16, false);
5661 if (send_bitset[id]) {
5662 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5664 send_bitset[id] = true;
5668 Session::mark_aux_send_id (uint32_t id)
5670 if (id >= aux_send_bitset.size()) {
5671 aux_send_bitset.resize (id+16, false);
5673 if (aux_send_bitset[id]) {
5674 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5676 aux_send_bitset[id] = true;
5680 Session::mark_return_id (uint32_t id)
5682 if (id >= return_bitset.size()) {
5683 return_bitset.resize (id+16, false);
5685 if (return_bitset[id]) {
5686 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5688 return_bitset[id] = true;
5692 Session::mark_insert_id (uint32_t id)
5694 if (id >= insert_bitset.size()) {
5695 insert_bitset.resize (id+16, false);
5697 if (insert_bitset[id]) {
5698 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5700 insert_bitset[id] = true;
5704 Session::unmark_send_id (uint32_t id)
5706 if (id < send_bitset.size()) {
5707 send_bitset[id] = false;
5712 Session::unmark_aux_send_id (uint32_t id)
5714 if (id < aux_send_bitset.size()) {
5715 aux_send_bitset[id] = false;
5720 Session::unmark_return_id (uint32_t id)
5722 if (_state_of_the_state & Deletion) { return; }
5723 if (id < return_bitset.size()) {
5724 return_bitset[id] = false;
5729 Session::unmark_insert_id (uint32_t id)
5731 if (id < insert_bitset.size()) {
5732 insert_bitset[id] = false;
5737 Session::reset_native_file_format ()
5739 boost::shared_ptr<RouteList> rl = routes.reader ();
5741 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5742 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5744 /* don't save state as we do this, there's no point
5746 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5747 tr->reset_write_sources (false);
5748 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5754 Session::route_name_unique (string n) const
5756 boost::shared_ptr<RouteList> r = routes.reader ();
5758 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5759 if ((*i)->name() == n) {
5768 Session::route_name_internal (string n) const
5770 if (auditioner && auditioner->name() == n) {
5774 if (_click_io && _click_io->name() == n) {
5782 Session::freeze_all (InterThreadInfo& itt)
5784 boost::shared_ptr<RouteList> r = routes.reader ();
5786 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5788 boost::shared_ptr<Track> t;
5790 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5791 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5801 boost::shared_ptr<Region>
5802 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5803 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5804 InterThreadInfo& itt,
5805 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5806 bool for_export, bool for_freeze)
5808 boost::shared_ptr<Region> result;
5809 boost::shared_ptr<Playlist> playlist;
5810 boost::shared_ptr<Source> source;
5811 ChanCount diskstream_channels (track.n_channels());
5812 framepos_t position;
5813 framecnt_t this_chunk;
5815 framepos_t latency_skip;
5817 framepos_t len = end - start;
5818 bool need_block_size_reset = false;
5819 ChanCount const max_proc = track.max_processor_streams ();
5820 string legal_playlist_name;
5821 string possible_path;
5824 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5825 end, start) << endmsg;
5829 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5830 include_endpoint, for_export, for_freeze);
5832 if (diskstream_channels.n(track.data_type()) < 1) {
5833 error << _("Cannot write a range with no data.") << endmsg;
5837 // block all process callback handling
5839 block_processing ();
5842 // synchronize with AudioEngine::process_callback()
5843 // make sure processing is not currently running
5844 // and processing_blocked() is honored before
5845 // acquiring thread buffers
5846 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5849 _bounce_processing_active = true;
5851 /* call tree *MUST* hold route_lock */
5853 if ((playlist = track.playlist()) == 0) {
5857 legal_playlist_name = legalize_for_path (playlist->name());
5859 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5861 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5862 string path = ((track.data_type() == DataType::AUDIO)
5863 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5864 : new_midi_source_path (legal_playlist_name));
5871 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5874 catch (failed_constructor& err) {
5875 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5879 srcs.push_back (source);
5882 /* tell redirects that care that we are about to use a much larger
5883 * blocksize. this will flush all plugins too, so that they are ready
5884 * to be used for this process.
5887 need_block_size_reset = true;
5888 track.set_block_size (bounce_chunk_size);
5889 _engine.main_thread()->get_buffers ();
5893 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5895 /* create a set of reasonably-sized buffers */
5896 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5897 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5899 buffers.set_count (max_proc);
5901 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5902 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5903 boost::shared_ptr<MidiSource> ms;
5905 afs->prepare_for_peakfile_writes ();
5906 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5907 Source::Lock lock(ms->mutex());
5908 ms->mark_streaming_write_started(lock);
5912 while (to_do && !itt.cancel) {
5914 this_chunk = min (to_do, bounce_chunk_size);
5916 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5920 start += this_chunk;
5921 to_do -= this_chunk;
5922 itt.progress = (float) (1.0 - ((double) to_do / len));
5924 if (latency_skip >= bounce_chunk_size) {
5925 latency_skip -= bounce_chunk_size;
5929 const framecnt_t current_chunk = this_chunk - latency_skip;
5932 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5933 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5934 boost::shared_ptr<MidiSource> ms;
5937 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5940 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5941 Source::Lock lock(ms->mutex());
5943 const MidiBuffer& buf = buffers.get_midi(0);
5944 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5945 Evoral::Event<framepos_t> ev = *i;
5946 ev.set_time(ev.time() - position);
5947 ms->append_event_frames(lock, ev, ms->timeline_position());
5954 /* post-roll, pick up delayed processor output */
5955 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5957 while (latency_skip && !itt.cancel) {
5958 this_chunk = min (latency_skip, bounce_chunk_size);
5959 latency_skip -= this_chunk;
5961 buffers.silence (this_chunk, 0);
5962 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5965 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5966 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5969 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5981 xnow = localtime (&now);
5983 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5984 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5985 boost::shared_ptr<MidiSource> ms;
5988 afs->update_header (position, *xnow, now);
5989 afs->flush_header ();
5990 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5991 Source::Lock lock(ms->mutex());
5992 ms->mark_streaming_write_completed(lock);
5996 /* construct a region to represent the bounced material */
6000 plist.add (Properties::start, 0);
6001 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6002 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6004 result = RegionFactory::create (srcs, plist);
6010 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6011 (*src)->mark_for_remove ();
6012 (*src)->drop_references ();
6016 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6017 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6020 afs->done_with_peakfile_writes ();
6024 _bounce_processing_active = false;
6026 if (need_block_size_reset) {
6027 _engine.main_thread()->drop_buffers ();
6028 track.set_block_size (get_block_size());
6031 unblock_processing ();
6037 Session::gain_automation_buffer() const
6039 return ProcessThread::gain_automation_buffer ();
6043 Session::trim_automation_buffer() const
6045 return ProcessThread::trim_automation_buffer ();
6049 Session::send_gain_automation_buffer() const
6051 return ProcessThread::send_gain_automation_buffer ();
6055 Session::pan_automation_buffer() const
6057 return ProcessThread::pan_automation_buffer ();
6061 Session::get_silent_buffers (ChanCount count)
6063 return ProcessThread::get_silent_buffers (count);
6067 Session::get_scratch_buffers (ChanCount count, bool silence)
6069 return ProcessThread::get_scratch_buffers (count, silence);
6073 Session::get_noinplace_buffers (ChanCount count)
6075 return ProcessThread::get_noinplace_buffers (count);
6079 Session::get_route_buffers (ChanCount count, bool silence)
6081 return ProcessThread::get_route_buffers (count, silence);
6086 Session::get_mix_buffers (ChanCount count)
6088 return ProcessThread::get_mix_buffers (count);
6092 Session::ntracks () const
6095 boost::shared_ptr<RouteList> r = routes.reader ();
6097 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6098 if (boost::dynamic_pointer_cast<Track> (*i)) {
6107 Session::nbusses () const
6110 boost::shared_ptr<RouteList> r = routes.reader ();
6112 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6113 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6122 Session::add_automation_list(AutomationList *al)
6124 automation_lists[al->id()] = al;
6127 /** @return true if there is at least one record-enabled track, otherwise false */
6129 Session::have_rec_enabled_track () const
6131 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6135 Session::have_rec_disabled_track () const
6137 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6140 /** Update the state of our rec-enabled tracks flag */
6142 Session::update_route_record_state ()
6144 boost::shared_ptr<RouteList> rl = routes.reader ();
6145 RouteList::iterator i = rl->begin();
6146 while (i != rl->end ()) {
6148 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6149 if (tr && tr->rec_enable_control()->get_value()) {
6156 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6158 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6160 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6161 RecordStateChanged (); /* EMIT SIGNAL */
6164 for (i = rl->begin(); i != rl->end (); ++i) {
6165 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6166 if (tr && !tr->rec_enable_control()->get_value()) {
6171 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6173 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6175 if (record_status() == Recording && record_arm_state_changed ) {
6176 RecordArmStateChanged ();
6182 Session::listen_position_changed ()
6184 boost::shared_ptr<RouteList> r = routes.reader ();
6186 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6187 (*i)->listen_position_changed ();
6192 Session::solo_control_mode_changed ()
6194 if (soloing() || listening()) {
6195 /* We can't use ::clear_all_solo_state() here because during
6196 session loading at program startup, that will queue a call
6197 to rt_clear_all_solo_state() that will not execute until
6198 AFTER solo states have been established (thus throwing away
6199 the session's saved solo state). So just explicitly turn
6202 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6206 /** Called when a property of one of our route groups changes */
6208 Session::route_group_property_changed (RouteGroup* rg)
6210 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6213 /** Called when a route is added to one of our route groups */
6215 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6217 RouteAddedToRouteGroup (rg, r);
6220 /** Called when a route is removed from one of our route groups */
6222 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6224 update_route_record_state ();
6225 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6228 boost::shared_ptr<RouteList>
6229 Session::get_tracks () const
6231 boost::shared_ptr<RouteList> rl = routes.reader ();
6232 boost::shared_ptr<RouteList> tl (new RouteList);
6234 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6235 if (boost::dynamic_pointer_cast<Track> (*r)) {
6236 if (!(*r)->is_auditioner()) {
6244 boost::shared_ptr<RouteList>
6245 Session::get_routes_with_regions_at (framepos_t const p) const
6247 boost::shared_ptr<RouteList> r = routes.reader ();
6248 boost::shared_ptr<RouteList> rl (new RouteList);
6250 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6251 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6256 boost::shared_ptr<Playlist> pl = tr->playlist ();
6261 if (pl->has_region_at (p)) {
6270 Session::goto_end ()
6272 if (_session_range_location) {
6273 request_locate (_session_range_location->end(), false);
6275 request_locate (0, false);
6280 Session::goto_start ()
6282 if (_session_range_location) {
6283 request_locate (_session_range_location->start(), false);
6285 request_locate (0, false);
6290 Session::current_start_frame () const
6292 return _session_range_location ? _session_range_location->start() : 0;
6296 Session::current_end_frame () const
6298 return _session_range_location ? _session_range_location->end() : 0;
6302 Session::set_session_range_location (framepos_t start, framepos_t end)
6304 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6305 _locations->add (_session_range_location);
6309 Session::step_edit_status_change (bool yn)
6315 send = (_step_editors == 0);
6320 send = (_step_editors == 1);
6323 if (_step_editors > 0) {
6329 StepEditStatusChange (val);
6335 Session::start_time_changed (framepos_t old)
6337 /* Update the auto loop range to match the session range
6338 (unless the auto loop range has been changed by the user)
6341 Location* s = _locations->session_range_location ();
6346 Location* l = _locations->auto_loop_location ();
6348 if (l && l->start() == old) {
6349 l->set_start (s->start(), true);
6354 Session::end_time_changed (framepos_t old)
6356 /* Update the auto loop range to match the session range
6357 (unless the auto loop range has been changed by the user)
6360 Location* s = _locations->session_range_location ();
6365 Location* l = _locations->auto_loop_location ();
6367 if (l && l->end() == old) {
6368 l->set_end (s->end(), true);
6372 std::vector<std::string>
6373 Session::source_search_path (DataType type) const
6377 if (session_dirs.size() == 1) {
6379 case DataType::AUDIO:
6380 sp.push_back (_session_dir->sound_path());
6382 case DataType::MIDI:
6383 sp.push_back (_session_dir->midi_path());
6387 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6388 SessionDirectory sdir (i->path);
6390 case DataType::AUDIO:
6391 sp.push_back (sdir.sound_path());
6393 case DataType::MIDI:
6394 sp.push_back (sdir.midi_path());
6400 if (type == DataType::AUDIO) {
6401 const string sound_path_2X = _session_dir->sound_path_2X();
6402 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6403 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6404 sp.push_back (sound_path_2X);
6409 // now check the explicit (possibly user-specified) search path
6412 case DataType::AUDIO:
6413 sp += Searchpath(config.get_audio_search_path ());
6415 case DataType::MIDI:
6416 sp += Searchpath(config.get_midi_search_path ());
6424 Session::ensure_search_path_includes (const string& path, DataType type)
6433 case DataType::AUDIO:
6434 sp += Searchpath(config.get_audio_search_path ());
6436 case DataType::MIDI:
6437 sp += Searchpath (config.get_midi_search_path ());
6441 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6442 /* No need to add this new directory if it has the same inode as
6443 an existing one; checking inode rather than name prevents duplicated
6444 directories when we are using symlinks.
6446 On Windows, I think we could just do if (*i == path) here.
6448 if (PBD::equivalent_paths (*i, path)) {
6456 case DataType::AUDIO:
6457 config.set_audio_search_path (sp.to_string());
6459 case DataType::MIDI:
6460 config.set_midi_search_path (sp.to_string());
6466 Session::remove_dir_from_search_path (const string& dir, DataType type)
6471 case DataType::AUDIO:
6472 sp = Searchpath(config.get_audio_search_path ());
6474 case DataType::MIDI:
6475 sp = Searchpath (config.get_midi_search_path ());
6482 case DataType::AUDIO:
6483 config.set_audio_search_path (sp.to_string());
6485 case DataType::MIDI:
6486 config.set_midi_search_path (sp.to_string());
6492 boost::shared_ptr<Speakers>
6493 Session::get_speakers()
6499 Session::unknown_processors () const
6503 boost::shared_ptr<RouteList> r = routes.reader ();
6504 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6505 list<string> t = (*i)->unknown_processors ();
6506 copy (t.begin(), t.end(), back_inserter (p));
6516 Session::update_latency (bool playback)
6519 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6521 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6525 boost::shared_ptr<RouteList> r = routes.reader ();
6526 framecnt_t max_latency = 0;
6529 /* reverse the list so that we work backwards from the last route to run to the first */
6530 RouteList* rl = routes.reader().get();
6531 r.reset (new RouteList (*rl));
6532 reverse (r->begin(), r->end());
6535 /* compute actual latency values for the given direction and store them all in per-port
6536 structures. this will also publish the same values (to JACK) so that computation of latency
6537 for routes can consistently use public latency values.
6540 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6541 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6544 /* because we latency compensate playback, our published playback latencies should
6545 be the same for all output ports - all material played back by ardour has
6546 the same latency, whether its caused by plugins or by latency compensation. since
6547 these may differ from the values computed above, reset all playback port latencies
6551 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6553 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6554 (*i)->set_public_port_latencies (max_latency, playback);
6559 post_playback_latency ();
6563 post_capture_latency ();
6566 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6570 Session::post_playback_latency ()
6572 set_worst_playback_latency ();
6574 boost::shared_ptr<RouteList> r = routes.reader ();
6576 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6577 if (!(*i)->is_auditioner() && ((*i)->active())) {
6578 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6582 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6583 (*i)->set_latency_compensation (_worst_track_latency);
6588 Session::post_capture_latency ()
6590 set_worst_capture_latency ();
6592 /* reflect any changes in capture latencies into capture offsets
6595 boost::shared_ptr<RouteList> rl = routes.reader();
6596 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6597 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6599 tr->set_capture_offset ();
6605 Session::initialize_latencies ()
6608 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6609 update_latency (false);
6610 update_latency (true);
6613 set_worst_io_latencies ();
6617 Session::set_worst_io_latencies ()
6619 set_worst_playback_latency ();
6620 set_worst_capture_latency ();
6624 Session::set_worst_playback_latency ()
6626 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6630 _worst_output_latency = 0;
6632 if (!_engine.connected()) {
6636 boost::shared_ptr<RouteList> r = routes.reader ();
6638 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6639 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6642 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6646 Session::set_worst_capture_latency ()
6648 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6652 _worst_input_latency = 0;
6654 if (!_engine.connected()) {
6658 boost::shared_ptr<RouteList> r = routes.reader ();
6660 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6661 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6664 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6668 Session::update_latency_compensation (bool force_whole_graph)
6670 bool some_track_latency_changed = false;
6672 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6676 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6678 _worst_track_latency = 0;
6680 boost::shared_ptr<RouteList> r = routes.reader ();
6682 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6683 if (!(*i)->is_auditioner() && ((*i)->active())) {
6685 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6686 some_track_latency_changed = true;
6688 _worst_track_latency = max (tl, _worst_track_latency);
6692 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6693 (some_track_latency_changed ? "yes" : "no")));
6695 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6697 if (some_track_latency_changed || force_whole_graph) {
6698 _engine.update_latencies ();
6702 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6703 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6707 tr->set_capture_offset ();
6712 Session::session_name_is_legal (const string& path)
6714 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6716 for (int i = 0; illegal_chars[i]; ++i) {
6717 if (path.find (illegal_chars[i]) != string::npos) {
6718 return illegal_chars[i];
6726 Session::notify_presentation_info_change ()
6728 if (deletion_in_progress()) {
6732 PresentationInfo::Change (); /* EMIT SIGNAL */
6733 reassign_track_numbers();
6735 #ifdef USE_TRACKS_CODE_FEATURES
6736 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6737 * if track order has been changed by user
6739 reconnect_existing_routes(true, true);
6745 Session::operation_in_progress (GQuark op) const
6747 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6750 boost::shared_ptr<Port>
6751 Session::ltc_input_port () const
6753 return _ltc_input->nth (0);
6756 boost::shared_ptr<Port>
6757 Session::ltc_output_port () const
6759 return _ltc_output->nth (0);
6763 Session::reconnect_ltc_input ()
6767 string src = Config->get_ltc_source_port();
6769 _ltc_input->disconnect (this);
6771 if (src != _("None") && !src.empty()) {
6772 _ltc_input->nth (0)->connect (src);
6775 if ( ARDOUR::Profile->get_trx () ) {
6776 // Tracks need this signal to update timecode_source_dropdown
6777 MtcOrLtcInputPortChanged (); //emit signal
6783 Session::reconnect_ltc_output ()
6787 string src = Config->get_ltc_output_port();
6789 _ltc_output->disconnect (this);
6791 if (src != _("None") && !src.empty()) {
6792 _ltc_output->nth (0)->connect (src);
6798 Session::set_range_selection (framepos_t start, framepos_t end)
6800 _range_selection = Evoral::Range<framepos_t> (start, end);
6801 #ifdef USE_TRACKS_CODE_FEATURES
6802 follow_playhead_priority ();
6807 Session::set_object_selection (framepos_t start, framepos_t end)
6809 _object_selection = Evoral::Range<framepos_t> (start, end);
6810 #ifdef USE_TRACKS_CODE_FEATURES
6811 follow_playhead_priority ();
6816 Session::clear_range_selection ()
6818 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6819 #ifdef USE_TRACKS_CODE_FEATURES
6820 follow_playhead_priority ();
6825 Session::clear_object_selection ()
6827 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6828 #ifdef USE_TRACKS_CODE_FEATURES
6829 follow_playhead_priority ();
6834 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6835 const ChanCount& input_start,
6836 const ChanCount& output_start,
6837 const ChanCount& input_offset,
6838 const ChanCount& output_offset)
6840 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6841 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6842 input_start, output_start,
6843 input_offset, output_offset));
6845 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6846 pthread_cond_signal (&_auto_connect_cond);
6847 pthread_mutex_unlock (&_auto_connect_mutex);
6852 Session::queue_latency_recompute ()
6854 g_atomic_int_inc (&_latency_recompute_pending);
6855 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6856 pthread_cond_signal (&_auto_connect_cond);
6857 pthread_mutex_unlock (&_auto_connect_mutex);
6862 Session::auto_connect (const AutoConnectRequest& ar)
6864 boost::shared_ptr<Route> route = ar.route.lock();
6866 if (!route) { return; }
6868 if (!IO::connecting_legal) {
6872 /* If both inputs and outputs are auto-connected to physical ports,
6873 * use the max of input and output offsets to ensure auto-connected
6874 * port numbers always match up (e.g. the first audio input and the
6875 * first audio output of the route will have the same physical
6876 * port number). Otherwise just use the lowest input or output
6880 const bool in_out_physical =
6881 (Config->get_input_auto_connect() & AutoConnectPhysical)
6882 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6883 && ar.connect_inputs;
6885 const ChanCount in_offset = in_out_physical
6886 ? ChanCount::max(ar.input_offset, ar.output_offset)
6889 const ChanCount out_offset = in_out_physical
6890 ? ChanCount::max(ar.input_offset, ar.output_offset)
6893 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6894 vector<string> physinputs;
6895 vector<string> physoutputs;
6897 _engine.get_physical_outputs (*t, physoutputs);
6898 _engine.get_physical_inputs (*t, physinputs);
6900 if (!physinputs.empty() && ar.connect_inputs) {
6901 uint32_t nphysical_in = physinputs.size();
6903 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6906 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6907 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6910 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6916 if (!physoutputs.empty()) {
6917 uint32_t nphysical_out = physoutputs.size();
6918 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6922 * do not create new connections if we reached the limit of physical outputs
6925 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6926 ARDOUR::Profile->get_trx () &&
6927 ar.output_offset.get(*t) == nphysical_out ) {
6931 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6932 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6933 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6934 /* master bus is audio only */
6935 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6936 port = _master_out->input()->ports().port(*t,
6937 i % _master_out->input()->n_ports().get(*t))->name();
6941 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6950 Session::auto_connect_thread_start ()
6952 if (_ac_thread_active) {
6956 while (!_auto_connect_queue.empty ()) {
6957 _auto_connect_queue.pop ();
6960 _ac_thread_active = true;
6961 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6962 _ac_thread_active = false;
6967 Session::auto_connect_thread_terminate ()
6969 if (!_ac_thread_active) {
6972 _ac_thread_active = false;
6975 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6976 while (!_auto_connect_queue.empty ()) {
6977 _auto_connect_queue.pop ();
6981 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6982 pthread_cond_signal (&_auto_connect_cond);
6983 pthread_mutex_unlock (&_auto_connect_mutex);
6987 pthread_join (_auto_connect_thread, &status);
6991 Session::auto_connect_thread (void *arg)
6993 Session *s = static_cast<Session *>(arg);
6994 s->auto_connect_thread_run ();
7000 Session::auto_connect_thread_run ()
7002 pthread_set_name (X_("autoconnect"));
7003 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7004 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7005 pthread_mutex_lock (&_auto_connect_mutex);
7006 while (_ac_thread_active) {
7008 if (!_auto_connect_queue.empty ()) {
7009 // Why would we need the process lock ??
7010 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7011 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7012 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7013 // We have control over those, but what does jack do?
7014 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7016 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7017 while (!_auto_connect_queue.empty ()) {
7018 const AutoConnectRequest ar (_auto_connect_queue.front());
7019 _auto_connect_queue.pop ();
7026 if (!actively_recording ()) { // might not be needed,
7027 /* this is only used for updating plugin latencies, the
7028 * graph does not change. so it's safe in general.
7030 * .. update_latency_compensation () entails set_capture_offset()
7031 * which calls Diskstream::set_capture_offset () which
7032 * modifies the capture offset... which can be a proplem
7033 * in "prepare_to_stop"
7035 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7036 update_latency_compensation ();
7040 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7042 pthread_mutex_unlock (&_auto_connect_mutex);