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/route_graph.h"
94 #include "ardour/route_group.h"
95 #include "ardour/route_sorters.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/source_factory.h"
102 #include "ardour/speakers.h"
103 #include "ardour/tempo.h"
104 #include "ardour/ticker.h"
105 #include "ardour/track.h"
106 #include "ardour/user_bundle.h"
107 #include "ardour/utils.h"
108 #include "ardour/vca_manager.h"
110 #include "midi++/port.h"
111 #include "midi++/mmc.h"
113 #include "LuaBridge/LuaBridge.h"
117 #include <glibmm/checksum.h>
126 using namespace ARDOUR;
129 bool Session::_disable_all_loaded_plugins = false;
130 bool Session::_bypass_all_loaded_plugins = false;
131 guint Session::_name_id_counter = 0;
133 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
134 PBD::Signal1<void,std::string> Session::Dialog;
135 PBD::Signal0<int> Session::AskAboutPendingState;
136 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
137 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
138 PBD::Signal0<void> Session::SendFeedback;
139 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
141 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
142 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
143 PBD::Signal2<void,std::string, std::string> Session::Exported;
144 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
145 PBD::Signal0<void> Session::Quit;
146 PBD::Signal0<void> Session::FeedbackDetected;
147 PBD::Signal0<void> Session::SuccessfulGraphSort;
148 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
150 const framecnt_t Session::bounce_chunk_size = 8192;
151 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
152 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
154 // seconds should be added after the region exceeds end marker
155 #ifdef USE_TRACKS_CODE_FEATURES
156 const uint32_t Session::session_end_shift = 5;
158 const uint32_t Session::session_end_shift = 0;
161 /** @param snapshot_name Snapshot name, without .ardour suffix */
162 Session::Session (AudioEngine &eng,
163 const string& fullpath,
164 const string& snapshot_name,
165 BusProfile* bus_profile,
167 : playlists (new SessionPlaylists)
169 , process_function (&Session::process_with_events)
170 , _bounce_processing_active (false)
171 , waiting_for_sync_offset (false)
172 , _base_frame_rate (0)
173 , _nominal_frame_rate (0)
174 , _current_frame_rate (0)
175 , transport_sub_state (0)
176 , _record_status (Disabled)
177 , _transport_frame (0)
178 , _session_range_location (0)
181 , _transport_speed (0)
182 , _default_transport_speed (1.0)
183 , _last_transport_speed (0)
184 , _target_transport_speed (0.0)
185 , auto_play_legal (false)
186 , _last_slave_transport_frame (0)
187 , maximum_output_latency (0)
188 , _requested_return_frame (-1)
189 , current_block_size (0)
190 , _worst_output_latency (0)
191 , _worst_input_latency (0)
192 , _worst_track_latency (0)
193 , _have_captured (false)
194 , _non_soloed_outs_muted (false)
197 , _solo_isolated_cnt (0)
199 , _was_seamless (Config->get_seamless_loop ())
200 , _under_nsm_control (false)
202 , delta_accumulator_cnt (0)
203 , average_slave_delta (1800) // !!! why 1800 ???
205 , have_first_delta_accumulator (false)
206 , _slave_state (Stopped)
207 , _mtc_active (false)
208 , _ltc_active (false)
209 , post_export_sync (false)
210 , post_export_position (0)
212 , _export_rolling (false)
213 , _export_preroll (0)
214 , _pre_export_mmc_enabled (false)
215 , _name (snapshot_name)
217 , _send_qf_mtc (false)
218 , _pframes_since_last_mtc (0)
219 , session_midi_feedback (0)
221 , loop_changing (false)
223 , _session_dir (new SessionDirectory (fullpath))
224 , _current_snapshot_name (snapshot_name)
226 , state_was_pending (false)
227 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
229 , _save_queued (false)
230 , _last_roll_location (0)
231 , _last_roll_or_reversal_location (0)
232 , _last_record_location (0)
233 , pending_locate_roll (false)
234 , pending_locate_frame (0)
235 , pending_locate_flush (false)
236 , pending_abort (false)
237 , pending_auto_loop (false)
238 , _mempool ("Session", 1048576)
239 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
241 , _butler (new Butler (*this))
242 , _post_transport_work (0)
243 , cumulative_rf_motion (0)
245 , _locations (new Locations (*this))
246 , _ignore_skips_updates (false)
247 , _rt_thread_active (false)
248 , _rt_emit_pending (false)
249 , _ac_thread_active (false)
251 , outbound_mtc_timecode_frame (0)
252 , next_quarter_frame_to_send (-1)
253 , _frames_per_timecode_frame (0)
254 , _frames_per_hour (0)
255 , _timecode_frames_per_hour (0)
256 , last_timecode_valid (false)
257 , last_timecode_when (0)
258 , _send_timecode_update (false)
270 , ltc_timecode_offset (0)
271 , ltc_timecode_negative_offset (false)
272 , midi_control_ui (0)
274 , _all_route_group (new RouteGroup (*this, "all"))
275 , routes (new RouteList)
276 , _adding_routes_in_progress (false)
277 , _reconnecting_routes_in_progress (false)
278 , _route_deletion_in_progress (false)
279 , destructive_index (0)
280 , _track_number_decimals(1)
281 , default_fade_steepness (0)
282 , default_fade_msecs (0)
283 , _total_free_4k_blocks (0)
284 , _total_free_4k_blocks_uncertain (false)
285 , no_questions_about_missing_files (false)
288 , _bundles (new BundleList)
289 , _bundle_xml_node (0)
293 , click_emphasis_data (0)
295 , click_emphasis_length (0)
296 , _clicks_cleared (0)
297 , _play_range (false)
298 , _range_selection (-1,-1)
299 , _object_selection (-1,-1)
301 , first_file_data_format_reset (true)
302 , first_file_header_format_reset (true)
303 , have_looped (false)
304 , _have_rec_enabled_track (false)
305 , _have_rec_disabled_track (true)
307 , _suspend_timecode_transmission (0)
308 , _speakers (new Speakers)
310 , ignore_route_processor_changes (false)
315 , _vca_manager (new VCAManager (*this))
319 pthread_mutex_init (&_rt_emit_mutex, 0);
320 pthread_cond_init (&_rt_emit_cond, 0);
322 pthread_mutex_init (&_auto_connect_mutex, 0);
323 pthread_cond_init (&_auto_connect_cond, 0);
325 init_name_id_counter (1); // reset for new sessions, start at 1
327 pre_engine_init (fullpath);
333 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
335 #ifdef USE_TRACKS_CODE_FEATURES
336 sr = EngineStateController::instance()->get_current_sample_rate();
338 if (ensure_engine (sr, true)) {
340 throw SessionException (_("Cannot connect to audio/midi engine"));
343 // set samplerate for plugins added early
344 // e.g from templates or MB channelstrip
345 set_block_size (_engine.samples_per_cycle());
346 set_frame_rate (_engine.sample_rate());
348 if (create (mix_template, bus_profile)) {
350 throw SessionException (_("Session initialization failed"));
353 /* if a mix template was provided, then ::create() will
354 * have copied it into the session and we need to load it
355 * so that we have the state ready for ::set_state()
356 * after the engine is started.
358 * Note that we do NOT try to get the sample rate from
359 * the template at this time, though doing so would
360 * be easy if we decided this was an appropriate part
364 if (!mix_template.empty()) {
365 if (load_state (_current_snapshot_name)) {
366 throw SessionException (_("Failed to load template/snapshot state"));
368 store_recent_templates (mix_template);
371 /* load default session properties - if any */
376 if (load_state (_current_snapshot_name)) {
377 throw SessionException (_("Failed to load state"));
380 /* try to get sample rate from XML state so that we
381 * can influence the SR if we set up the audio
386 XMLProperty const * prop;
387 XMLNode const * root (state_tree->root());
388 if ((prop = root->property (X_("sample-rate"))) != 0) {
389 sr = atoi (prop->value());
393 if (ensure_engine (sr, false)) {
395 throw SessionException (_("Cannot connect to audio/midi engine"));
399 if (post_engine_init ()) {
401 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
404 store_recent_sessions (_name, _path);
406 bool was_dirty = dirty();
408 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
410 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
411 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
414 DirtyChanged (); /* EMIT SIGNAL */
417 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
418 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
420 emit_thread_start ();
421 auto_connect_thread_start ();
423 /* hook us up to the engine since we are now completely constructed */
425 BootMessage (_("Connect to engine"));
427 _engine.set_session (this);
428 _engine.reset_timebase ();
430 #ifdef USE_TRACKS_CODE_FEATURES
432 EngineStateController::instance()->set_session(this);
435 if ( ARDOUR::Profile->get_trx () ) {
437 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
438 * each available input must have corresponding track when session starts.
441 uint32_t how_many (0);
443 std::vector<std::string> inputs;
444 EngineStateController::instance()->get_physical_audio_inputs(inputs);
446 how_many = inputs.size();
448 list<boost::shared_ptr<AudioTrack> > tracks;
450 // Track names after driver
451 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
452 string track_name = "";
453 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
455 track_name = inputs[i];
456 replace_all (track_name, "system:capture", "");
458 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
459 tracks.insert(tracks.begin(), single_track.front());
461 } else { // Default track names
462 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
465 if (tracks.size() != how_many) {
467 throw failed_constructor ();
476 BootMessage (_("Session loading complete"));
488 Session::next_name_id ()
490 return g_atomic_int_add (&_name_id_counter, 1);
494 Session::name_id_counter ()
496 return g_atomic_int_get (&_name_id_counter);
500 Session::init_name_id_counter (guint n)
502 g_atomic_int_set (&_name_id_counter, n);
506 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
508 if (_engine.current_backend() == 0) {
509 /* backend is unknown ... */
510 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
511 if (r.get_value_or (-1) != 0) {
514 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
516 } else if (_engine.setup_required()) {
517 /* backend is known, but setup is needed */
518 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
519 if (r.get_value_or (-1) != 0) {
522 } else if (!_engine.running()) {
523 if (_engine.start()) {
528 /* at this point the engine should be running */
530 if (!_engine.running()) {
534 return immediately_post_engine ();
539 Session::immediately_post_engine ()
541 /* Do various initializations that should take place directly after we
542 * know that the engine is running, but before we either create a
543 * session or set state for an existing one.
546 if (how_many_dsp_threads () > 1) {
547 /* For now, only create the graph if we are using >1 DSP threads, as
548 it is a bit slower than the old code with 1 thread.
550 _process_graph.reset (new Graph (*this));
553 /* every time we reconnect, recompute worst case output latencies */
555 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
557 if (synced_to_engine()) {
558 _engine.transport_stop ();
561 if (config.get_jack_time_master()) {
562 _engine.transport_locate (_transport_frame);
567 BootMessage (_("Set up LTC"));
569 BootMessage (_("Set up Click"));
571 BootMessage (_("Set up standard connections"));
575 catch (failed_constructor& err) {
579 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
581 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
589 vector<void*> debug_pointers;
591 /* if we got to here, leaving pending capture state around
595 remove_pending_capture_state ();
599 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
601 /* stop autoconnecting */
602 auto_connect_thread_terminate ();
604 /* disconnect from any and all signals that we are connected to */
606 Port::PortSignalDrop (); /* EMIT SIGNAL */
609 /* shutdown control surface protocols while we still have ports
610 and the engine to move data to any devices.
613 ControlProtocolManager::instance().drop_protocols ();
615 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
617 _engine.remove_session ();
619 #ifdef USE_TRACKS_CODE_FEATURES
620 EngineStateController::instance()->remove_session();
623 /* deregister all ports - there will be no process or any other
624 * callbacks from the engine any more.
627 Port::PortDrop (); /* EMIT SIGNAL */
631 /* clear history so that no references to objects are held any more */
635 /* clear state tree so that no references to objects are held any more */
640 // unregister all lua functions, drop held references (if any)
642 lua.do_command ("Session = nil");
650 lua.collect_garbage ();
652 /* reset dynamic state version back to default */
653 Stateful::loading_state_version = 0;
655 _butler->drop_references ();
659 delete _all_route_group;
661 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
662 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
666 if (click_data != default_click) {
667 delete [] click_data;
670 if (click_emphasis_data != default_click_emphasis) {
671 delete [] click_emphasis_data;
676 /* need to remove auditioner before monitoring section
677 * otherwise it is re-connected */
680 /* drop references to routes held by the monitoring section
681 * specifically _monitor_out aux/listen references */
682 remove_monitor_section();
684 /* clear out any pending dead wood from RCU managed objects */
689 AudioDiskstream::free_working_buffers();
691 /* tell everyone who is still standing that we're about to die */
694 /* tell everyone to drop references and delete objects as we go */
696 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
697 RegionFactory::delete_all_regions ();
699 /* Do this early so that VCAs no longer hold references to routes */
701 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
704 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
706 /* reset these three references to special routes before we do the usual route delete thing */
708 _master_out.reset ();
709 _monitor_out.reset ();
712 RCUWriter<RouteList> writer (routes);
713 boost::shared_ptr<RouteList> r = writer.get_copy ();
715 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
716 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
717 (*i)->drop_references ();
721 /* writer goes out of scope and updates master */
726 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
727 Glib::Threads::Mutex::Lock lm (source_lock);
728 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
729 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
730 i->second->drop_references ();
736 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
739 emit_thread_terminate ();
741 pthread_cond_destroy (&_rt_emit_cond);
742 pthread_mutex_destroy (&_rt_emit_mutex);
744 pthread_cond_destroy (&_auto_connect_cond);
745 pthread_mutex_destroy (&_auto_connect_mutex);
747 delete _scene_changer; _scene_changer = 0;
748 delete midi_control_ui; midi_control_ui = 0;
750 delete _mmc; _mmc = 0;
751 delete _midi_ports; _midi_ports = 0;
752 delete _locations; _locations = 0;
757 /* clear event queue, the session is gone, nobody is interested in
758 * those anymore, but they do leak memory if not removed
760 while (!immediate_events.empty ()) {
761 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
762 SessionEvent *ev = immediate_events.front ();
763 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
764 immediate_events.pop_front ();
768 case SessionEvent::AutoLoop:
769 case SessionEvent::AutoLoopDeclick:
770 case SessionEvent::Skip:
771 case SessionEvent::PunchIn:
772 case SessionEvent::PunchOut:
773 case SessionEvent::StopOnce:
774 case SessionEvent::RangeStop:
775 case SessionEvent::RangeLocate:
779 case SessionEvent::RealTimeOperation:
786 del = del && !_remove_event (ev);
793 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
795 BOOST_SHOW_POINTERS ();
799 Session::setup_ltc ()
803 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
804 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
806 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
807 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
810 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
811 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
813 reconnect_ltc_input ();
816 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
817 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
820 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
821 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
823 reconnect_ltc_output ();
826 /* fix up names of LTC ports because we don't want the normal
827 * IO style of NAME/TYPE-{in,out}N
830 _ltc_input->nth (0)->set_name (X_("LTC-in"));
831 _ltc_output->nth (0)->set_name (X_("LTC-out"));
835 Session::setup_click ()
839 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
840 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
842 _click_io.reset (new ClickIO (*this, X_("Click")));
843 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
844 _click_gain->activate ();
846 setup_click_state (state_tree->root());
848 setup_click_state (0);
853 Session::setup_click_state (const XMLNode* node)
855 const XMLNode* child = 0;
857 if (node && (child = find_named_node (*node, "Click")) != 0) {
859 /* existing state for Click */
862 if (Stateful::loading_state_version < 3000) {
863 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
865 const XMLNodeList& children (child->children());
866 XMLNodeList::const_iterator i = children.begin();
867 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
869 if (i != children.end()) {
870 c = _click_gain->set_state (**i, Stateful::loading_state_version);
876 _clicking = Config->get_clicking ();
880 error << _("could not setup Click I/O") << endmsg;
887 /* default state for Click: dual-mono to first 2 physical outputs */
890 _engine.get_physical_outputs (DataType::AUDIO, outs);
892 for (uint32_t physport = 0; physport < 2; ++physport) {
893 if (outs.size() > physport) {
894 if (_click_io->add_port (outs[physport], this)) {
895 // relax, even though its an error
900 if (_click_io->n_ports () > ChanCount::ZERO) {
901 _clicking = Config->get_clicking ();
907 Session::setup_bundles ()
911 RCUWriter<BundleList> writer (_bundles);
912 boost::shared_ptr<BundleList> b = writer.get_copy ();
913 for (BundleList::iterator i = b->begin(); i != b->end();) {
914 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
922 vector<string> inputs[DataType::num_types];
923 vector<string> outputs[DataType::num_types];
924 for (uint32_t i = 0; i < DataType::num_types; ++i) {
925 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
926 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
929 /* Create a set of Bundle objects that map
930 to the physical I/O currently available. We create both
931 mono and stereo bundles, so that the common cases of mono
932 and stereo tracks get bundles to put in their mixer strip
933 in / out menus. There may be a nicer way of achieving that;
934 it doesn't really scale that well to higher channel counts
937 /* mono output bundles */
939 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
941 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
943 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
945 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
948 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
949 c->add_channel (_("mono"), DataType::AUDIO);
950 c->set_port (0, outputs[DataType::AUDIO][np]);
952 add_bundle (c, false);
955 /* stereo output bundles */
957 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
958 if (np + 1 < outputs[DataType::AUDIO].size()) {
960 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
961 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
962 c->add_channel (_("L"), DataType::AUDIO);
963 c->set_port (0, outputs[DataType::AUDIO][np]);
964 c->add_channel (_("R"), DataType::AUDIO);
965 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
967 add_bundle (c, false);
971 /* mono input bundles */
973 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
975 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
977 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
979 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
982 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
983 c->add_channel (_("mono"), DataType::AUDIO);
984 c->set_port (0, inputs[DataType::AUDIO][np]);
986 add_bundle (c, false);
989 /* stereo input bundles */
991 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
992 if (np + 1 < inputs[DataType::AUDIO].size()) {
994 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
996 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
997 c->add_channel (_("L"), DataType::AUDIO);
998 c->set_port (0, inputs[DataType::AUDIO][np]);
999 c->add_channel (_("R"), DataType::AUDIO);
1000 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1002 add_bundle (c, false);
1006 /* MIDI input bundles */
1008 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1009 string n = inputs[DataType::MIDI][np];
1010 std::string pn = _engine.get_pretty_name_by_name (n);
1014 boost::erase_first (n, X_("alsa_pcm:"));
1016 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1017 c->add_channel ("", DataType::MIDI);
1018 c->set_port (0, inputs[DataType::MIDI][np]);
1019 add_bundle (c, false);
1022 /* MIDI output bundles */
1024 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1025 string n = outputs[DataType::MIDI][np];
1026 std::string pn = _engine.get_pretty_name_by_name (n);
1030 boost::erase_first (n, X_("alsa_pcm:"));
1032 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1033 c->add_channel ("", DataType::MIDI);
1034 c->set_port (0, outputs[DataType::MIDI][np]);
1035 add_bundle (c, false);
1038 // we trust the backend to only calls us if there's a change
1039 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1043 Session::auto_connect_master_bus ()
1045 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1049 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1050 // In this case it means "Multi Out" output mode
1051 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1055 /* if requested auto-connect the outputs to the first N physical ports.
1058 uint32_t limit = _master_out->n_outputs().n_total();
1059 vector<string> outputs[DataType::num_types];
1061 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1062 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1065 for (uint32_t n = 0; n < limit; ++n) {
1066 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1068 if (outputs[p->type()].size() > n) {
1069 connect_to = outputs[p->type()][n];
1072 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1073 if (_master_out->output()->connect (p, connect_to, this)) {
1074 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1083 Session::remove_monitor_section ()
1085 if (!_monitor_out || Profile->get_trx()) {
1089 /* force reversion to Solo-In-Place */
1090 Config->set_solo_control_is_listen_control (false);
1092 /* if we are auditioning, cancel it ... this is a workaround
1093 to a problem (auditioning does not execute the process graph,
1094 which is needed to remove routes when using >1 core for processing)
1099 /* Hold process lock while doing this so that we don't hear bits and
1100 * pieces of audio as we work on each route.
1103 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1105 /* Connect tracks to monitor section. Note that in an
1106 existing session, the internal sends will already exist, but we want the
1107 routes to notice that they connect to the control out specifically.
1111 boost::shared_ptr<RouteList> r = routes.reader ();
1112 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1114 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1116 if ((*x)->is_monitor()) {
1118 } else if ((*x)->is_master()) {
1121 (*x)->remove_aux_or_listen (_monitor_out);
1126 remove_route (_monitor_out);
1127 if (_state_of_the_state & Deletion) {
1131 auto_connect_master_bus ();
1134 auditioner->connect ();
1137 Config->ParameterChanged ("use-monitor-bus");
1141 Session::add_monitor_section ()
1145 if (_monitor_out || !_master_out || Profile->get_trx()) {
1149 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1155 BOOST_MARK_ROUTE(r);
1158 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1159 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1160 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1162 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1167 add_routes (rl, false, false, false);
1169 assert (_monitor_out);
1171 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1172 are undefined, at best.
1175 uint32_t limit = _monitor_out->n_inputs().n_audio();
1179 /* connect the inputs to the master bus outputs. this
1180 * represents a separate data feed from the internal sends from
1181 * each route. as of jan 2011, it allows the monitor section to
1182 * conditionally ignore either the internal sends or the normal
1183 * input feed, but we should really find a better way to do
1187 _master_out->output()->disconnect (this);
1189 for (uint32_t n = 0; n < limit; ++n) {
1190 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1191 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1194 string connect_to = o->name();
1195 if (_monitor_out->input()->connect (p, connect_to, this)) {
1196 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1204 /* if monitor section is not connected, connect it to physical outs
1207 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1209 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1211 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1214 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1216 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1217 Config->get_monitor_bus_preferred_bundle())
1223 /* Monitor bus is audio only */
1225 vector<string> outputs[DataType::num_types];
1227 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1228 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1231 uint32_t mod = outputs[DataType::AUDIO].size();
1232 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1236 for (uint32_t n = 0; n < limit; ++n) {
1238 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1240 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1241 connect_to = outputs[DataType::AUDIO][n % mod];
1244 if (!connect_to.empty()) {
1245 if (_monitor_out->output()->connect (p, connect_to, this)) {
1246 error << string_compose (
1247 _("cannot connect control output %1 to %2"),
1258 /* Hold process lock while doing this so that we don't hear bits and
1259 * pieces of audio as we work on each route.
1262 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1264 /* Connect tracks to monitor section. Note that in an
1265 existing session, the internal sends will already exist, but we want the
1266 routes to notice that they connect to the control out specifically.
1270 boost::shared_ptr<RouteList> rls = routes.reader ();
1272 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1274 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1276 if ((*x)->is_monitor()) {
1278 } else if ((*x)->is_master()) {
1281 (*x)->enable_monitor_send ();
1286 auditioner->connect ();
1288 Config->ParameterChanged ("use-monitor-bus");
1292 Session::reset_monitor_section ()
1294 /* Process lock should be held by the caller.*/
1296 if (!_monitor_out || Profile->get_trx()) {
1300 uint32_t limit = _master_out->n_outputs().n_audio();
1302 /* connect the inputs to the master bus outputs. this
1303 * represents a separate data feed from the internal sends from
1304 * each route. as of jan 2011, it allows the monitor section to
1305 * conditionally ignore either the internal sends or the normal
1306 * input feed, but we should really find a better way to do
1310 _master_out->output()->disconnect (this);
1311 _monitor_out->output()->disconnect (this);
1313 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1314 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1316 for (uint32_t n = 0; n < limit; ++n) {
1317 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1318 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1321 string connect_to = o->name();
1322 if (_monitor_out->input()->connect (p, connect_to, this)) {
1323 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1330 /* connect monitor section to physical outs
1333 if (Config->get_auto_connect_standard_busses()) {
1335 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1337 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1340 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1342 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1343 Config->get_monitor_bus_preferred_bundle())
1349 /* Monitor bus is audio only */
1351 vector<string> outputs[DataType::num_types];
1353 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1354 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1357 uint32_t mod = outputs[DataType::AUDIO].size();
1358 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1362 for (uint32_t n = 0; n < limit; ++n) {
1364 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1366 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1367 connect_to = outputs[DataType::AUDIO][n % mod];
1370 if (!connect_to.empty()) {
1371 if (_monitor_out->output()->connect (p, connect_to, this)) {
1372 error << string_compose (
1373 _("cannot connect control output %1 to %2"),
1384 /* Connect tracks to monitor section. Note that in an
1385 existing session, the internal sends will already exist, but we want the
1386 routes to notice that they connect to the control out specifically.
1390 boost::shared_ptr<RouteList> rls = routes.reader ();
1392 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1394 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1396 if ((*x)->is_monitor()) {
1398 } else if ((*x)->is_master()) {
1401 (*x)->enable_monitor_send ();
1407 Session::hookup_io ()
1409 /* stop graph reordering notifications from
1410 causing resorts, etc.
1413 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1417 /* we delay creating the auditioner till now because
1418 it makes its own connections to ports.
1422 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1424 throw failed_constructor ();
1426 a->use_new_diskstream ();
1430 catch (failed_constructor& err) {
1431 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1435 /* load bundles, which we may have postponed earlier on */
1436 if (_bundle_xml_node) {
1437 load_bundles (*_bundle_xml_node);
1438 delete _bundle_xml_node;
1441 /* Tell all IO objects to connect themselves together */
1443 IO::enable_connecting ();
1445 /* Now tell all "floating" ports to connect to whatever
1446 they should be connected to.
1449 AudioEngine::instance()->reconnect_ports ();
1451 /* Anyone who cares about input state, wake up and do something */
1453 IOConnectionsComplete (); /* EMIT SIGNAL */
1455 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1457 /* now handle the whole enchilada as if it was one
1458 graph reorder event.
1463 /* update the full solo state, which can't be
1464 correctly determined on a per-route basis, but
1465 needs the global overview that only the session
1469 update_route_solo_state ();
1473 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1475 boost::shared_ptr<Track> track = wp.lock ();
1480 boost::shared_ptr<Playlist> playlist;
1482 if ((playlist = track->playlist()) != 0) {
1483 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1484 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1485 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1490 Session::record_enabling_legal () const
1492 /* this used to be in here, but survey says.... we don't need to restrict it */
1493 // if (record_status() == Recording) {
1497 if (Config->get_all_safe()) {
1504 Session::set_track_monitor_input_status (bool yn)
1506 boost::shared_ptr<RouteList> rl = routes.reader ();
1507 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1508 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1509 if (tr && tr->record_enabled ()) {
1510 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1511 tr->request_input_monitoring (yn);
1517 Session::auto_punch_start_changed (Location* location)
1519 replace_event (SessionEvent::PunchIn, location->start());
1521 if (get_record_enabled() && config.get_punch_in()) {
1522 /* capture start has been changed, so save new pending state */
1523 save_state ("", true);
1528 Session::auto_punch_end_changed (Location* location)
1530 framepos_t when_to_stop = location->end();
1531 // when_to_stop += _worst_output_latency + _worst_input_latency;
1532 replace_event (SessionEvent::PunchOut, when_to_stop);
1536 Session::auto_punch_changed (Location* location)
1538 framepos_t when_to_stop = location->end();
1540 replace_event (SessionEvent::PunchIn, location->start());
1541 //when_to_stop += _worst_output_latency + _worst_input_latency;
1542 replace_event (SessionEvent::PunchOut, when_to_stop);
1545 /** @param loc A loop location.
1546 * @param pos Filled in with the start time of the required fade-out (in session frames).
1547 * @param length Filled in with the length of the required fade-out.
1550 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1552 pos = max (loc->start(), loc->end() - 64);
1553 length = loc->end() - pos;
1557 Session::auto_loop_changed (Location* location)
1559 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1562 auto_loop_declick_range (location, dcp, dcl);
1564 if (transport_rolling() && play_loop) {
1566 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1568 // if (_transport_frame > location->end()) {
1570 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1571 // relocate to beginning of loop
1572 clear_events (SessionEvent::LocateRoll);
1574 request_locate (location->start(), true);
1577 else if (Config->get_seamless_loop() && !loop_changing) {
1579 // schedule a locate-roll to refill the diskstreams at the
1580 // previous loop end
1581 loop_changing = true;
1583 if (location->end() > last_loopend) {
1584 clear_events (SessionEvent::LocateRoll);
1585 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1591 clear_events (SessionEvent::AutoLoopDeclick);
1592 clear_events (SessionEvent::AutoLoop);
1595 /* possibly move playhead if not rolling; if we are rolling we'll move
1596 to the loop start on stop if that is appropriate.
1601 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1602 if (pos == location->start()) {
1603 request_locate (pos);
1608 last_loopend = location->end();
1613 Session::set_auto_punch_location (Location* location)
1617 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1618 punch_connections.drop_connections();
1619 existing->set_auto_punch (false, this);
1620 remove_event (existing->start(), SessionEvent::PunchIn);
1621 clear_events (SessionEvent::PunchOut);
1622 auto_punch_location_changed (0);
1627 if (location == 0) {
1631 if (location->end() <= location->start()) {
1632 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1636 punch_connections.drop_connections ();
1638 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1639 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1640 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1642 location->set_auto_punch (true, this);
1644 auto_punch_changed (location);
1646 auto_punch_location_changed (location);
1650 Session::set_session_extents (framepos_t start, framepos_t end)
1653 if ((existing = _locations->session_range_location()) == 0) {
1654 //if there is no existing session, we need to make a new session location (should never happen)
1655 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1659 error << _("Session: you can't use that location for session start/end)") << endmsg;
1663 existing->set( start, end );
1669 Session::set_auto_loop_location (Location* location)
1673 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1674 loop_connections.drop_connections ();
1675 existing->set_auto_loop (false, this);
1676 remove_event (existing->end(), SessionEvent::AutoLoop);
1679 auto_loop_declick_range (existing, dcp, dcl);
1680 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1681 auto_loop_location_changed (0);
1686 if (location == 0) {
1690 if (location->end() <= location->start()) {
1691 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1695 last_loopend = location->end();
1697 loop_connections.drop_connections ();
1699 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1700 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1701 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1702 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1704 location->set_auto_loop (true, this);
1706 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1707 // set all tracks to use internal looping
1708 boost::shared_ptr<RouteList> rl = routes.reader ();
1709 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1710 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1711 if (tr && !tr->hidden()) {
1712 tr->set_loop (location);
1717 /* take care of our stuff first */
1719 auto_loop_changed (location);
1721 /* now tell everyone else */
1723 auto_loop_location_changed (location);
1727 Session::update_marks (Location*)
1733 Session::update_skips (Location* loc, bool consolidate)
1735 if (_ignore_skips_updates) {
1739 Locations::LocationList skips;
1742 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1743 consolidate_skips (loc);
1746 sync_locations_to_skips ();
1752 Session::consolidate_skips (Location* loc)
1754 Locations::LocationList all_locations = _locations->list ();
1756 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1758 if (!(*l)->is_skip ()) {
1763 /* don't test against self */
1770 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1771 case Evoral::OverlapInternal:
1772 case Evoral::OverlapExternal:
1773 case Evoral::OverlapStart:
1774 case Evoral::OverlapEnd:
1775 /* adjust new location to cover existing one */
1776 loc->set_start (min (loc->start(), (*l)->start()));
1777 loc->set_end (max (loc->end(), (*l)->end()));
1778 /* we don't need this one any more */
1779 _locations->remove (*l);
1780 /* the location has been deleted, so remove reference to it in our local list */
1781 l = all_locations.erase (l);
1784 case Evoral::OverlapNone:
1792 Session::sync_locations_to_skips ()
1794 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1795 * Session::_sync_locations_to_skips() from the audioengine thread.
1797 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1801 Session::_sync_locations_to_skips ()
1803 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1805 Locations::LocationList const & locs (_locations->list());
1807 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1809 Location* location = *i;
1811 if (location->is_skip() && location->is_skipping()) {
1812 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1820 Session::location_added (Location *location)
1822 if (location->is_auto_punch()) {
1823 set_auto_punch_location (location);
1826 if (location->is_auto_loop()) {
1827 set_auto_loop_location (location);
1830 if (location->is_session_range()) {
1831 /* no need for any signal handling or event setting with the session range,
1832 because we keep a direct reference to it and use its start/end directly.
1834 _session_range_location = location;
1837 if (location->is_mark()) {
1838 /* listen for per-location signals that require us to do any * global updates for marks */
1840 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1841 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1842 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1843 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1846 if (location->is_skip()) {
1847 /* listen for per-location signals that require us to update skip-locate events */
1849 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1850 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1851 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1852 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1854 update_skips (location, true);
1861 Session::location_removed (Location *location)
1863 if (location->is_auto_loop()) {
1864 set_auto_loop_location (0);
1865 set_track_loop (false);
1868 if (location->is_auto_punch()) {
1869 set_auto_punch_location (0);
1872 if (location->is_session_range()) {
1873 /* this is never supposed to happen */
1874 error << _("programming error: session range removed!") << endl;
1877 if (location->is_skip()) {
1879 update_skips (location, false);
1886 Session::locations_changed ()
1888 _locations->apply (*this, &Session::_locations_changed);
1892 Session::_locations_changed (const Locations::LocationList& locations)
1894 /* There was some mass-change in the Locations object.
1896 We might be re-adding a location here but it doesn't actually matter
1897 for all the locations that the Session takes an interest in.
1901 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1902 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1903 location_added (*i);
1907 update_skips (NULL, false);
1911 Session::enable_record ()
1913 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1914 /* no recording at anything except normal speed */
1919 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1921 if (rs == Recording) {
1925 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1927 _last_record_location = _transport_frame;
1928 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1930 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1931 set_track_monitor_input_status (true);
1934 RecordStateChanged ();
1941 Session::set_all_tracks_record_enabled (bool enable )
1943 boost::shared_ptr<RouteList> rl = routes.reader();
1944 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1945 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1947 tr->set_record_enabled (enable, Controllable::NoGroup);
1954 Session::disable_record (bool rt_context, bool force)
1958 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1960 if (!Config->get_latched_record_enable () || force) {
1961 g_atomic_int_set (&_record_status, Disabled);
1962 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1964 if (rs == Recording) {
1965 g_atomic_int_set (&_record_status, Enabled);
1969 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1970 set_track_monitor_input_status (false);
1973 RecordStateChanged (); /* emit signal */
1976 remove_pending_capture_state ();
1982 Session::step_back_from_record ()
1984 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1986 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1987 set_track_monitor_input_status (false);
1990 RecordStateChanged (); /* emit signal */
1995 Session::maybe_enable_record ()
1997 if (_step_editors > 0) {
2001 g_atomic_int_set (&_record_status, Enabled);
2003 /* This function is currently called from somewhere other than an RT thread.
2004 This save_state() call therefore doesn't impact anything. Doing it here
2005 means that we save pending state of which sources the next record will use,
2006 which gives us some chance of recovering from a crash during the record.
2009 save_state ("", true);
2011 if (_transport_speed) {
2012 if (!config.get_punch_in()) {
2016 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2017 RecordStateChanged (); /* EMIT SIGNAL */
2024 Session::audible_frame () const
2030 offset = worst_playback_latency ();
2032 if (synced_to_engine()) {
2033 /* Note: this is basically just sync-to-JACK */
2034 tf = _engine.transport_frame();
2036 tf = _transport_frame;
2041 if (!non_realtime_work_pending()) {
2045 /* Check to see if we have passed the first guaranteed
2046 audible frame past our last start position. if not,
2047 return that last start point because in terms
2048 of audible frames, we have not moved yet.
2050 `Start position' in this context means the time we last
2051 either started, located, or changed transport direction.
2054 if (_transport_speed > 0.0f) {
2056 if (!play_loop || !have_looped) {
2057 if (tf < _last_roll_or_reversal_location + offset) {
2058 return _last_roll_or_reversal_location;
2066 } else if (_transport_speed < 0.0f) {
2068 /* XXX wot? no backward looping? */
2070 if (tf > _last_roll_or_reversal_location - offset) {
2071 return _last_roll_or_reversal_location;
2083 Session::set_frame_rate (framecnt_t frames_per_second)
2085 /** \fn void Session::set_frame_size(framecnt_t)
2086 the AudioEngine object that calls this guarantees
2087 that it will not be called while we are also in
2088 ::process(). Its fine to do things that block
2092 if (_base_frame_rate == 0) {
2093 _base_frame_rate = frames_per_second;
2095 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2096 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2098 _nominal_frame_rate = frames_per_second;
2103 reset_write_sources (false);
2105 // XXX we need some equivalent to this, somehow
2106 // SndFileSource::setup_standard_crossfades (frames_per_second);
2110 /* XXX need to reset/reinstantiate all LADSPA plugins */
2114 Session::set_block_size (pframes_t nframes)
2116 /* the AudioEngine guarantees
2117 that it will not be called while we are also in
2118 ::process(). It is therefore fine to do things that block
2123 current_block_size = nframes;
2127 boost::shared_ptr<RouteList> r = routes.reader ();
2129 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2130 (*i)->set_block_size (nframes);
2133 boost::shared_ptr<RouteList> rl = routes.reader ();
2134 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2135 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2137 tr->set_block_size (nframes);
2141 set_worst_io_latencies ();
2147 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2149 boost::shared_ptr<Route> r2;
2151 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2152 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2156 /* make a copy of the existing list of routes that feed r1 */
2158 Route::FedBy existing (r1->fed_by());
2160 /* for each route that feeds r1, recurse, marking it as feeding
2164 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2165 if (!(r2 = i->r.lock ())) {
2166 /* (*i) went away, ignore it */
2170 /* r2 is a route that feeds r1 which somehow feeds base. mark
2171 base as being fed by r2
2174 rbase->add_fed_by (r2, i->sends_only);
2178 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2182 if (r1->feeds (r2) && r2->feeds (r1)) {
2186 /* now recurse, so that we can mark base as being fed by
2187 all routes that feed r2
2190 trace_terminal (r2, rbase);
2197 Session::resort_routes ()
2199 /* don't do anything here with signals emitted
2200 by Routes during initial setup or while we
2201 are being destroyed.
2204 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2208 if (_route_deletion_in_progress) {
2213 RCUWriter<RouteList> writer (routes);
2214 boost::shared_ptr<RouteList> r = writer.get_copy ();
2215 resort_routes_using (r);
2216 /* writer goes out of scope and forces update */
2220 if (DEBUG_ENABLED(DEBUG::Graph)) {
2221 boost::shared_ptr<RouteList> rl = routes.reader ();
2222 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2223 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2225 const Route::FedBy& fb ((*i)->fed_by());
2227 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2228 boost::shared_ptr<Route> sf = f->r.lock();
2230 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2239 /** This is called whenever we need to rebuild the graph of how we will process
2241 * @param r List of routes, in any order.
2245 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2247 /* We are going to build a directed graph of our routes;
2248 this is where the edges of that graph are put.
2253 /* Go through all routes doing two things:
2255 * 1. Collect the edges of the route graph. Each of these edges
2256 * is a pair of routes, one of which directly feeds the other
2257 * either by a JACK connection or by an internal send.
2259 * 2. Begin the process of making routes aware of which other
2260 * routes directly or indirectly feed them. This information
2261 * is used by the solo code.
2264 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2266 /* Clear out the route's list of direct or indirect feeds */
2267 (*i)->clear_fed_by ();
2269 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2271 bool via_sends_only;
2273 /* See if this *j feeds *i according to the current state of the JACK
2274 connections and internal sends.
2276 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2277 /* add the edge to the graph (part #1) */
2278 edges.add (*j, *i, via_sends_only);
2279 /* tell the route (for part #2) */
2280 (*i)->add_fed_by (*j, via_sends_only);
2285 /* Attempt a topological sort of the route graph */
2286 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2288 if (sorted_routes) {
2289 /* We got a satisfactory topological sort, so there is no feedback;
2292 Note: the process graph rechain does not require a
2293 topologically-sorted list, but hey ho.
2295 if (_process_graph) {
2296 _process_graph->rechain (sorted_routes, edges);
2299 _current_route_graph = edges;
2301 /* Complete the building of the routes' lists of what directly
2302 or indirectly feeds them.
2304 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2305 trace_terminal (*i, *i);
2308 *r = *sorted_routes;
2311 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2312 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2313 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2314 (*i)->name(), (*i)->order_key ()));
2318 SuccessfulGraphSort (); /* EMIT SIGNAL */
2321 /* The topological sort failed, so we have a problem. Tell everyone
2322 and stick to the old graph; this will continue to be processed, so
2323 until the feedback is fixed, what is played back will not quite
2324 reflect what is actually connected. Note also that we do not
2325 do trace_terminal here, as it would fail due to an endless recursion,
2326 so the solo code will think that everything is still connected
2330 FeedbackDetected (); /* EMIT SIGNAL */
2335 /** Find a route name starting with \a base, maybe followed by the
2336 * lowest \a id. \a id will always be added if \a definitely_add_number
2337 * is true on entry; otherwise it will only be added if required
2338 * to make the name unique.
2340 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2341 * The available route name with the lowest ID will be used, and \a id
2342 * will be set to the ID.
2344 * \return false if a route name could not be found, and \a track_name
2345 * and \a id do not reflect a free route name.
2348 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2350 /* the base may conflict with ports that do not belong to existing
2351 routes, but hidden objects like the click track. So check port names
2352 before anything else.
2355 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2356 if (base == *reserved) {
2357 /* Check if this reserved name already exists, and if
2358 so, disallow it without a numeric suffix.
2360 if (route_by_name (*reserved)) {
2361 definitely_add_number = true;
2370 if (!definitely_add_number && route_by_name (base) == 0) {
2371 /* juse use the base */
2377 name = string_compose ("%1 %2", base, id);
2379 if (route_by_name (name) == 0) {
2385 } while (id < (UINT_MAX-1));
2390 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2392 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2394 in = ChanCount::ZERO;
2395 out = ChanCount::ZERO;
2397 boost::shared_ptr<RouteList> r = routes.reader ();
2399 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2400 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2401 if (tr && !tr->is_auditioner()) {
2402 in += tr->n_inputs();
2403 out += tr->n_outputs();
2409 Session::default_track_name_pattern (DataType t)
2412 case DataType::AUDIO:
2413 if (Profile->get_trx()) {
2420 case DataType::MIDI:
2427 /** Caller must not hold process lock
2428 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2429 * @param instrument plugin info for the instrument to insert pre-fader, if any
2431 list<boost::shared_ptr<MidiTrack> >
2432 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2433 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template, Plugin::PresetRecord* pset)
2436 uint32_t track_id = 0;
2438 RouteList new_routes;
2439 list<boost::shared_ptr<MidiTrack> > ret;
2441 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2442 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2445 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2446 error << "cannot find name for new midi track" << endmsg;
2450 boost::shared_ptr<MidiTrack> track;
2453 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2455 if (track->init ()) {
2459 if (Profile->get_mixbus ()) {
2460 track->set_strict_io (true);
2463 track->use_new_diskstream();
2465 BOOST_MARK_TRACK (track);
2468 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2469 if (track->input()->ensure_io (input, false, this)) {
2470 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2474 if (track->output()->ensure_io (output, false, this)) {
2475 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2480 track->non_realtime_input_change();
2483 route_group->add (track);
2486 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2488 if (Config->get_remote_model() == UserOrdered) {
2489 track->set_remote_control_id (next_control_id());
2492 new_routes.push_back (track);
2493 ret.push_back (track);
2495 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
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);
2518 add_routes (new_routes, true, true, false);
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)
2541 uint32_t bus_id = 0;
2545 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2548 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2549 error << "cannot find name for new midi bus" << endmsg;
2554 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2560 if (Profile->get_mixbus ()) {
2561 bus->set_strict_io (true);
2564 BOOST_MARK_ROUTE(bus);
2567 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2569 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2570 error << _("cannot configure new midi bus input") << endmsg;
2575 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2576 error << _("cannot configure new midi bus output") << endmsg;
2582 route_group->add (bus);
2584 if (Config->get_remote_model() == UserOrdered) {
2585 bus->set_remote_control_id (next_control_id());
2588 ret.push_back (bus);
2589 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2593 catch (failed_constructor &err) {
2594 error << _("Session: could not create new audio route.") << endmsg;
2598 catch (AudioEngine::PortRegistrationFailure& pfe) {
2599 error << pfe.what() << endmsg;
2609 StateProtector sp (this);
2610 add_routes (ret, false, false, false);
2613 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2614 PluginPtr plugin = instrument->load (*this);
2616 plugin->load_preset (*pset);
2618 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2619 (*r)->add_processor (p, PreFader);
2630 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2632 boost::shared_ptr<Route> midi_track (wmt.lock());
2638 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2640 if (change.after.n_audio() <= change.before.n_audio()) {
2644 /* new audio ports: make sure the audio goes somewhere useful,
2645 * unless the user has no-auto-connect selected.
2647 * The existing ChanCounts don't matter for this call as they are only
2648 * to do with matching input and output indices, and we are only changing
2651 auto_connect_route (midi_track, false, ChanCount(), change.before);
2655 #ifdef USE_TRACKS_CODE_FEATURES
2658 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2660 return route1->remote_control_id() < route2->remote_control_id();
2664 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2666 // it is not allowed to perform connection
2667 if (!IO::connecting_legal) {
2671 // if we are deleting routes we will call this once at the end
2672 if (_route_deletion_in_progress) {
2676 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2682 // We need to disconnect the route's inputs and outputs first
2683 // basing on autoconnect configuration
2684 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2685 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2687 ChanCount existing_inputs;
2688 ChanCount existing_outputs;
2689 count_existing_track_channels (existing_inputs, existing_outputs);
2691 //ChanCount inputs = ChanCount::ZERO;
2692 //ChanCount outputs = ChanCount::ZERO;
2694 RouteList existing_routes = *routes.reader ();
2695 existing_routes.sort (compare_routes_by_remote_id);
2698 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2700 vector<string> physinputs;
2701 vector<string> physoutputs;
2703 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2704 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2706 uint32_t input_n = 0;
2707 uint32_t output_n = 0;
2708 RouteList::iterator rIter = existing_routes.begin();
2709 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2710 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2711 for (; rIter != existing_routes.end(); ++rIter) {
2712 if (*rIter == _master_out || *rIter == _monitor_out ) {
2716 if (current_output_auto_connection == AutoConnectPhysical) {
2717 (*rIter)->amp()->deactivate();
2718 } else if (current_output_auto_connection == AutoConnectMaster) {
2719 (*rIter)->amp()->activate();
2722 if (reconnectIputs) {
2723 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2725 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2727 if (current_input_auto_connection & AutoConnectPhysical) {
2729 if ( input_n == physinputs.size() ) {
2733 string port = physinputs[input_n];
2735 if (port.empty() ) {
2736 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2739 //GZ: check this; could be heavy
2740 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2746 if (reconnectOutputs) {
2748 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2749 if (current_output_auto_connection & AutoConnectPhysical) {
2751 //GZ: check this; could be heavy
2752 (*rIter)->output()->disconnect (this);
2753 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2755 //GZ: check this; could be heavy
2756 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2758 } else if (current_output_auto_connection & AutoConnectMaster){
2760 if (!reconnect_master) {
2764 //GZ: check this; could be heavy
2765 (*rIter)->output()->disconnect (this);
2768 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2769 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2771 error << error << "Master bus is not available" << endmsg;
2776 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2777 if (current_output_auto_connection & AutoConnectPhysical) {
2779 if ( output_n == physoutputs.size() ) {
2783 string port = physoutputs[output_n];
2785 if (port.empty() ) {
2786 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2789 //GZ: check this; could be heavy
2790 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2793 } else if (current_output_auto_connection & AutoConnectMaster) {
2795 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2799 // connect to master bus
2800 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2802 if (port.empty() ) {
2803 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2807 //GZ: check this; could be heavy
2808 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2815 _master_out->output()->disconnect (this);
2816 auto_connect_master_bus ();
2821 session_routes_reconnected (); /* EMIT SIGNAL */
2825 Session::reconnect_midi_scene_ports(bool inputs)
2829 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2831 scene_in_ptr->disconnect_all ();
2833 std::vector<EngineStateController::MidiPortState> midi_port_states;
2834 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2836 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2838 for (; state_iter != midi_port_states.end(); ++state_iter) {
2839 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2840 scene_in_ptr->connect (state_iter->name);
2847 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2849 if (scene_out_ptr ) {
2850 scene_out_ptr->disconnect_all ();
2852 std::vector<EngineStateController::MidiPortState> midi_port_states;
2853 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2855 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2857 for (; state_iter != midi_port_states.end(); ++state_iter) {
2858 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2859 scene_out_ptr->connect (state_iter->name);
2867 Session::reconnect_mtc_ports ()
2869 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2875 mtc_in_ptr->disconnect_all ();
2877 std::vector<EngineStateController::MidiPortState> midi_port_states;
2878 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2880 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2882 for (; state_iter != midi_port_states.end(); ++state_iter) {
2883 if (state_iter->available && state_iter->mtc_in) {
2884 mtc_in_ptr->connect (state_iter->name);
2888 if (!_midi_ports->mtc_input_port ()->connected () &&
2889 config.get_external_sync () &&
2890 (Config->get_sync_source () == MTC) ) {
2891 config.set_external_sync (false);
2894 if ( ARDOUR::Profile->get_trx () ) {
2895 // Tracks need this signal to update timecode_source_dropdown
2896 MtcOrLtcInputPortChanged (); //emit signal
2901 Session::reconnect_mmc_ports(bool inputs)
2903 if (inputs ) { // get all enabled midi input ports
2905 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2907 mmc_in_ptr->disconnect_all ();
2908 std::vector<std::string> enabled_midi_inputs;
2909 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2911 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2913 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2914 mmc_in_ptr->connect (*port_iter);
2918 } else { // get all enabled midi output ports
2920 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2922 mmc_out_ptr->disconnect_all ();
2923 std::vector<std::string> enabled_midi_outputs;
2924 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2926 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2928 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2929 mmc_out_ptr->connect (*port_iter);
2937 /** Caller must not hold process lock
2938 * @param name_template string to use for the start of the name, or "" to use "Audio".
2940 list< boost::shared_ptr<AudioTrack> >
2941 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2942 uint32_t how_many, string name_template)
2945 uint32_t track_id = 0;
2947 RouteList new_routes;
2948 list<boost::shared_ptr<AudioTrack> > ret;
2950 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2951 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2955 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2956 error << "cannot find name for new audio track" << endmsg;
2960 boost::shared_ptr<AudioTrack> track;
2963 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2965 if (track->init ()) {
2969 if (Profile->get_mixbus ()) {
2970 track->set_strict_io (true);
2974 if (ARDOUR::Profile->get_trx ()) {
2975 // TRACKS considers it's not a USE CASE, it's
2976 // a piece of behavior of the session model:
2978 // Gain for a newly created route depends on
2979 // the current output_auto_connect mode:
2981 // 0 for Stereo Out mode
2983 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2984 track->set_gain (dB_to_coefficient (0), Controllable::NoGroup);
2988 track->use_new_diskstream();
2990 BOOST_MARK_TRACK (track);
2993 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2995 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2996 error << string_compose (
2997 _("cannot configure %1 in/%2 out configuration for new audio track"),
2998 input_channels, output_channels)
3003 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3004 error << string_compose (
3005 _("cannot configure %1 in/%2 out configuration for new audio track"),
3006 input_channels, output_channels)
3013 route_group->add (track);
3016 track->non_realtime_input_change();
3018 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3019 if (Config->get_remote_model() == UserOrdered) {
3020 track->set_remote_control_id (next_control_id());
3023 new_routes.push_back (track);
3024 ret.push_back (track);
3026 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3029 catch (failed_constructor &err) {
3030 error << _("Session: could not create new audio track.") << endmsg;
3034 catch (AudioEngine::PortRegistrationFailure& pfe) {
3036 error << pfe.what() << endmsg;
3044 if (!new_routes.empty()) {
3045 StateProtector sp (this);
3046 if (Profile->get_trx()) {
3047 add_routes (new_routes, false, false, false);
3049 add_routes (new_routes, true, true, false);
3056 /** Caller must not hold process lock.
3057 * @param name_template string to use for the start of the name, or "" to use "Bus".
3060 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
3063 uint32_t bus_id = 0;
3067 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3070 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3071 error << "cannot find name for new audio bus" << endmsg;
3076 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3082 if (Profile->get_mixbus ()) {
3083 bus->set_strict_io (true);
3086 BOOST_MARK_ROUTE(bus);
3089 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3091 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3092 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3093 input_channels, output_channels)
3099 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3100 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3101 input_channels, output_channels)
3108 route_group->add (bus);
3110 if (Config->get_remote_model() == UserOrdered) {
3111 bus->set_remote_control_id (next_control_id());
3114 bus->add_internal_return ();
3116 ret.push_back (bus);
3118 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3124 catch (failed_constructor &err) {
3125 error << _("Session: could not create new audio route.") << endmsg;
3129 catch (AudioEngine::PortRegistrationFailure& pfe) {
3130 error << pfe.what() << endmsg;
3140 StateProtector sp (this);
3141 if (Profile->get_trx()) {
3142 add_routes (ret, false, false, false);
3144 add_routes (ret, false, true, true); // autoconnect // outputs only
3153 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3157 if (!tree.read (template_path.c_str())) {
3161 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3165 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3168 uint32_t control_id;
3169 uint32_t number = 0;
3170 const uint32_t being_added = how_many;
3171 /* This will prevent the use of any existing XML-provided PBD::ID
3174 Stateful::ForceIDRegeneration force_ids;
3175 IO::disable_connecting ();
3177 control_id = next_control_id ();
3181 /* We're going to modify the node contents a bit so take a
3182 * copy. The node may be re-used when duplicating more than once.
3185 XMLNode node_copy (node);
3190 if (!name_base.empty()) {
3192 /* if we're adding more than one routes, force
3193 * all the names of the new routes to be
3194 * numbered, via the final parameter.
3197 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3198 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3204 string const route_name = node_copy.property(X_("name"))->value ();
3206 /* generate a new name by adding a number to the end of the template name */
3207 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3208 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3209 abort(); /*NOTREACHED*/
3213 /* set this name in the XML description that we are about to use */
3215 bool rename_playlist;
3218 rename_playlist = true;
3223 rename_playlist = false;
3226 Route::set_name_in_state (node_copy, name, rename_playlist);
3228 /* trim bitslots from listen sends so that new ones are used */
3229 XMLNodeList children = node_copy.children ();
3230 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3231 if ((*i)->name() == X_("Processor")) {
3232 /* ForceIDRegeneration does not catch the following */
3233 XMLProperty const * role = (*i)->property (X_("role"));
3234 XMLProperty const * type = (*i)->property (X_("type"));
3235 if (role && role->value() == X_("Aux")) {
3236 /* check if the target bus exists.
3237 * we should not save aux-sends in templates.
3239 XMLProperty const * target = (*i)->property (X_("target"));
3241 (*i)->add_property ("type", "dangling-aux-send");
3244 boost::shared_ptr<Route> r = route_by_id (target->value());
3245 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3246 (*i)->add_property ("type", "dangling-aux-send");
3250 if (role && role->value() == X_("Listen")) {
3251 (*i)->remove_property (X_("bitslot"));
3253 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3255 Delivery::Role xrole;
3256 uint32_t bitslot = 0;
3257 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3258 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3259 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3260 (*i)->remove_property (X_("bitslot"));
3261 (*i)->remove_property (X_("name"));
3262 (*i)->add_property ("bitslot", buf);
3263 (*i)->add_property ("name", name);
3265 else if (type && type->value() == X_("return")) {
3266 // Return::set_state() generates a new one
3267 (*i)->remove_property (X_("bitslot"));
3269 else if (type && type->value() == X_("port")) {
3270 // PortInsert::set_state() handles the bitslot
3271 (*i)->remove_property (X_("bitslot"));
3272 (*i)->add_property ("ignore-name", "1");
3277 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3280 error << _("Session: cannot create track/bus from template description") << endmsg;
3284 if (boost::dynamic_pointer_cast<Track>(route)) {
3285 /* force input/output change signals so that the new diskstream
3286 picks up the configuration of the route. During session
3287 loading this normally happens in a different way.
3290 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3292 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3293 change.after = route->input()->n_ports();
3294 route->input()->changed (change, this);
3295 change.after = route->output()->n_ports();
3296 route->output()->changed (change, this);
3299 route->set_remote_control_id (control_id);
3302 boost::shared_ptr<Track> track;
3304 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3307 track->use_new_playlist ();
3310 track->use_copy_playlist ();
3317 ret.push_back (route);
3319 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3322 catch (failed_constructor &err) {
3323 error << _("Session: could not create new route from template") << endmsg;
3327 catch (AudioEngine::PortRegistrationFailure& pfe) {
3328 error << pfe.what() << endmsg;
3337 StateProtector sp (this);
3338 if (Profile->get_trx()) {
3339 add_routes (ret, false, false, false);
3341 add_routes (ret, true, true, false);
3343 IO::enable_connecting ();
3350 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3353 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3354 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3357 error << _("Adding new tracks/busses failed") << endmsg;
3362 update_latency (true);
3363 update_latency (false);
3368 save_state (_current_snapshot_name);
3371 reassign_track_numbers();
3373 update_route_record_state ();
3375 RouteAdded (new_routes); /* EMIT SIGNAL */
3379 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3381 ChanCount existing_inputs;
3382 ChanCount existing_outputs;
3383 uint32_t order = next_control_id();
3386 if (_order_hint > -1) {
3387 order = _order_hint;
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());
3398 /* if there is no control out and we're not in the middle of loading,
3399 * resort the graph here. if there is a control out, we will resort
3400 * toward the end of this method. if we are in the middle of loading,
3401 * we will resort when done.
3404 if (!_monitor_out && IO::connecting_legal) {
3405 resort_routes_using (r);
3409 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3411 boost::weak_ptr<Route> wpr (*x);
3412 boost::shared_ptr<Route> r (*x);
3414 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3415 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3416 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3418 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3419 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3421 if (r->is_master()) {
3425 if (r->is_monitor()) {
3429 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3431 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3432 track_playlist_changed (boost::weak_ptr<Track> (tr));
3433 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3435 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3437 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3438 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3442 if (input_auto_connect || output_auto_connect) {
3443 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3444 existing_inputs += r->n_inputs();
3445 existing_outputs += r->n_outputs();
3448 /* order keys are a GUI responsibility but we need to set up
3449 reasonable defaults because they also affect the remote control
3450 ID in most situations.
3453 if (!r->has_order_key ()) {
3454 if (r->is_auditioner()) {
3455 /* use an arbitrarily high value */
3456 r->set_order_key (UINT_MAX);
3458 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3459 r->set_order_key (order);
3467 if (_monitor_out && IO::connecting_legal) {
3468 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3470 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3471 if ((*x)->is_monitor()) {
3473 } else if ((*x)->is_master()) {
3476 (*x)->enable_monitor_send ();
3483 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3485 boost::shared_ptr<RouteList> r = routes.reader ();
3486 boost::shared_ptr<Send> s;
3488 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3489 if ((s = (*i)->internal_send_for (dest)) != 0) {
3490 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3496 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3498 boost::shared_ptr<RouteList> r = routes.reader ();
3499 boost::shared_ptr<Send> s;
3501 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3502 if ((s = (*i)->internal_send_for (dest)) != 0) {
3503 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3509 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3511 boost::shared_ptr<RouteList> r = routes.reader ();
3512 boost::shared_ptr<Send> s;
3514 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3515 if ((s = (*i)->internal_send_for (dest)) != 0) {
3516 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3521 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3523 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3525 boost::shared_ptr<RouteList> r = routes.reader ();
3526 boost::shared_ptr<RouteList> t (new RouteList);
3528 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3529 /* no MIDI sends because there are no MIDI busses yet */
3530 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3535 add_internal_sends (dest, p, t);
3539 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3541 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3542 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3547 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3549 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3553 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3555 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3559 if (!dest->internal_return()) {
3560 dest->add_internal_return ();
3563 sender->add_aux_send (dest, before);
3569 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3571 { // RCU Writer scope
3572 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3573 RCUWriter<RouteList> writer (routes);
3574 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3577 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3579 if (*iter == _master_out) {
3583 (*iter)->set_solo (false, Controllable::NoGroup);
3587 /* deleting the master out seems like a dumb
3588 idea, but its more of a UI policy issue
3592 if (*iter == _master_out) {
3593 _master_out = boost::shared_ptr<Route> ();
3596 if (*iter == _monitor_out) {
3597 _monitor_out.reset ();
3600 // We need to disconnect the route's inputs and outputs
3602 (*iter)->input()->disconnect (0);
3603 (*iter)->output()->disconnect (0);
3605 /* if the route had internal sends sending to it, remove them */
3606 if ((*iter)->internal_return()) {
3608 boost::shared_ptr<RouteList> r = routes.reader ();
3609 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3610 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3612 (*i)->remove_processor (s);
3617 /* if the monitoring section had a pointer to this route, remove it */
3618 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3619 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3620 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3621 (*iter)->remove_aux_or_listen (_monitor_out);
3624 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3625 if (mt && mt->step_editing()) {
3626 if (_step_editors > 0) {
3632 /* writer goes out of scope, forces route list update */
3634 } // end of RCU Writer scope
3636 update_route_solo_state ();
3637 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3638 update_latency_compensation ();
3641 /* Re-sort routes to remove the graph's current references to the one that is
3642 * going away, then flush old references out of the graph.
3643 * Wave Tracks: reconnect routes
3646 #ifdef USE_TRACKS_CODE_FEATURES
3647 reconnect_existing_routes(true, false);
3649 routes.flush (); // maybe unsafe, see below.
3653 if (_process_graph && !(_state_of_the_state & Deletion)) {
3654 _process_graph->clear_other_chain ();
3657 /* get rid of it from the dead wood collection in the route list manager */
3658 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3662 /* try to cause everyone to drop their references
3663 * and unregister ports from the backend
3666 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3667 (*iter)->drop_references ();
3670 if (_state_of_the_state & Deletion) {
3674 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3676 /* save the new state of the world */
3678 if (save_state (_current_snapshot_name)) {
3679 save_history (_current_snapshot_name);
3682 reassign_track_numbers();
3683 update_route_record_state ();
3687 Session::remove_route (boost::shared_ptr<Route> route)
3689 boost::shared_ptr<RouteList> rl (new RouteList);
3690 rl->push_back (route);
3695 Session::route_mute_changed ()
3701 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3703 boost::shared_ptr<Route> route (wpr.lock());
3709 if (route->listening_via_monitor ()) {
3711 if (Config->get_exclusive_solo()) {
3713 RouteGroup* rg = route->route_group ();
3714 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3716 boost::shared_ptr<RouteList> r = routes.reader ();
3718 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3719 if ((*i) == route) {
3720 /* already changed */
3724 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3725 /* route does not get solo propagated to it */
3729 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3730 /* this route is a part of the same solo group as the route
3731 * that was changed. Changing that route did change or will
3732 * change all group members appropriately, so we can ignore it
3737 (*i)->set_listen (false, Controllable::NoGroup);
3743 } else if (_listen_cnt > 0) {
3748 update_route_solo_state ();
3752 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3754 boost::shared_ptr<Route> route (wpr.lock());
3760 bool send_changed = false;
3762 if (route->solo_isolated()) {
3763 if (_solo_isolated_cnt == 0) {
3764 send_changed = true;
3766 _solo_isolated_cnt++;
3767 } else if (_solo_isolated_cnt > 0) {
3768 _solo_isolated_cnt--;
3769 if (_solo_isolated_cnt == 0) {
3770 send_changed = true;
3775 IsolatedChanged (); /* EMIT SIGNAL */
3780 Session::route_solo_changed (bool self_solo_change, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3782 cerr << "route solo change (self ? " << self_solo_change << endl;
3784 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3786 boost::shared_ptr<Route> route (wpr.lock());
3792 if (Config->get_solo_control_is_listen_control()) {
3793 route_listen_changed (group_override, wpr);
3797 if (!self_solo_change) {
3798 // session doesn't care about changes to soloed-by-others
3802 boost::shared_ptr<RouteList> r = routes.reader ();
3805 if (route->self_soloed()) {
3811 /* the route may be a member of a group that has shared-solo
3812 * semantics. If so, then all members of that group should follow the
3813 * solo of the changed route. But ... this is optional, controlled by a
3814 * Controllable::GroupControlDisposition.
3816 * The first argument to the signal that this method is connected to is the
3817 * GroupControlDisposition value that was used to change solo.
3819 * If the solo change was done with group semantics (either InverseGroup
3820 * (force the entire group to change even if the group shared solo is
3821 * disabled) or UseGroup (use the group, which may or may not have the
3822 * shared solo property enabled)) then as we propagate the change to
3823 * the entire session we should IGNORE THE GROUP that the changed route
3827 RouteGroup* rg = route->route_group ();
3828 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3830 if (delta == 1 && Config->get_exclusive_solo()) {
3832 /* new solo: disable all other solos, but not the group if its solo-enabled */
3834 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3836 if ((*i) == route) {
3837 /* already changed */
3841 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3842 /* route does not get solo propagated to it */
3846 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3847 /* this route is a part of the same solo group as the route
3848 * that was changed. Changing that route did change or will
3849 * change all group members appropriately, so we can ignore it
3855 (*i)->set_solo (false, group_override);
3859 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3861 RouteList uninvolved;
3863 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3865 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3866 bool via_sends_only;
3867 bool in_signal_flow;
3869 if ((*i) == route) {
3870 /* already changed */
3874 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3875 /* route does not get solo propagated to it */
3879 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3880 /* this route is a part of the same solo group as the route
3881 * that was changed. Changing that route did change or will
3882 * change all group members appropriately, so we can ignore it
3888 in_signal_flow = false;
3890 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3892 if ((*i)->feeds (route, &via_sends_only)) {
3893 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3894 if (!via_sends_only) {
3895 if (!route->soloed_by_others_upstream()) {
3896 (*i)->mod_solo_by_others_downstream (delta);
3898 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3901 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3903 in_signal_flow = true;
3905 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3908 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3910 if (route->feeds (*i, &via_sends_only)) {
3911 /* propagate solo upstream only if routing other than
3912 sends is involved, but do consider the other route
3913 (*i) to be part of the signal flow even if only
3916 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3920 route->soloed_by_others_downstream(),
3921 route->soloed_by_others_upstream()));
3922 if (!via_sends_only) {
3923 //NB. Triggers Invert Push, which handles soloed by downstream
3924 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3925 (*i)->mod_solo_by_others_upstream (delta);
3927 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3929 in_signal_flow = true;
3931 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3934 if (!in_signal_flow) {
3935 uninvolved.push_back (*i);
3939 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3941 update_route_solo_state (r);
3943 /* now notify that the mute state of the routes not involved in the signal
3944 pathway of the just-solo-changed route may have altered.
3947 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3948 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3949 (*i)->act_on_mute ();
3950 (*i)->mute_control()->Changed (false, Controllable::NoGroup);
3953 SoloChanged (); /* EMIT SIGNAL */
3958 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3960 /* now figure out if anything that matters is soloed (or is "listening")*/
3962 bool something_soloed = false;
3963 bool something_listening = false;
3964 uint32_t listeners = 0;
3965 uint32_t isolated = 0;
3968 r = routes.reader();
3971 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3972 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3973 something_soloed = true;
3976 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3977 if (Config->get_solo_control_is_listen_control()) {
3979 something_listening = true;
3981 (*i)->set_listen (false, Controllable::NoGroup);
3985 if ((*i)->solo_isolated()) {
3990 if (something_soloed != _non_soloed_outs_muted) {
3991 _non_soloed_outs_muted = something_soloed;
3992 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3995 if (something_listening != _listening) {
3996 _listening = something_listening;
3997 SoloActive (_listening);
4000 _listen_cnt = listeners;
4002 if (isolated != _solo_isolated_cnt) {
4003 _solo_isolated_cnt = isolated;
4004 IsolatedChanged (); /* EMIT SIGNAL */
4007 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4008 something_soloed, listeners, isolated));
4011 boost::shared_ptr<RouteList>
4012 Session::get_routes_with_internal_returns() const
4014 boost::shared_ptr<RouteList> r = routes.reader ();
4015 boost::shared_ptr<RouteList> rl (new RouteList);
4017 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4018 if ((*i)->internal_return ()) {
4026 Session::io_name_is_legal (const std::string& name)
4028 boost::shared_ptr<RouteList> r = routes.reader ();
4030 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4031 if (name == *reserved) {
4032 if (!route_by_name (*reserved)) {
4033 /* first instance of a reserved name is allowed */
4036 /* all other instances of a reserved name are not allowed */
4041 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4042 if ((*i)->name() == name) {
4046 if ((*i)->has_io_processor_named (name)) {
4055 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4058 vector<string> connections;
4060 /* if we are passed only a single route and we're not told to turn
4061 * others off, then just do the simple thing.
4064 if (flip_others == false && rl->size() == 1) {
4065 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4067 mt->set_input_active (onoff);
4072 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4074 PortSet& ps ((*rt)->input()->ports());
4076 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4077 p->get_connections (connections);
4080 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4081 routes_using_input_from (*s, rl2);
4084 /* scan all relevant routes to see if others are on or off */
4086 bool others_are_already_on = false;
4088 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4090 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4096 if ((*r) != (*rt)) {
4097 if (mt->input_active()) {
4098 others_are_already_on = true;
4101 /* this one needs changing */
4102 mt->set_input_active (onoff);
4108 /* globally reverse other routes */
4110 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4111 if ((*r) != (*rt)) {
4112 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4114 mt->set_input_active (!others_are_already_on);
4123 Session::routes_using_input_from (const string& str, RouteList& rl)
4125 boost::shared_ptr<RouteList> r = routes.reader();
4127 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4128 if ((*i)->input()->connected_to (str)) {
4134 boost::shared_ptr<Route>
4135 Session::route_by_name (string name)
4137 boost::shared_ptr<RouteList> r = routes.reader ();
4139 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4140 if ((*i)->name() == name) {
4145 return boost::shared_ptr<Route> ((Route*) 0);
4148 boost::shared_ptr<Route>
4149 Session::route_by_id (PBD::ID id)
4151 boost::shared_ptr<RouteList> r = routes.reader ();
4153 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4154 if ((*i)->id() == id) {
4159 return boost::shared_ptr<Route> ((Route*) 0);
4162 boost::shared_ptr<Processor>
4163 Session::processor_by_id (PBD::ID id) const
4165 boost::shared_ptr<RouteList> r = routes.reader ();
4167 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4168 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4174 return boost::shared_ptr<Processor> ();
4177 boost::shared_ptr<Track>
4178 Session::track_by_diskstream_id (PBD::ID id)
4180 boost::shared_ptr<RouteList> r = routes.reader ();
4182 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4183 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4184 if (t && t->using_diskstream_id (id)) {
4189 return boost::shared_ptr<Track> ();
4192 boost::shared_ptr<Route>
4193 Session::route_by_remote_id (uint32_t id)
4195 boost::shared_ptr<RouteList> r = routes.reader ();
4197 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4198 if ((*i)->remote_control_id() == id) {
4203 return boost::shared_ptr<Route> ((Route*) 0);
4207 boost::shared_ptr<Stripable>
4208 Session::stripable_by_remote_id (uint32_t id)
4210 boost::shared_ptr<RouteList> r = routes.reader ();
4212 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4213 if ((*i)->remote_control_id() == id) {
4218 return boost::shared_ptr<Route> ((Route*) 0);
4222 boost::shared_ptr<Route>
4223 Session::route_by_selected_count (uint32_t id)
4225 boost::shared_ptr<RouteList> r = routes.reader ();
4227 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4228 /* NOT IMPLEMENTED */
4231 return boost::shared_ptr<Route> ((Route*) 0);
4236 Session::reassign_track_numbers ()
4240 RouteList r (*(routes.reader ()));
4241 SignalOrderRouteSorter sorter;
4244 StateProtector sp (this);
4246 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4247 if (boost::dynamic_pointer_cast<Track> (*i)) {
4248 (*i)->set_track_number(++tn);
4250 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4251 (*i)->set_track_number(--bn);
4254 const uint32_t decimals = ceilf (log10f (tn + 1));
4255 const bool decimals_changed = _track_number_decimals != decimals;
4256 _track_number_decimals = decimals;
4258 if (decimals_changed && config.get_track_name_number ()) {
4259 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4260 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4262 t->resync_track_name();
4265 // trigger GUI re-layout
4266 config.ParameterChanged("track-name-number");
4271 Session::playlist_region_added (boost::weak_ptr<Region> w)
4273 boost::shared_ptr<Region> r = w.lock ();
4278 /* These are the operations that are currently in progress... */
4279 list<GQuark> curr = _current_trans_quarks;
4282 /* ...and these are the operations during which we want to update
4283 the session range location markers.
4286 ops.push_back (Operations::capture);
4287 ops.push_back (Operations::paste);
4288 ops.push_back (Operations::duplicate_region);
4289 ops.push_back (Operations::insert_file);
4290 ops.push_back (Operations::insert_region);
4291 ops.push_back (Operations::drag_region_brush);
4292 ops.push_back (Operations::region_drag);
4293 ops.push_back (Operations::selection_grab);
4294 ops.push_back (Operations::region_fill);
4295 ops.push_back (Operations::fill_selection);
4296 ops.push_back (Operations::create_region);
4297 ops.push_back (Operations::region_copy);
4298 ops.push_back (Operations::fixed_time_region_copy);
4301 /* See if any of the current operations match the ones that we want */
4303 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4305 /* If so, update the session range markers */
4307 maybe_update_session_range (r->position (), r->last_frame ());
4311 /** Update the session range markers if a is before the current start or
4312 * b is after the current end.
4315 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4317 if (_state_of_the_state & Loading) {
4321 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4323 if (_session_range_location == 0) {
4325 set_session_range_location (a, b + session_end_marker_shift_samples);
4329 if (a < _session_range_location->start()) {
4330 _session_range_location->set_start (a);
4333 if (b > _session_range_location->end()) {
4334 _session_range_location->set_end (b);
4340 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4342 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4343 maybe_update_session_range (i->to, i->to + i->length);
4348 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4350 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4351 maybe_update_session_range (i->from, i->to);
4355 /* Region management */
4357 boost::shared_ptr<Region>
4358 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4360 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4361 RegionFactory::RegionMap::const_iterator i;
4362 boost::shared_ptr<Region> region;
4364 Glib::Threads::Mutex::Lock lm (region_lock);
4366 for (i = regions.begin(); i != regions.end(); ++i) {
4370 if (region->whole_file()) {
4372 if (child->source_equivalent (region)) {
4378 return boost::shared_ptr<Region> ();
4382 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4384 set<boost::shared_ptr<Region> > relevant_regions;
4386 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4387 RegionFactory::get_regions_using_source (*s, relevant_regions);
4390 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4391 set<boost::shared_ptr<Region> >::iterator tmp;
4396 playlists->destroy_region (*r);
4397 RegionFactory::map_remove (*r);
4399 (*r)->drop_sources ();
4400 (*r)->drop_references ();
4402 relevant_regions.erase (r);
4407 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4410 Glib::Threads::Mutex::Lock ls (source_lock);
4411 /* remove from the main source list */
4412 sources.erase ((*s)->id());
4415 (*s)->mark_for_remove ();
4416 (*s)->drop_references ();
4425 Session::remove_last_capture ()
4427 list<boost::shared_ptr<Source> > srcs;
4429 boost::shared_ptr<RouteList> rl = routes.reader ();
4430 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4431 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4436 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4439 srcs.insert (srcs.end(), l.begin(), l.end());
4444 destroy_sources (srcs);
4446 save_state (_current_snapshot_name);
4451 /* Source Management */
4454 Session::add_source (boost::shared_ptr<Source> source)
4456 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4457 pair<SourceMap::iterator,bool> result;
4459 entry.first = source->id();
4460 entry.second = source;
4463 Glib::Threads::Mutex::Lock lm (source_lock);
4464 result = sources.insert (entry);
4467 if (result.second) {
4469 /* yay, new source */
4471 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4474 if (!fs->within_session()) {
4475 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4481 boost::shared_ptr<AudioFileSource> afs;
4483 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4484 if (Config->get_auto_analyse_audio()) {
4485 Analyser::queue_source_for_analysis (source, false);
4489 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4494 Session::remove_source (boost::weak_ptr<Source> src)
4496 if (_state_of_the_state & Deletion) {
4500 SourceMap::iterator i;
4501 boost::shared_ptr<Source> source = src.lock();
4508 Glib::Threads::Mutex::Lock lm (source_lock);
4510 if ((i = sources.find (source->id())) != sources.end()) {
4515 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4517 /* save state so we don't end up with a session file
4518 referring to non-existent sources.
4521 save_state (_current_snapshot_name);
4525 boost::shared_ptr<Source>
4526 Session::source_by_id (const PBD::ID& id)
4528 Glib::Threads::Mutex::Lock lm (source_lock);
4529 SourceMap::iterator i;
4530 boost::shared_ptr<Source> source;
4532 if ((i = sources.find (id)) != sources.end()) {
4539 boost::shared_ptr<AudioFileSource>
4540 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4542 /* Restricted to audio files because only audio sources have channel
4546 Glib::Threads::Mutex::Lock lm (source_lock);
4548 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4549 boost::shared_ptr<AudioFileSource> afs
4550 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4552 if (afs && afs->path() == path && chn == afs->channel()) {
4557 return boost::shared_ptr<AudioFileSource>();
4560 boost::shared_ptr<MidiSource>
4561 Session::midi_source_by_path (const std::string& path) const
4563 /* Restricted to MIDI files because audio sources require a channel
4564 for unique identification, in addition to a path.
4567 Glib::Threads::Mutex::Lock lm (source_lock);
4569 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4570 boost::shared_ptr<MidiSource> ms
4571 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4572 boost::shared_ptr<FileSource> fs
4573 = boost::dynamic_pointer_cast<FileSource>(s->second);
4575 if (ms && fs && fs->path() == path) {
4580 return boost::shared_ptr<MidiSource>();
4584 Session::count_sources_by_origin (const string& path)
4587 Glib::Threads::Mutex::Lock lm (source_lock);
4589 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4590 boost::shared_ptr<FileSource> fs
4591 = boost::dynamic_pointer_cast<FileSource>(i->second);
4593 if (fs && fs->origin() == path) {
4602 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4604 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4605 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4607 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4612 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4614 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4616 if (Glib::path_is_absolute (filepath)) {
4618 /* rip the session dir from the audiofile source */
4620 string session_path;
4621 bool in_another_session = true;
4623 if (filepath.find (interchange_dir_string) != string::npos) {
4625 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4626 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4627 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4628 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4630 /* see if it is within our session */
4632 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4633 if (i->path == session_path) {
4634 in_another_session = false;
4639 in_another_session = false;
4643 if (in_another_session) {
4644 SessionDirectory sd (session_path);
4645 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4649 /* 1) if file belongs to this session
4650 * it may be a relative path (interchange/...)
4651 * or just basename (session_state, remove source)
4652 * -> just use the basename
4654 std::string filename = Glib::path_get_basename (filepath);
4657 /* 2) if the file is outside our session dir:
4658 * (imported but not copied) add the path for check-summming */
4660 path = Glib::path_get_dirname (filepath);
4663 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4667 Session::new_audio_source_path_for_embedded (const std::string& path)
4671 * we know that the filename is already unique because it exists
4672 * out in the filesystem.
4674 * However, when we bring it into the session, we could get a
4677 * Eg. two embedded files:
4682 * When merged into session, these collide.
4684 * There will not be a conflict with in-memory sources
4685 * because when the source was created we already picked
4686 * a unique name for it.
4688 * This collision is not likely to be common, but we have to guard
4689 * against it. So, if there is a collision, take the md5 hash of the
4690 * the path, and use that as the filename instead.
4693 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4694 string base = Glib::path_get_basename (path);
4695 string newpath = Glib::build_filename (sdir.sound_path(), base);
4697 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4701 md5.digestString (path.c_str());
4702 md5.writeToString ();
4703 base = md5.digestChars;
4705 string ext = get_suffix (path);
4712 newpath = Glib::build_filename (sdir.sound_path(), base);
4714 /* if this collides, we're screwed */
4716 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4717 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4726 /** Return true if there are no audio file sources that use @param name as
4727 * the filename component of their path.
4729 * Return false otherwise.
4731 * This method MUST ONLY be used to check in-session, mono files since it
4732 * hard-codes the channel of the audio file source we are looking for as zero.
4734 * If/when Ardour supports native files in non-mono formats, the logic here
4735 * will need to be revisited.
4738 Session::audio_source_name_is_unique (const string& name)
4740 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4741 vector<space_and_path>::iterator i;
4742 uint32_t existing = 0;
4744 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4746 /* note that we search *without* the extension so that
4747 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4748 in the event that this new name is required for
4749 a file format change.
4752 const string spath = *i;
4754 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4759 /* it is possible that we have the path already
4760 * assigned to a source that has not yet been written
4761 * (ie. the write source for a diskstream). we have to
4762 * check this in order to make sure that our candidate
4763 * path isn't used again, because that can lead to
4764 * two Sources point to the same file with different
4765 * notions of their removability.
4769 string possible_path = Glib::build_filename (spath, name);
4771 if (audio_source_by_path_and_channel (possible_path, 0)) {
4777 return (existing == 0);
4781 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)
4784 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4786 if (Profile->get_trx() && destructive) {
4788 sstr << setfill ('0') << setw (4) << cnt;
4789 sstr << legalized_base;
4791 sstr << legalized_base;
4793 if (take_required || related_exists) {
4805 } else if (nchan > 2) {
4810 /* XXX what? more than 26 channels! */
4821 /** Return a unique name based on \a base for a new internal audio source */
4823 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4826 string possible_name;
4827 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4829 bool some_related_source_name_exists = false;
4831 legalized = legalize_for_path (base);
4833 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4835 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4837 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4839 if (audio_source_name_is_unique (possible_name)) {
4843 some_related_source_name_exists = true;
4846 error << string_compose(
4847 _("There are already %1 recordings for %2, which I consider too many."),
4848 limit, base) << endmsg;
4850 throw failed_constructor();
4854 /* We've established that the new name does not exist in any session
4855 * directory, so now find out which one we should use for this new
4859 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4861 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4866 /** Return a unique name based on `base` for a new internal MIDI source */
4868 Session::new_midi_source_path (const string& base)
4871 char buf[PATH_MAX+1];
4872 const uint32_t limit = 10000;
4874 string possible_path;
4875 string possible_name;
4878 legalized = legalize_for_path (base);
4880 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4881 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4883 /* - the main session folder is the first in the vector.
4884 * - after checking all locations for file-name uniqueness,
4885 * we keep the one from the last iteration as new file name
4886 * - midi files are small and should just be kept in the main session-folder
4888 * -> reverse the array, check main session folder last and use that as location
4891 std::reverse(sdirs.begin(), sdirs.end());
4893 for (cnt = 1; cnt <= limit; ++cnt) {
4895 vector<space_and_path>::iterator i;
4896 uint32_t existing = 0;
4898 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4900 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4901 possible_name = buf;
4903 possible_path = Glib::build_filename (*i, possible_name);
4905 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4909 if (midi_source_by_path (possible_path)) {
4914 if (existing == 0) {
4919 error << string_compose(
4920 _("There are already %1 recordings for %2, which I consider too many."),
4921 limit, base) << endmsg;
4927 /* No need to "find best location" for software/app-based RAID, because
4928 MIDI is so small that we always put it in the same place.
4931 return possible_path;
4935 /** Create a new within-session audio source */
4936 boost::shared_ptr<AudioFileSource>
4937 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4939 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4941 if (!path.empty()) {
4942 return boost::dynamic_pointer_cast<AudioFileSource> (
4943 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4945 throw failed_constructor ();
4949 /** Create a new within-session MIDI source */
4950 boost::shared_ptr<MidiSource>
4951 Session::create_midi_source_for_session (string const & basic_name)
4953 const string path = new_midi_source_path (basic_name);
4955 if (!path.empty()) {
4956 return boost::dynamic_pointer_cast<SMFSource> (
4957 SourceFactory::createWritable (
4958 DataType::MIDI, *this, path, false, frame_rate()));
4960 throw failed_constructor ();
4964 /** Create a new within-session MIDI source */
4965 boost::shared_ptr<MidiSource>
4966 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4968 /* the caller passes in the track the source will be used in,
4969 so that we can keep the numbering sane.
4971 Rationale: a track with the name "Foo" that has had N
4972 captures carried out so far will ALREADY have a write source
4973 named "Foo-N+1.mid" waiting to be used for the next capture.
4975 If we call new_midi_source_name() we will get "Foo-N+2". But
4976 there is no region corresponding to "Foo-N+1", so when
4977 "Foo-N+2" appears in the track, the gap presents the user
4978 with odd behaviour - why did it skip past Foo-N+1?
4980 We could explain this to the user in some odd way, but
4981 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4984 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4987 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4989 std::string name = track->steal_write_source_name ();
4992 return boost::shared_ptr<MidiSource>();
4995 /* MIDI files are small, just put them in the first location of the
4996 session source search path.
4999 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5001 return boost::dynamic_pointer_cast<SMFSource> (
5002 SourceFactory::createWritable (
5003 DataType::MIDI, *this, path, false, frame_rate()));
5008 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5010 if (playlist->hidden()) {
5014 playlists->add (playlist);
5017 playlist->release();
5024 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5026 if (_state_of_the_state & Deletion) {
5030 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5036 playlists->remove (playlist);
5042 Session::set_audition (boost::shared_ptr<Region> r)
5044 pending_audition_region = r;
5045 add_post_transport_work (PostTransportAudition);
5046 _butler->schedule_transport_work ();
5050 Session::audition_playlist ()
5052 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5053 ev->region.reset ();
5059 Session::register_lua_function (
5060 const std::string& name,
5061 const std::string& script,
5062 const LuaScriptParamList& args
5065 Glib::Threads::Mutex::Lock lm (lua_lock);
5067 lua_State* L = lua.getState();
5069 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5070 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5071 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5072 if ((*i)->optional && !(*i)->is_set) { continue; }
5073 tbl_arg[(*i)->name] = (*i)->value;
5075 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5080 Session::unregister_lua_function (const std::string& name)
5082 Glib::Threads::Mutex::Lock lm (lua_lock);
5083 (*_lua_del)(name); // throws luabridge::LuaException
5084 lua.collect_garbage ();
5088 std::vector<std::string>
5089 Session::registered_lua_functions ()
5091 Glib::Threads::Mutex::Lock lm (lua_lock);
5092 std::vector<std::string> rv;
5095 luabridge::LuaRef list ((*_lua_list)());
5096 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5097 if (!i.key ().isString ()) { assert(0); continue; }
5098 rv.push_back (i.key ().cast<std::string> ());
5100 } catch (luabridge::LuaException const& e) { }
5105 static void _lua_print (std::string s) {
5106 std::cout << "SessionLua: " << s << "\n";
5111 Session::try_run_lua (pframes_t nframes)
5113 if (_n_lua_scripts == 0) return;
5114 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5116 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5121 Session::setup_lua ()
5124 lua.Print.connect (&_lua_print);
5127 "function ArdourSession ()"
5128 " local self = { scripts = {}, instances = {} }"
5130 " local remove = function (n)"
5131 " self.scripts[n] = nil"
5132 " self.instances[n] = nil"
5133 " Session:scripts_changed()" // call back
5136 " local addinternal = function (n, f, a)"
5137 " assert(type(n) == 'string', 'function-name must be string')"
5138 " assert(type(f) == 'function', 'Given script is a not a function')"
5139 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5140 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5141 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5142 " 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"
5143 " 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 }"
5144 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5145 " Session:scripts_changed()" // call back
5148 " local add = function (n, b, a)"
5149 " assert(type(b) == 'string', 'ByteCode must be string')"
5150 " load (b)()" // assigns f
5151 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5152 " addinternal (n, load(f), a)"
5155 " local run = function (...)"
5156 " for n, s in pairs (self.instances) do"
5157 " local status, err = pcall (s, ...)"
5158 " if not status then"
5159 " print ('fn \"'.. n .. '\": ', err)"
5166 " local cleanup = function ()"
5167 " self.scripts = nil"
5168 " self.instances = nil"
5171 " local list = function ()"
5173 " for n, _ in pairs (self.scripts) do"
5179 " local function basic_serialize (o)"
5180 " if type(o) == \"number\" then"
5181 " return tostring(o)"
5183 " return string.format(\"%q\", o)"
5187 " local function serialize (name, value)"
5188 " local rv = name .. ' = '"
5190 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5191 " return rv .. basic_serialize(value) .. ' '"
5192 " elseif type(value) == \"table\" then"
5194 " for k,v in pairs(value) do"
5195 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5196 " rv = rv .. serialize(fieldname, v) .. ' '"
5197 " collectgarbage()" // string concatenation allocates a new string :(
5200 " elseif type(value) == \"function\" then"
5201 " return rv .. string.format(\"%q\", string.dump(value, true))"
5203 " error('cannot save a ' .. type(value))"
5208 " local save = function ()"
5209 " return (serialize('scripts', self.scripts))"
5212 " local restore = function (state)"
5213 " self.scripts = {}"
5215 " for n, s in pairs (scripts) do"
5216 " addinternal (n, load(s['f']), s['a'])"
5220 " return { run = run, add = add, remove = remove,"
5221 " list = list, restore = restore, save = save, cleanup = cleanup}"
5224 " sess = ArdourSession ()"
5225 " ArdourSession = nil"
5227 "function ardour () end"
5230 lua_State* L = lua.getState();
5233 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5234 lua.do_command ("sess = nil"); // hide it.
5235 lua.do_command ("collectgarbage()");
5237 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5238 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5239 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5240 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5241 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5242 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5243 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5244 } catch (luabridge::LuaException const& e) {
5245 fatal << string_compose (_("programming error: %1"),
5246 X_("Failed to setup Lua interpreter"))
5248 abort(); /*NOTREACHED*/
5251 LuaBindings::stddef (L);
5252 LuaBindings::common (L);
5253 LuaBindings::dsp (L);
5254 luabridge::push <Session *> (L, this);
5255 lua_setglobal (L, "Session");
5259 Session::scripts_changed ()
5261 assert (!lua_lock.trylock()); // must hold lua_lock
5264 luabridge::LuaRef list ((*_lua_list)());
5266 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5267 if (!i.key ().isString ()) { assert(0); continue; }
5270 _n_lua_scripts = cnt;
5271 } catch (luabridge::LuaException const& e) {
5272 fatal << string_compose (_("programming error: %1"),
5273 X_("Indexing Lua Session Scripts failed."))
5275 abort(); /*NOTREACHED*/
5280 Session::non_realtime_set_audition ()
5282 assert (pending_audition_region);
5283 auditioner->audition_region (pending_audition_region);
5284 pending_audition_region.reset ();
5285 AuditionActive (true); /* EMIT SIGNAL */
5289 Session::audition_region (boost::shared_ptr<Region> r)
5291 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5297 Session::cancel_audition ()
5302 if (auditioner->auditioning()) {
5303 auditioner->cancel_audition ();
5304 AuditionActive (false); /* EMIT SIGNAL */
5309 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5311 if (a->is_monitor()) {
5314 if (b->is_monitor()) {
5317 return a->order_key () < b->order_key ();
5321 Session::is_auditioning () const
5323 /* can be called before we have an auditioner object */
5325 return auditioner->auditioning();
5332 Session::graph_reordered ()
5334 /* don't do this stuff if we are setting up connections
5335 from a set_state() call or creating new tracks. Ditto for deletion.
5338 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5342 /* every track/bus asked for this to be handled but it was deferred because
5343 we were connecting. do it now.
5346 request_input_change_handling ();
5350 /* force all diskstreams to update their capture offset values to
5351 reflect any changes in latencies within the graph.
5354 boost::shared_ptr<RouteList> rl = routes.reader ();
5355 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5356 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5358 tr->set_capture_offset ();
5363 /** @return Number of frames that there is disk space available to write,
5366 boost::optional<framecnt_t>
5367 Session::available_capture_duration ()
5369 Glib::Threads::Mutex::Lock lm (space_lock);
5371 if (_total_free_4k_blocks_uncertain) {
5372 return boost::optional<framecnt_t> ();
5375 float sample_bytes_on_disk = 4.0; // keep gcc happy
5377 switch (config.get_native_file_data_format()) {
5379 sample_bytes_on_disk = 4.0;
5383 sample_bytes_on_disk = 3.0;
5387 sample_bytes_on_disk = 2.0;
5391 /* impossible, but keep some gcc versions happy */
5392 fatal << string_compose (_("programming error: %1"),
5393 X_("illegal native file data format"))
5395 abort(); /*NOTREACHED*/
5398 double scale = 4096.0 / sample_bytes_on_disk;
5400 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5401 return max_framecnt;
5404 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5408 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5411 RCUWriter<BundleList> writer (_bundles);
5412 boost::shared_ptr<BundleList> b = writer.get_copy ();
5413 b->push_back (bundle);
5417 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5424 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5426 bool removed = false;
5429 RCUWriter<BundleList> writer (_bundles);
5430 boost::shared_ptr<BundleList> b = writer.get_copy ();
5431 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5433 if (i != b->end()) {
5440 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5446 boost::shared_ptr<Bundle>
5447 Session::bundle_by_name (string name) const
5449 boost::shared_ptr<BundleList> b = _bundles.reader ();
5451 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5452 if ((*i)->name() == name) {
5457 return boost::shared_ptr<Bundle> ();
5461 Session::tempo_map_changed (const PropertyChange&)
5465 playlists->update_after_tempo_map_change ();
5467 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5473 Session::gui_tempo_map_changed ()
5477 playlists->update_after_tempo_map_change ();
5479 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5483 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5485 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5486 (*i)->recompute_frames_from_bbt ();
5490 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5491 * the given count with the current block size.
5494 Session::ensure_buffers (ChanCount howmany)
5496 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5500 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5502 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5503 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5508 Session::next_insert_id ()
5510 /* this doesn't really loop forever. just think about it */
5513 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5514 if (!insert_bitset[n]) {
5515 insert_bitset[n] = true;
5521 /* none available, so resize and try again */
5523 insert_bitset.resize (insert_bitset.size() + 16, false);
5528 Session::next_send_id ()
5530 /* this doesn't really loop forever. just think about it */
5533 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5534 if (!send_bitset[n]) {
5535 send_bitset[n] = true;
5541 /* none available, so resize and try again */
5543 send_bitset.resize (send_bitset.size() + 16, false);
5548 Session::next_aux_send_id ()
5550 /* this doesn't really loop forever. just think about it */
5553 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5554 if (!aux_send_bitset[n]) {
5555 aux_send_bitset[n] = true;
5561 /* none available, so resize and try again */
5563 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5568 Session::next_return_id ()
5570 /* this doesn't really loop forever. just think about it */
5573 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5574 if (!return_bitset[n]) {
5575 return_bitset[n] = true;
5581 /* none available, so resize and try again */
5583 return_bitset.resize (return_bitset.size() + 16, false);
5588 Session::mark_send_id (uint32_t id)
5590 if (id >= send_bitset.size()) {
5591 send_bitset.resize (id+16, false);
5593 if (send_bitset[id]) {
5594 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5596 send_bitset[id] = true;
5600 Session::mark_aux_send_id (uint32_t id)
5602 if (id >= aux_send_bitset.size()) {
5603 aux_send_bitset.resize (id+16, false);
5605 if (aux_send_bitset[id]) {
5606 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5608 aux_send_bitset[id] = true;
5612 Session::mark_return_id (uint32_t id)
5614 if (id >= return_bitset.size()) {
5615 return_bitset.resize (id+16, false);
5617 if (return_bitset[id]) {
5618 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5620 return_bitset[id] = true;
5624 Session::mark_insert_id (uint32_t id)
5626 if (id >= insert_bitset.size()) {
5627 insert_bitset.resize (id+16, false);
5629 if (insert_bitset[id]) {
5630 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5632 insert_bitset[id] = true;
5636 Session::unmark_send_id (uint32_t id)
5638 if (id < send_bitset.size()) {
5639 send_bitset[id] = false;
5644 Session::unmark_aux_send_id (uint32_t id)
5646 if (id < aux_send_bitset.size()) {
5647 aux_send_bitset[id] = false;
5652 Session::unmark_return_id (uint32_t id)
5654 if (_state_of_the_state & Deletion) { return; }
5655 if (id < return_bitset.size()) {
5656 return_bitset[id] = false;
5661 Session::unmark_insert_id (uint32_t id)
5663 if (id < insert_bitset.size()) {
5664 insert_bitset[id] = false;
5669 Session::reset_native_file_format ()
5671 boost::shared_ptr<RouteList> rl = routes.reader ();
5673 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5674 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5676 /* don't save state as we do this, there's no point
5678 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5679 tr->reset_write_sources (false);
5680 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5686 Session::route_name_unique (string n) const
5688 boost::shared_ptr<RouteList> r = routes.reader ();
5690 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5691 if ((*i)->name() == n) {
5700 Session::route_name_internal (string n) const
5702 if (auditioner && auditioner->name() == n) {
5706 if (_click_io && _click_io->name() == n) {
5714 Session::freeze_all (InterThreadInfo& itt)
5716 boost::shared_ptr<RouteList> r = routes.reader ();
5718 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5720 boost::shared_ptr<Track> t;
5722 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5723 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5733 boost::shared_ptr<Region>
5734 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5735 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5736 InterThreadInfo& itt,
5737 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5738 bool for_export, bool for_freeze)
5740 boost::shared_ptr<Region> result;
5741 boost::shared_ptr<Playlist> playlist;
5742 boost::shared_ptr<Source> source;
5743 ChanCount diskstream_channels (track.n_channels());
5744 framepos_t position;
5745 framecnt_t this_chunk;
5747 framepos_t latency_skip;
5749 framepos_t len = end - start;
5750 bool need_block_size_reset = false;
5751 ChanCount const max_proc = track.max_processor_streams ();
5752 string legal_playlist_name;
5753 string possible_path;
5756 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5757 end, start) << endmsg;
5761 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5762 include_endpoint, for_export, for_freeze);
5764 if (diskstream_channels.n(track.data_type()) < 1) {
5765 error << _("Cannot write a range with no data.") << endmsg;
5769 // block all process callback handling
5771 block_processing ();
5774 // synchronize with AudioEngine::process_callback()
5775 // make sure processing is not currently running
5776 // and processing_blocked() is honored before
5777 // acquiring thread buffers
5778 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5781 _bounce_processing_active = true;
5783 /* call tree *MUST* hold route_lock */
5785 if ((playlist = track.playlist()) == 0) {
5789 legal_playlist_name = legalize_for_path (playlist->name());
5791 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5793 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5794 string path = ((track.data_type() == DataType::AUDIO)
5795 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5796 : new_midi_source_path (legal_playlist_name));
5803 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5806 catch (failed_constructor& err) {
5807 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5811 srcs.push_back (source);
5814 /* tell redirects that care that we are about to use a much larger
5815 * blocksize. this will flush all plugins too, so that they are ready
5816 * to be used for this process.
5819 need_block_size_reset = true;
5820 track.set_block_size (bounce_chunk_size);
5821 _engine.main_thread()->get_buffers ();
5825 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5827 /* create a set of reasonably-sized buffers */
5828 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5829 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5831 buffers.set_count (max_proc);
5833 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5834 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5835 boost::shared_ptr<MidiSource> ms;
5837 afs->prepare_for_peakfile_writes ();
5838 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5839 Source::Lock lock(ms->mutex());
5840 ms->mark_streaming_write_started(lock);
5844 while (to_do && !itt.cancel) {
5846 this_chunk = min (to_do, bounce_chunk_size);
5848 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5852 start += this_chunk;
5853 to_do -= this_chunk;
5854 itt.progress = (float) (1.0 - ((double) to_do / len));
5856 if (latency_skip >= bounce_chunk_size) {
5857 latency_skip -= bounce_chunk_size;
5861 const framecnt_t current_chunk = this_chunk - latency_skip;
5864 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5865 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5866 boost::shared_ptr<MidiSource> ms;
5869 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5872 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5873 Source::Lock lock(ms->mutex());
5875 const MidiBuffer& buf = buffers.get_midi(0);
5876 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5877 Evoral::Event<framepos_t> ev = *i;
5878 ev.set_time(ev.time() - position);
5879 ms->append_event_frames(lock, ev, ms->timeline_position());
5886 /* post-roll, pick up delayed processor output */
5887 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5889 while (latency_skip && !itt.cancel) {
5890 this_chunk = min (latency_skip, bounce_chunk_size);
5891 latency_skip -= this_chunk;
5893 buffers.silence (this_chunk, 0);
5894 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5897 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5898 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5901 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5913 xnow = localtime (&now);
5915 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5916 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5917 boost::shared_ptr<MidiSource> ms;
5920 afs->update_header (position, *xnow, now);
5921 afs->flush_header ();
5922 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5923 Source::Lock lock(ms->mutex());
5924 ms->mark_streaming_write_completed(lock);
5928 /* construct a region to represent the bounced material */
5932 plist.add (Properties::start, 0);
5933 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5934 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5936 result = RegionFactory::create (srcs, plist);
5942 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5943 (*src)->mark_for_remove ();
5944 (*src)->drop_references ();
5948 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5949 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5952 afs->done_with_peakfile_writes ();
5956 _bounce_processing_active = false;
5958 if (need_block_size_reset) {
5959 _engine.main_thread()->drop_buffers ();
5960 track.set_block_size (get_block_size());
5963 unblock_processing ();
5969 Session::gain_automation_buffer() const
5971 return ProcessThread::gain_automation_buffer ();
5975 Session::trim_automation_buffer() const
5977 return ProcessThread::trim_automation_buffer ();
5981 Session::send_gain_automation_buffer() const
5983 return ProcessThread::send_gain_automation_buffer ();
5987 Session::pan_automation_buffer() const
5989 return ProcessThread::pan_automation_buffer ();
5993 Session::get_silent_buffers (ChanCount count)
5995 return ProcessThread::get_silent_buffers (count);
5999 Session::get_scratch_buffers (ChanCount count, bool silence)
6001 return ProcessThread::get_scratch_buffers (count, silence);
6005 Session::get_noinplace_buffers (ChanCount count)
6007 return ProcessThread::get_noinplace_buffers (count);
6011 Session::get_route_buffers (ChanCount count, bool silence)
6013 return ProcessThread::get_route_buffers (count, silence);
6018 Session::get_mix_buffers (ChanCount count)
6020 return ProcessThread::get_mix_buffers (count);
6024 Session::ntracks () const
6027 boost::shared_ptr<RouteList> r = routes.reader ();
6029 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6030 if (boost::dynamic_pointer_cast<Track> (*i)) {
6039 Session::nbusses () const
6042 boost::shared_ptr<RouteList> r = routes.reader ();
6044 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6045 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6054 Session::add_automation_list(AutomationList *al)
6056 automation_lists[al->id()] = al;
6059 /** @return true if there is at least one record-enabled track, otherwise false */
6061 Session::have_rec_enabled_track () const
6063 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6067 Session::have_rec_disabled_track () const
6069 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6072 /** Update the state of our rec-enabled tracks flag */
6074 Session::update_route_record_state ()
6076 boost::shared_ptr<RouteList> rl = routes.reader ();
6077 RouteList::iterator i = rl->begin();
6078 while (i != rl->end ()) {
6080 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6081 if (tr && tr->record_enabled ()) {
6088 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6090 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6092 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6093 RecordStateChanged (); /* EMIT SIGNAL */
6096 for (i = rl->begin(); i != rl->end (); ++i) {
6097 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6098 if (tr && !tr->record_enabled ()) {
6103 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6105 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6107 if (record_status() == Recording && record_arm_state_changed ) {
6108 RecordArmStateChanged ();
6114 Session::listen_position_changed ()
6116 boost::shared_ptr<RouteList> r = routes.reader ();
6118 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6119 (*i)->listen_position_changed ();
6124 Session::solo_control_mode_changed ()
6126 /* cancel all solo or all listen when solo control mode changes */
6129 set_solo (get_routes(), false);
6130 } else if (listening()) {
6131 set_listen (get_routes(), false);
6135 /** Called when a property of one of our route groups changes */
6137 Session::route_group_property_changed (RouteGroup* rg)
6139 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6142 /** Called when a route is added to one of our route groups */
6144 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6146 RouteAddedToRouteGroup (rg, r);
6149 /** Called when a route is removed from one of our route groups */
6151 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6153 update_route_record_state ();
6154 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6157 boost::shared_ptr<RouteList>
6158 Session::get_tracks () const
6160 boost::shared_ptr<RouteList> rl = routes.reader ();
6161 boost::shared_ptr<RouteList> tl (new RouteList);
6163 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6164 if (boost::dynamic_pointer_cast<Track> (*r)) {
6165 if (!(*r)->is_auditioner()) {
6173 boost::shared_ptr<RouteList>
6174 Session::get_routes_with_regions_at (framepos_t const p) const
6176 boost::shared_ptr<RouteList> r = routes.reader ();
6177 boost::shared_ptr<RouteList> rl (new RouteList);
6179 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6180 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6185 boost::shared_ptr<Playlist> pl = tr->playlist ();
6190 if (pl->has_region_at (p)) {
6199 Session::goto_end ()
6201 if (_session_range_location) {
6202 request_locate (_session_range_location->end(), false);
6204 request_locate (0, false);
6209 Session::goto_start ()
6211 if (_session_range_location) {
6212 request_locate (_session_range_location->start(), false);
6214 request_locate (0, false);
6219 Session::current_start_frame () const
6221 return _session_range_location ? _session_range_location->start() : 0;
6225 Session::current_end_frame () const
6227 return _session_range_location ? _session_range_location->end() : 0;
6231 Session::set_session_range_location (framepos_t start, framepos_t end)
6233 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6234 _locations->add (_session_range_location);
6238 Session::step_edit_status_change (bool yn)
6244 send = (_step_editors == 0);
6249 send = (_step_editors == 1);
6252 if (_step_editors > 0) {
6258 StepEditStatusChange (val);
6264 Session::start_time_changed (framepos_t old)
6266 /* Update the auto loop range to match the session range
6267 (unless the auto loop range has been changed by the user)
6270 Location* s = _locations->session_range_location ();
6275 Location* l = _locations->auto_loop_location ();
6277 if (l && l->start() == old) {
6278 l->set_start (s->start(), true);
6283 Session::end_time_changed (framepos_t old)
6285 /* Update the auto loop range to match the session range
6286 (unless the auto loop range has been changed by the user)
6289 Location* s = _locations->session_range_location ();
6294 Location* l = _locations->auto_loop_location ();
6296 if (l && l->end() == old) {
6297 l->set_end (s->end(), true);
6301 std::vector<std::string>
6302 Session::source_search_path (DataType type) const
6306 if (session_dirs.size() == 1) {
6308 case DataType::AUDIO:
6309 sp.push_back (_session_dir->sound_path());
6311 case DataType::MIDI:
6312 sp.push_back (_session_dir->midi_path());
6316 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6317 SessionDirectory sdir (i->path);
6319 case DataType::AUDIO:
6320 sp.push_back (sdir.sound_path());
6322 case DataType::MIDI:
6323 sp.push_back (sdir.midi_path());
6329 if (type == DataType::AUDIO) {
6330 const string sound_path_2X = _session_dir->sound_path_2X();
6331 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6332 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6333 sp.push_back (sound_path_2X);
6338 // now check the explicit (possibly user-specified) search path
6341 case DataType::AUDIO:
6342 sp += Searchpath(config.get_audio_search_path ());
6344 case DataType::MIDI:
6345 sp += Searchpath(config.get_midi_search_path ());
6353 Session::ensure_search_path_includes (const string& path, DataType type)
6362 case DataType::AUDIO:
6363 sp += Searchpath(config.get_audio_search_path ());
6365 case DataType::MIDI:
6366 sp += Searchpath (config.get_midi_search_path ());
6370 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6371 /* No need to add this new directory if it has the same inode as
6372 an existing one; checking inode rather than name prevents duplicated
6373 directories when we are using symlinks.
6375 On Windows, I think we could just do if (*i == path) here.
6377 if (PBD::equivalent_paths (*i, path)) {
6385 case DataType::AUDIO:
6386 config.set_audio_search_path (sp.to_string());
6388 case DataType::MIDI:
6389 config.set_midi_search_path (sp.to_string());
6395 Session::remove_dir_from_search_path (const string& dir, DataType type)
6400 case DataType::AUDIO:
6401 sp = Searchpath(config.get_audio_search_path ());
6403 case DataType::MIDI:
6404 sp = Searchpath (config.get_midi_search_path ());
6411 case DataType::AUDIO:
6412 config.set_audio_search_path (sp.to_string());
6414 case DataType::MIDI:
6415 config.set_midi_search_path (sp.to_string());
6421 boost::shared_ptr<Speakers>
6422 Session::get_speakers()
6428 Session::unknown_processors () const
6432 boost::shared_ptr<RouteList> r = routes.reader ();
6433 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6434 list<string> t = (*i)->unknown_processors ();
6435 copy (t.begin(), t.end(), back_inserter (p));
6445 Session::update_latency (bool playback)
6448 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6450 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6454 boost::shared_ptr<RouteList> r = routes.reader ();
6455 framecnt_t max_latency = 0;
6458 /* reverse the list so that we work backwards from the last route to run to the first */
6459 RouteList* rl = routes.reader().get();
6460 r.reset (new RouteList (*rl));
6461 reverse (r->begin(), r->end());
6464 /* compute actual latency values for the given direction and store them all in per-port
6465 structures. this will also publish the same values (to JACK) so that computation of latency
6466 for routes can consistently use public latency values.
6469 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6470 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6473 /* because we latency compensate playback, our published playback latencies should
6474 be the same for all output ports - all material played back by ardour has
6475 the same latency, whether its caused by plugins or by latency compensation. since
6476 these may differ from the values computed above, reset all playback port latencies
6480 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6482 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6483 (*i)->set_public_port_latencies (max_latency, playback);
6488 post_playback_latency ();
6492 post_capture_latency ();
6495 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6499 Session::post_playback_latency ()
6501 set_worst_playback_latency ();
6503 boost::shared_ptr<RouteList> r = routes.reader ();
6505 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6506 if (!(*i)->is_auditioner() && ((*i)->active())) {
6507 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6511 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6512 (*i)->set_latency_compensation (_worst_track_latency);
6517 Session::post_capture_latency ()
6519 set_worst_capture_latency ();
6521 /* reflect any changes in capture latencies into capture offsets
6524 boost::shared_ptr<RouteList> rl = routes.reader();
6525 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6526 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6528 tr->set_capture_offset ();
6534 Session::initialize_latencies ()
6537 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6538 update_latency (false);
6539 update_latency (true);
6542 set_worst_io_latencies ();
6546 Session::set_worst_io_latencies ()
6548 set_worst_playback_latency ();
6549 set_worst_capture_latency ();
6553 Session::set_worst_playback_latency ()
6555 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6559 _worst_output_latency = 0;
6561 if (!_engine.connected()) {
6565 boost::shared_ptr<RouteList> r = routes.reader ();
6567 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6568 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6571 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6575 Session::set_worst_capture_latency ()
6577 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6581 _worst_input_latency = 0;
6583 if (!_engine.connected()) {
6587 boost::shared_ptr<RouteList> r = routes.reader ();
6589 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6590 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6593 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6597 Session::update_latency_compensation (bool force_whole_graph)
6599 bool some_track_latency_changed = false;
6601 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6605 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6607 _worst_track_latency = 0;
6609 boost::shared_ptr<RouteList> r = routes.reader ();
6611 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6612 if (!(*i)->is_auditioner() && ((*i)->active())) {
6614 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6615 some_track_latency_changed = true;
6617 _worst_track_latency = max (tl, _worst_track_latency);
6621 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6622 (some_track_latency_changed ? "yes" : "no")));
6624 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6626 if (some_track_latency_changed || force_whole_graph) {
6627 _engine.update_latencies ();
6631 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6632 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6636 tr->set_capture_offset ();
6641 Session::session_name_is_legal (const string& path)
6643 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6645 for (int i = 0; illegal_chars[i]; ++i) {
6646 if (path.find (illegal_chars[i]) != string::npos) {
6647 return illegal_chars[i];
6655 Session::next_control_id () const
6659 /* the monitor bus remote ID is in a different
6660 * "namespace" than regular routes. its existence doesn't
6661 * affect normal (low) numbered routes.
6668 /* the same about masterbus in Waves Tracks */
6670 if (Profile->get_trx() && _master_out) {
6674 return nroutes() - subtract;
6678 Session::notify_remote_id_change ()
6680 if (deletion_in_progress()) {
6684 switch (Config->get_remote_model()) {
6686 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6692 #ifdef USE_TRACKS_CODE_FEATURES
6693 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6694 * if track order has been changed by user
6696 reconnect_existing_routes(true, true);
6702 Session::sync_order_keys ()
6704 if (deletion_in_progress()) {
6708 /* tell everyone that something has happened to the sort keys
6709 and let them sync up with the change(s)
6710 this will give objects that manage the sort order keys the
6711 opportunity to keep them in sync if they wish to.
6714 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6716 reassign_track_numbers();
6718 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6720 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6724 Session::operation_in_progress (GQuark op) const
6726 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6729 boost::shared_ptr<Port>
6730 Session::ltc_input_port () const
6732 return _ltc_input->nth (0);
6735 boost::shared_ptr<Port>
6736 Session::ltc_output_port () const
6738 return _ltc_output->nth (0);
6742 Session::reconnect_ltc_input ()
6746 string src = Config->get_ltc_source_port();
6748 _ltc_input->disconnect (this);
6750 if (src != _("None") && !src.empty()) {
6751 _ltc_input->nth (0)->connect (src);
6754 if ( ARDOUR::Profile->get_trx () ) {
6755 // Tracks need this signal to update timecode_source_dropdown
6756 MtcOrLtcInputPortChanged (); //emit signal
6762 Session::reconnect_ltc_output ()
6766 string src = Config->get_ltc_output_port();
6768 _ltc_output->disconnect (this);
6770 if (src != _("None") && !src.empty()) {
6771 _ltc_output->nth (0)->connect (src);
6777 Session::set_range_selection (framepos_t start, framepos_t end)
6779 _range_selection = Evoral::Range<framepos_t> (start, end);
6780 #ifdef USE_TRACKS_CODE_FEATURES
6781 follow_playhead_priority ();
6786 Session::set_object_selection (framepos_t start, framepos_t end)
6788 _object_selection = Evoral::Range<framepos_t> (start, end);
6789 #ifdef USE_TRACKS_CODE_FEATURES
6790 follow_playhead_priority ();
6795 Session::clear_range_selection ()
6797 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6798 #ifdef USE_TRACKS_CODE_FEATURES
6799 follow_playhead_priority ();
6804 Session::clear_object_selection ()
6806 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6807 #ifdef USE_TRACKS_CODE_FEATURES
6808 follow_playhead_priority ();
6813 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6814 const ChanCount& input_start,
6815 const ChanCount& output_start,
6816 const ChanCount& input_offset,
6817 const ChanCount& output_offset)
6819 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6820 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6821 input_start, output_start,
6822 input_offset, output_offset));
6824 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6825 pthread_cond_signal (&_auto_connect_cond);
6826 pthread_mutex_unlock (&_auto_connect_mutex);
6831 Session::auto_connect (const AutoConnectRequest& ar)
6833 boost::shared_ptr<Route> route = ar.route.lock();
6835 if (!route) { return; }
6837 if (!IO::connecting_legal) {
6841 /* If both inputs and outputs are auto-connected to physical ports,
6842 * use the max of input and output offsets to ensure auto-connected
6843 * port numbers always match up (e.g. the first audio input and the
6844 * first audio output of the route will have the same physical
6845 * port number). Otherwise just use the lowest input or output
6849 const bool in_out_physical =
6850 (Config->get_input_auto_connect() & AutoConnectPhysical)
6851 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6852 && ar.connect_inputs;
6854 const ChanCount in_offset = in_out_physical
6855 ? ChanCount::max(ar.input_offset, ar.output_offset)
6858 const ChanCount out_offset = in_out_physical
6859 ? ChanCount::max(ar.input_offset, ar.output_offset)
6862 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6863 vector<string> physinputs;
6864 vector<string> physoutputs;
6866 _engine.get_physical_outputs (*t, physoutputs);
6867 _engine.get_physical_inputs (*t, physinputs);
6869 if (!physinputs.empty() && ar.connect_inputs) {
6870 uint32_t nphysical_in = physinputs.size();
6872 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6875 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6876 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6879 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6885 if (!physoutputs.empty()) {
6886 uint32_t nphysical_out = physoutputs.size();
6887 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6891 * do not create new connections if we reached the limit of physical outputs
6894 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6895 ARDOUR::Profile->get_trx () &&
6896 ar.output_offset.get(*t) == nphysical_out ) {
6900 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6901 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6902 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6903 /* master bus is audio only */
6904 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6905 port = _master_out->input()->ports().port(*t,
6906 i % _master_out->input()->n_ports().get(*t))->name();
6910 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6919 Session::auto_connect_thread_start ()
6921 if (_ac_thread_active) {
6925 while (!_auto_connect_queue.empty ()) {
6926 _auto_connect_queue.pop ();
6929 _ac_thread_active = true;
6930 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6931 _ac_thread_active = false;
6936 Session::auto_connect_thread_terminate ()
6938 if (!_ac_thread_active) {
6941 _ac_thread_active = false;
6944 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6945 while (!_auto_connect_queue.empty ()) {
6946 _auto_connect_queue.pop ();
6950 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6951 pthread_cond_signal (&_auto_connect_cond);
6952 pthread_mutex_unlock (&_auto_connect_mutex);
6956 pthread_join (_auto_connect_thread, &status);
6960 Session::auto_connect_thread (void *arg)
6962 Session *s = static_cast<Session *>(arg);
6963 s->auto_connect_thread_run ();
6969 Session::auto_connect_thread_run ()
6971 pthread_set_name (X_("autoconnect"));
6972 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6973 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6974 pthread_mutex_lock (&_auto_connect_mutex);
6975 while (_ac_thread_active) {
6977 if (!_auto_connect_queue.empty ()) {
6978 // Why would we need the process lock ??
6979 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
6980 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
6981 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
6982 // We have control over those, but what does jack do?
6983 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6985 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6986 while (!_auto_connect_queue.empty ()) {
6987 const AutoConnectRequest ar (_auto_connect_queue.front());
6988 _auto_connect_queue.pop ();
6995 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
6997 pthread_mutex_unlock (&_auto_connect_mutex);