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 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
701 /* reset these three references to special routes before we do the usual route delete thing */
703 _master_out.reset ();
704 _monitor_out.reset ();
707 RCUWriter<RouteList> writer (routes);
708 boost::shared_ptr<RouteList> r = writer.get_copy ();
710 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
711 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
712 (*i)->drop_references ();
716 /* writer goes out of scope and updates master */
721 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
722 Glib::Threads::Mutex::Lock lm (source_lock);
723 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
724 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
725 i->second->drop_references ();
731 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
734 emit_thread_terminate ();
736 pthread_cond_destroy (&_rt_emit_cond);
737 pthread_mutex_destroy (&_rt_emit_mutex);
739 pthread_cond_destroy (&_auto_connect_cond);
740 pthread_mutex_destroy (&_auto_connect_mutex);
742 delete _scene_changer; _scene_changer = 0;
743 delete midi_control_ui; midi_control_ui = 0;
745 delete _mmc; _mmc = 0;
746 delete _midi_ports; _midi_ports = 0;
747 delete _locations; _locations = 0;
753 /* clear event queue, the session is gone, nobody is interested in
754 * those anymore, but they do leak memory if not removed
756 while (!immediate_events.empty ()) {
757 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
758 SessionEvent *ev = immediate_events.front ();
759 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
760 immediate_events.pop_front ();
764 case SessionEvent::AutoLoop:
765 case SessionEvent::AutoLoopDeclick:
766 case SessionEvent::Skip:
767 case SessionEvent::PunchIn:
768 case SessionEvent::PunchOut:
769 case SessionEvent::StopOnce:
770 case SessionEvent::RangeStop:
771 case SessionEvent::RangeLocate:
775 case SessionEvent::RealTimeOperation:
782 del = del && !_remove_event (ev);
789 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
791 BOOST_SHOW_POINTERS ();
795 Session::setup_ltc ()
799 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
800 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
802 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
803 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
806 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
807 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
809 reconnect_ltc_input ();
812 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
813 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
816 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
817 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
819 reconnect_ltc_output ();
822 /* fix up names of LTC ports because we don't want the normal
823 * IO style of NAME/TYPE-{in,out}N
826 _ltc_input->nth (0)->set_name (X_("LTC-in"));
827 _ltc_output->nth (0)->set_name (X_("LTC-out"));
831 Session::setup_click ()
835 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
836 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
838 _click_io.reset (new ClickIO (*this, X_("Click")));
839 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
840 _click_gain->activate ();
842 setup_click_state (state_tree->root());
844 setup_click_state (0);
849 Session::setup_click_state (const XMLNode* node)
851 const XMLNode* child = 0;
853 if (node && (child = find_named_node (*node, "Click")) != 0) {
855 /* existing state for Click */
858 if (Stateful::loading_state_version < 3000) {
859 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
861 const XMLNodeList& children (child->children());
862 XMLNodeList::const_iterator i = children.begin();
863 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
865 if (i != children.end()) {
866 c = _click_gain->set_state (**i, Stateful::loading_state_version);
872 _clicking = Config->get_clicking ();
876 error << _("could not setup Click I/O") << endmsg;
883 /* default state for Click: dual-mono to first 2 physical outputs */
886 _engine.get_physical_outputs (DataType::AUDIO, outs);
888 for (uint32_t physport = 0; physport < 2; ++physport) {
889 if (outs.size() > physport) {
890 if (_click_io->add_port (outs[physport], this)) {
891 // relax, even though its an error
896 if (_click_io->n_ports () > ChanCount::ZERO) {
897 _clicking = Config->get_clicking ();
903 Session::setup_bundles ()
907 RCUWriter<BundleList> writer (_bundles);
908 boost::shared_ptr<BundleList> b = writer.get_copy ();
909 for (BundleList::iterator i = b->begin(); i != b->end();) {
910 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
918 vector<string> inputs[DataType::num_types];
919 vector<string> outputs[DataType::num_types];
920 for (uint32_t i = 0; i < DataType::num_types; ++i) {
921 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
922 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
925 /* Create a set of Bundle objects that map
926 to the physical I/O currently available. We create both
927 mono and stereo bundles, so that the common cases of mono
928 and stereo tracks get bundles to put in their mixer strip
929 in / out menus. There may be a nicer way of achieving that;
930 it doesn't really scale that well to higher channel counts
933 /* mono output bundles */
935 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
937 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
939 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
941 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
944 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
945 c->add_channel (_("mono"), DataType::AUDIO);
946 c->set_port (0, outputs[DataType::AUDIO][np]);
948 add_bundle (c, false);
951 /* stereo output bundles */
953 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
954 if (np + 1 < outputs[DataType::AUDIO].size()) {
956 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
957 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
958 c->add_channel (_("L"), DataType::AUDIO);
959 c->set_port (0, outputs[DataType::AUDIO][np]);
960 c->add_channel (_("R"), DataType::AUDIO);
961 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
963 add_bundle (c, false);
967 /* mono input bundles */
969 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
971 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
973 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
975 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
978 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
979 c->add_channel (_("mono"), DataType::AUDIO);
980 c->set_port (0, inputs[DataType::AUDIO][np]);
982 add_bundle (c, false);
985 /* stereo input bundles */
987 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
988 if (np + 1 < inputs[DataType::AUDIO].size()) {
990 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
992 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
993 c->add_channel (_("L"), DataType::AUDIO);
994 c->set_port (0, inputs[DataType::AUDIO][np]);
995 c->add_channel (_("R"), DataType::AUDIO);
996 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
998 add_bundle (c, false);
1002 /* MIDI input bundles */
1004 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1005 string n = inputs[DataType::MIDI][np];
1006 std::string pn = _engine.get_pretty_name_by_name (n);
1010 boost::erase_first (n, X_("alsa_pcm:"));
1012 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1013 c->add_channel ("", DataType::MIDI);
1014 c->set_port (0, inputs[DataType::MIDI][np]);
1015 add_bundle (c, false);
1018 /* MIDI output bundles */
1020 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1021 string n = outputs[DataType::MIDI][np];
1022 std::string pn = _engine.get_pretty_name_by_name (n);
1026 boost::erase_first (n, X_("alsa_pcm:"));
1028 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1029 c->add_channel ("", DataType::MIDI);
1030 c->set_port (0, outputs[DataType::MIDI][np]);
1031 add_bundle (c, false);
1034 // we trust the backend to only calls us if there's a change
1035 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1039 Session::auto_connect_master_bus ()
1041 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1045 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1046 // In this case it means "Multi Out" output mode
1047 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1051 /* if requested auto-connect the outputs to the first N physical ports.
1054 uint32_t limit = _master_out->n_outputs().n_total();
1055 vector<string> outputs[DataType::num_types];
1057 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1058 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1061 for (uint32_t n = 0; n < limit; ++n) {
1062 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1064 if (outputs[p->type()].size() > n) {
1065 connect_to = outputs[p->type()][n];
1068 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1069 if (_master_out->output()->connect (p, connect_to, this)) {
1070 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1079 Session::remove_monitor_section ()
1081 if (!_monitor_out || Profile->get_trx()) {
1085 /* force reversion to Solo-In-Place */
1086 Config->set_solo_control_is_listen_control (false);
1088 /* if we are auditioning, cancel it ... this is a workaround
1089 to a problem (auditioning does not execute the process graph,
1090 which is needed to remove routes when using >1 core for processing)
1095 /* Hold process lock while doing this so that we don't hear bits and
1096 * pieces of audio as we work on each route.
1099 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1101 /* Connect tracks to monitor section. Note that in an
1102 existing session, the internal sends will already exist, but we want the
1103 routes to notice that they connect to the control out specifically.
1107 boost::shared_ptr<RouteList> r = routes.reader ();
1108 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1110 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1112 if ((*x)->is_monitor()) {
1114 } else if ((*x)->is_master()) {
1117 (*x)->remove_aux_or_listen (_monitor_out);
1122 remove_route (_monitor_out);
1123 if (_state_of_the_state & Deletion) {
1127 auto_connect_master_bus ();
1130 auditioner->connect ();
1133 Config->ParameterChanged ("use-monitor-bus");
1137 Session::add_monitor_section ()
1141 if (_monitor_out || !_master_out || Profile->get_trx()) {
1145 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1151 BOOST_MARK_ROUTE(r);
1154 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1155 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1156 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1158 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1163 add_routes (rl, false, false, false);
1165 assert (_monitor_out);
1167 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1168 are undefined, at best.
1171 uint32_t limit = _monitor_out->n_inputs().n_audio();
1175 /* connect the inputs to the master bus outputs. this
1176 * represents a separate data feed from the internal sends from
1177 * each route. as of jan 2011, it allows the monitor section to
1178 * conditionally ignore either the internal sends or the normal
1179 * input feed, but we should really find a better way to do
1183 _master_out->output()->disconnect (this);
1185 for (uint32_t n = 0; n < limit; ++n) {
1186 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1187 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1190 string connect_to = o->name();
1191 if (_monitor_out->input()->connect (p, connect_to, this)) {
1192 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1200 /* if monitor section is not connected, connect it to physical outs
1203 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1205 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1207 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1210 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1212 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1213 Config->get_monitor_bus_preferred_bundle())
1219 /* Monitor bus is audio only */
1221 vector<string> outputs[DataType::num_types];
1223 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1224 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1227 uint32_t mod = outputs[DataType::AUDIO].size();
1228 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1232 for (uint32_t n = 0; n < limit; ++n) {
1234 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1236 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1237 connect_to = outputs[DataType::AUDIO][n % mod];
1240 if (!connect_to.empty()) {
1241 if (_monitor_out->output()->connect (p, connect_to, this)) {
1242 error << string_compose (
1243 _("cannot connect control output %1 to %2"),
1254 /* Hold process lock while doing this so that we don't hear bits and
1255 * pieces of audio as we work on each route.
1258 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1260 /* Connect tracks to monitor section. Note that in an
1261 existing session, the internal sends will already exist, but we want the
1262 routes to notice that they connect to the control out specifically.
1266 boost::shared_ptr<RouteList> rls = routes.reader ();
1268 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1270 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1272 if ((*x)->is_monitor()) {
1274 } else if ((*x)->is_master()) {
1277 (*x)->enable_monitor_send ();
1282 auditioner->connect ();
1284 Config->ParameterChanged ("use-monitor-bus");
1288 Session::reset_monitor_section ()
1290 /* Process lock should be held by the caller.*/
1292 if (!_monitor_out || Profile->get_trx()) {
1296 uint32_t limit = _master_out->n_outputs().n_audio();
1298 /* connect the inputs to the master bus outputs. this
1299 * represents a separate data feed from the internal sends from
1300 * each route. as of jan 2011, it allows the monitor section to
1301 * conditionally ignore either the internal sends or the normal
1302 * input feed, but we should really find a better way to do
1306 _master_out->output()->disconnect (this);
1307 _monitor_out->output()->disconnect (this);
1309 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1310 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1312 for (uint32_t n = 0; n < limit; ++n) {
1313 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1314 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1317 string connect_to = o->name();
1318 if (_monitor_out->input()->connect (p, connect_to, this)) {
1319 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1326 /* connect monitor section to physical outs
1329 if (Config->get_auto_connect_standard_busses()) {
1331 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1333 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1336 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1338 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1339 Config->get_monitor_bus_preferred_bundle())
1345 /* Monitor bus is audio only */
1347 vector<string> outputs[DataType::num_types];
1349 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1350 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1353 uint32_t mod = outputs[DataType::AUDIO].size();
1354 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1358 for (uint32_t n = 0; n < limit; ++n) {
1360 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1362 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1363 connect_to = outputs[DataType::AUDIO][n % mod];
1366 if (!connect_to.empty()) {
1367 if (_monitor_out->output()->connect (p, connect_to, this)) {
1368 error << string_compose (
1369 _("cannot connect control output %1 to %2"),
1380 /* Connect tracks to monitor section. Note that in an
1381 existing session, the internal sends will already exist, but we want the
1382 routes to notice that they connect to the control out specifically.
1386 boost::shared_ptr<RouteList> rls = routes.reader ();
1388 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1390 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1392 if ((*x)->is_monitor()) {
1394 } else if ((*x)->is_master()) {
1397 (*x)->enable_monitor_send ();
1403 Session::hookup_io ()
1405 /* stop graph reordering notifications from
1406 causing resorts, etc.
1409 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1413 /* we delay creating the auditioner till now because
1414 it makes its own connections to ports.
1418 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1420 throw failed_constructor ();
1422 a->use_new_diskstream ();
1426 catch (failed_constructor& err) {
1427 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1431 /* load bundles, which we may have postponed earlier on */
1432 if (_bundle_xml_node) {
1433 load_bundles (*_bundle_xml_node);
1434 delete _bundle_xml_node;
1437 /* Tell all IO objects to connect themselves together */
1439 IO::enable_connecting ();
1441 /* Now tell all "floating" ports to connect to whatever
1442 they should be connected to.
1445 AudioEngine::instance()->reconnect_ports ();
1447 /* Anyone who cares about input state, wake up and do something */
1449 IOConnectionsComplete (); /* EMIT SIGNAL */
1451 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1453 /* now handle the whole enchilada as if it was one
1454 graph reorder event.
1459 /* update the full solo state, which can't be
1460 correctly determined on a per-route basis, but
1461 needs the global overview that only the session
1465 update_route_solo_state ();
1469 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1471 boost::shared_ptr<Track> track = wp.lock ();
1476 boost::shared_ptr<Playlist> playlist;
1478 if ((playlist = track->playlist()) != 0) {
1479 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1480 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1481 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1486 Session::record_enabling_legal () const
1488 /* this used to be in here, but survey says.... we don't need to restrict it */
1489 // if (record_status() == Recording) {
1493 if (Config->get_all_safe()) {
1500 Session::set_track_monitor_input_status (bool yn)
1502 boost::shared_ptr<RouteList> rl = routes.reader ();
1503 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1504 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1505 if (tr && tr->record_enabled ()) {
1506 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1507 tr->request_input_monitoring (yn);
1513 Session::auto_punch_start_changed (Location* location)
1515 replace_event (SessionEvent::PunchIn, location->start());
1517 if (get_record_enabled() && config.get_punch_in()) {
1518 /* capture start has been changed, so save new pending state */
1519 save_state ("", true);
1524 Session::auto_punch_end_changed (Location* location)
1526 framepos_t when_to_stop = location->end();
1527 // when_to_stop += _worst_output_latency + _worst_input_latency;
1528 replace_event (SessionEvent::PunchOut, when_to_stop);
1532 Session::auto_punch_changed (Location* location)
1534 framepos_t when_to_stop = location->end();
1536 replace_event (SessionEvent::PunchIn, location->start());
1537 //when_to_stop += _worst_output_latency + _worst_input_latency;
1538 replace_event (SessionEvent::PunchOut, when_to_stop);
1541 /** @param loc A loop location.
1542 * @param pos Filled in with the start time of the required fade-out (in session frames).
1543 * @param length Filled in with the length of the required fade-out.
1546 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1548 pos = max (loc->start(), loc->end() - 64);
1549 length = loc->end() - pos;
1553 Session::auto_loop_changed (Location* location)
1555 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1558 auto_loop_declick_range (location, dcp, dcl);
1560 if (transport_rolling() && play_loop) {
1562 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1564 // if (_transport_frame > location->end()) {
1566 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1567 // relocate to beginning of loop
1568 clear_events (SessionEvent::LocateRoll);
1570 request_locate (location->start(), true);
1573 else if (Config->get_seamless_loop() && !loop_changing) {
1575 // schedule a locate-roll to refill the diskstreams at the
1576 // previous loop end
1577 loop_changing = true;
1579 if (location->end() > last_loopend) {
1580 clear_events (SessionEvent::LocateRoll);
1581 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1587 clear_events (SessionEvent::AutoLoopDeclick);
1588 clear_events (SessionEvent::AutoLoop);
1591 /* possibly move playhead if not rolling; if we are rolling we'll move
1592 to the loop start on stop if that is appropriate.
1597 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1598 if (pos == location->start()) {
1599 request_locate (pos);
1604 last_loopend = location->end();
1609 Session::set_auto_punch_location (Location* location)
1613 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1614 punch_connections.drop_connections();
1615 existing->set_auto_punch (false, this);
1616 remove_event (existing->start(), SessionEvent::PunchIn);
1617 clear_events (SessionEvent::PunchOut);
1618 auto_punch_location_changed (0);
1623 if (location == 0) {
1627 if (location->end() <= location->start()) {
1628 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1632 punch_connections.drop_connections ();
1634 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1635 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1636 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1638 location->set_auto_punch (true, this);
1640 auto_punch_changed (location);
1642 auto_punch_location_changed (location);
1646 Session::set_session_extents (framepos_t start, framepos_t end)
1649 if ((existing = _locations->session_range_location()) == 0) {
1650 //if there is no existing session, we need to make a new session location (should never happen)
1651 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1655 error << _("Session: you can't use that location for session start/end)") << endmsg;
1659 existing->set( start, end );
1665 Session::set_auto_loop_location (Location* location)
1669 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1670 loop_connections.drop_connections ();
1671 existing->set_auto_loop (false, this);
1672 remove_event (existing->end(), SessionEvent::AutoLoop);
1675 auto_loop_declick_range (existing, dcp, dcl);
1676 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1677 auto_loop_location_changed (0);
1682 if (location == 0) {
1686 if (location->end() <= location->start()) {
1687 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1691 last_loopend = location->end();
1693 loop_connections.drop_connections ();
1695 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1696 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1697 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1698 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1700 location->set_auto_loop (true, this);
1702 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1703 // set all tracks to use internal looping
1704 boost::shared_ptr<RouteList> rl = routes.reader ();
1705 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1706 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1707 if (tr && !tr->hidden()) {
1708 tr->set_loop (location);
1713 /* take care of our stuff first */
1715 auto_loop_changed (location);
1717 /* now tell everyone else */
1719 auto_loop_location_changed (location);
1723 Session::update_marks (Location*)
1729 Session::update_skips (Location* loc, bool consolidate)
1731 if (_ignore_skips_updates) {
1735 Locations::LocationList skips;
1738 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1739 consolidate_skips (loc);
1742 sync_locations_to_skips ();
1748 Session::consolidate_skips (Location* loc)
1750 Locations::LocationList all_locations = _locations->list ();
1752 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1754 if (!(*l)->is_skip ()) {
1759 /* don't test against self */
1766 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1767 case Evoral::OverlapInternal:
1768 case Evoral::OverlapExternal:
1769 case Evoral::OverlapStart:
1770 case Evoral::OverlapEnd:
1771 /* adjust new location to cover existing one */
1772 loc->set_start (min (loc->start(), (*l)->start()));
1773 loc->set_end (max (loc->end(), (*l)->end()));
1774 /* we don't need this one any more */
1775 _locations->remove (*l);
1776 /* the location has been deleted, so remove reference to it in our local list */
1777 l = all_locations.erase (l);
1780 case Evoral::OverlapNone:
1788 Session::sync_locations_to_skips ()
1790 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1791 * Session::_sync_locations_to_skips() from the audioengine thread.
1793 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1797 Session::_sync_locations_to_skips ()
1799 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1801 Locations::LocationList const & locs (_locations->list());
1803 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1805 Location* location = *i;
1807 if (location->is_skip() && location->is_skipping()) {
1808 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1816 Session::location_added (Location *location)
1818 if (location->is_auto_punch()) {
1819 set_auto_punch_location (location);
1822 if (location->is_auto_loop()) {
1823 set_auto_loop_location (location);
1826 if (location->is_session_range()) {
1827 /* no need for any signal handling or event setting with the session range,
1828 because we keep a direct reference to it and use its start/end directly.
1830 _session_range_location = location;
1833 if (location->is_mark()) {
1834 /* listen for per-location signals that require us to do any * global updates for marks */
1836 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1837 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1838 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1839 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1842 if (location->is_skip()) {
1843 /* listen for per-location signals that require us to update skip-locate events */
1845 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1846 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1847 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1848 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1850 update_skips (location, true);
1857 Session::location_removed (Location *location)
1859 if (location->is_auto_loop()) {
1860 set_auto_loop_location (0);
1861 set_track_loop (false);
1864 if (location->is_auto_punch()) {
1865 set_auto_punch_location (0);
1868 if (location->is_session_range()) {
1869 /* this is never supposed to happen */
1870 error << _("programming error: session range removed!") << endl;
1873 if (location->is_skip()) {
1875 update_skips (location, false);
1882 Session::locations_changed ()
1884 _locations->apply (*this, &Session::_locations_changed);
1888 Session::_locations_changed (const Locations::LocationList& locations)
1890 /* There was some mass-change in the Locations object.
1892 We might be re-adding a location here but it doesn't actually matter
1893 for all the locations that the Session takes an interest in.
1897 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1898 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1899 location_added (*i);
1903 update_skips (NULL, false);
1907 Session::enable_record ()
1909 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1910 /* no recording at anything except normal speed */
1915 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1917 if (rs == Recording) {
1921 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1923 _last_record_location = _transport_frame;
1924 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1926 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1927 set_track_monitor_input_status (true);
1930 RecordStateChanged ();
1937 Session::set_all_tracks_record_enabled (bool enable )
1939 boost::shared_ptr<RouteList> rl = routes.reader();
1940 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1941 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1943 tr->set_record_enabled (enable, Controllable::NoGroup);
1950 Session::disable_record (bool rt_context, bool force)
1954 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1956 if (!Config->get_latched_record_enable () || force) {
1957 g_atomic_int_set (&_record_status, Disabled);
1958 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1960 if (rs == Recording) {
1961 g_atomic_int_set (&_record_status, Enabled);
1965 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1966 set_track_monitor_input_status (false);
1969 RecordStateChanged (); /* emit signal */
1972 remove_pending_capture_state ();
1978 Session::step_back_from_record ()
1980 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1982 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1983 set_track_monitor_input_status (false);
1986 RecordStateChanged (); /* emit signal */
1991 Session::maybe_enable_record ()
1993 if (_step_editors > 0) {
1997 g_atomic_int_set (&_record_status, Enabled);
1999 /* This function is currently called from somewhere other than an RT thread.
2000 This save_state() call therefore doesn't impact anything. Doing it here
2001 means that we save pending state of which sources the next record will use,
2002 which gives us some chance of recovering from a crash during the record.
2005 save_state ("", true);
2007 if (_transport_speed) {
2008 if (!config.get_punch_in()) {
2012 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2013 RecordStateChanged (); /* EMIT SIGNAL */
2020 Session::audible_frame () const
2026 offset = worst_playback_latency ();
2028 if (synced_to_engine()) {
2029 /* Note: this is basically just sync-to-JACK */
2030 tf = _engine.transport_frame();
2032 tf = _transport_frame;
2037 if (!non_realtime_work_pending()) {
2041 /* Check to see if we have passed the first guaranteed
2042 audible frame past our last start position. if not,
2043 return that last start point because in terms
2044 of audible frames, we have not moved yet.
2046 `Start position' in this context means the time we last
2047 either started, located, or changed transport direction.
2050 if (_transport_speed > 0.0f) {
2052 if (!play_loop || !have_looped) {
2053 if (tf < _last_roll_or_reversal_location + offset) {
2054 return _last_roll_or_reversal_location;
2062 } else if (_transport_speed < 0.0f) {
2064 /* XXX wot? no backward looping? */
2066 if (tf > _last_roll_or_reversal_location - offset) {
2067 return _last_roll_or_reversal_location;
2079 Session::set_frame_rate (framecnt_t frames_per_second)
2081 /** \fn void Session::set_frame_size(framecnt_t)
2082 the AudioEngine object that calls this guarantees
2083 that it will not be called while we are also in
2084 ::process(). Its fine to do things that block
2088 if (_base_frame_rate == 0) {
2089 _base_frame_rate = frames_per_second;
2091 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2092 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2094 _nominal_frame_rate = frames_per_second;
2099 reset_write_sources (false);
2101 // XXX we need some equivalent to this, somehow
2102 // SndFileSource::setup_standard_crossfades (frames_per_second);
2106 /* XXX need to reset/reinstantiate all LADSPA plugins */
2110 Session::set_block_size (pframes_t nframes)
2112 /* the AudioEngine guarantees
2113 that it will not be called while we are also in
2114 ::process(). It is therefore fine to do things that block
2119 current_block_size = nframes;
2123 boost::shared_ptr<RouteList> r = routes.reader ();
2125 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2126 (*i)->set_block_size (nframes);
2129 boost::shared_ptr<RouteList> rl = routes.reader ();
2130 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2131 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2133 tr->set_block_size (nframes);
2137 set_worst_io_latencies ();
2143 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2145 boost::shared_ptr<Route> r2;
2147 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2148 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2152 /* make a copy of the existing list of routes that feed r1 */
2154 Route::FedBy existing (r1->fed_by());
2156 /* for each route that feeds r1, recurse, marking it as feeding
2160 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2161 if (!(r2 = i->r.lock ())) {
2162 /* (*i) went away, ignore it */
2166 /* r2 is a route that feeds r1 which somehow feeds base. mark
2167 base as being fed by r2
2170 rbase->add_fed_by (r2, i->sends_only);
2174 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2178 if (r1->feeds (r2) && r2->feeds (r1)) {
2182 /* now recurse, so that we can mark base as being fed by
2183 all routes that feed r2
2186 trace_terminal (r2, rbase);
2193 Session::resort_routes ()
2195 /* don't do anything here with signals emitted
2196 by Routes during initial setup or while we
2197 are being destroyed.
2200 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2204 if (_route_deletion_in_progress) {
2209 RCUWriter<RouteList> writer (routes);
2210 boost::shared_ptr<RouteList> r = writer.get_copy ();
2211 resort_routes_using (r);
2212 /* writer goes out of scope and forces update */
2216 if (DEBUG_ENABLED(DEBUG::Graph)) {
2217 boost::shared_ptr<RouteList> rl = routes.reader ();
2218 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2219 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2221 const Route::FedBy& fb ((*i)->fed_by());
2223 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2224 boost::shared_ptr<Route> sf = f->r.lock();
2226 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2235 /** This is called whenever we need to rebuild the graph of how we will process
2237 * @param r List of routes, in any order.
2241 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2243 /* We are going to build a directed graph of our routes;
2244 this is where the edges of that graph are put.
2249 /* Go through all routes doing two things:
2251 * 1. Collect the edges of the route graph. Each of these edges
2252 * is a pair of routes, one of which directly feeds the other
2253 * either by a JACK connection or by an internal send.
2255 * 2. Begin the process of making routes aware of which other
2256 * routes directly or indirectly feed them. This information
2257 * is used by the solo code.
2260 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2262 /* Clear out the route's list of direct or indirect feeds */
2263 (*i)->clear_fed_by ();
2265 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2267 bool via_sends_only;
2269 /* See if this *j feeds *i according to the current state of the JACK
2270 connections and internal sends.
2272 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2273 /* add the edge to the graph (part #1) */
2274 edges.add (*j, *i, via_sends_only);
2275 /* tell the route (for part #2) */
2276 (*i)->add_fed_by (*j, via_sends_only);
2281 /* Attempt a topological sort of the route graph */
2282 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2284 if (sorted_routes) {
2285 /* We got a satisfactory topological sort, so there is no feedback;
2288 Note: the process graph rechain does not require a
2289 topologically-sorted list, but hey ho.
2291 if (_process_graph) {
2292 _process_graph->rechain (sorted_routes, edges);
2295 _current_route_graph = edges;
2297 /* Complete the building of the routes' lists of what directly
2298 or indirectly feeds them.
2300 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2301 trace_terminal (*i, *i);
2304 *r = *sorted_routes;
2307 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2308 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2309 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2310 (*i)->name(), (*i)->order_key ()));
2314 SuccessfulGraphSort (); /* EMIT SIGNAL */
2317 /* The topological sort failed, so we have a problem. Tell everyone
2318 and stick to the old graph; this will continue to be processed, so
2319 until the feedback is fixed, what is played back will not quite
2320 reflect what is actually connected. Note also that we do not
2321 do trace_terminal here, as it would fail due to an endless recursion,
2322 so the solo code will think that everything is still connected
2326 FeedbackDetected (); /* EMIT SIGNAL */
2331 /** Find a route name starting with \a base, maybe followed by the
2332 * lowest \a id. \a id will always be added if \a definitely_add_number
2333 * is true on entry; otherwise it will only be added if required
2334 * to make the name unique.
2336 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2337 * The available route name with the lowest ID will be used, and \a id
2338 * will be set to the ID.
2340 * \return false if a route name could not be found, and \a track_name
2341 * and \a id do not reflect a free route name.
2344 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2346 /* the base may conflict with ports that do not belong to existing
2347 routes, but hidden objects like the click track. So check port names
2348 before anything else.
2351 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2352 if (base == *reserved) {
2353 /* Check if this reserved name already exists, and if
2354 so, disallow it without a numeric suffix.
2356 if (route_by_name (*reserved)) {
2357 definitely_add_number = true;
2366 if (!definitely_add_number && route_by_name (base) == 0) {
2367 /* juse use the base */
2373 name = string_compose ("%1 %2", base, id);
2375 if (route_by_name (name) == 0) {
2381 } while (id < (UINT_MAX-1));
2386 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2388 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2390 in = ChanCount::ZERO;
2391 out = ChanCount::ZERO;
2393 boost::shared_ptr<RouteList> r = routes.reader ();
2395 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2396 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2397 if (tr && !tr->is_auditioner()) {
2398 in += tr->n_inputs();
2399 out += tr->n_outputs();
2405 Session::default_track_name_pattern (DataType t)
2408 case DataType::AUDIO:
2409 if (Profile->get_trx()) {
2416 case DataType::MIDI:
2423 /** Caller must not hold process lock
2424 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2425 * @param instrument plugin info for the instrument to insert pre-fader, if any
2427 list<boost::shared_ptr<MidiTrack> >
2428 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2429 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template, Plugin::PresetRecord* pset)
2432 uint32_t track_id = 0;
2434 RouteList new_routes;
2435 list<boost::shared_ptr<MidiTrack> > ret;
2437 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2438 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2441 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2442 error << "cannot find name for new midi track" << endmsg;
2446 boost::shared_ptr<MidiTrack> track;
2449 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2451 if (track->init ()) {
2455 if (Profile->get_mixbus ()) {
2456 track->set_strict_io (true);
2459 track->use_new_diskstream();
2461 BOOST_MARK_TRACK (track);
2464 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2465 if (track->input()->ensure_io (input, false, this)) {
2466 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2470 if (track->output()->ensure_io (output, false, this)) {
2471 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2476 track->non_realtime_input_change();
2479 route_group->add (track);
2482 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2484 if (Config->get_remote_model() == UserOrdered) {
2485 track->set_remote_control_id (next_control_id());
2488 new_routes.push_back (track);
2489 ret.push_back (track);
2491 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2494 catch (failed_constructor &err) {
2495 error << _("Session: could not create new midi track.") << endmsg;
2499 catch (AudioEngine::PortRegistrationFailure& pfe) {
2501 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;
2509 if (!new_routes.empty()) {
2510 StateProtector sp (this);
2511 if (Profile->get_trx()) {
2512 add_routes (new_routes, false, false, false);
2514 add_routes (new_routes, true, true, false);
2518 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2519 PluginPtr plugin = instrument->load (*this);
2521 plugin->load_preset (*pset);
2523 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2524 (*r)->add_processor (p, PreFader);
2534 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset)
2537 uint32_t bus_id = 0;
2541 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2544 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2545 error << "cannot find name for new midi bus" << endmsg;
2550 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
2556 if (Profile->get_mixbus ()) {
2557 bus->set_strict_io (true);
2560 BOOST_MARK_ROUTE(bus);
2563 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2565 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2566 error << _("cannot configure new midi bus input") << endmsg;
2571 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2572 error << _("cannot configure new midi bus output") << endmsg;
2578 route_group->add (bus);
2580 if (Config->get_remote_model() == UserOrdered) {
2581 bus->set_remote_control_id (next_control_id());
2584 ret.push_back (bus);
2585 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2589 catch (failed_constructor &err) {
2590 error << _("Session: could not create new audio route.") << endmsg;
2594 catch (AudioEngine::PortRegistrationFailure& pfe) {
2595 error << pfe.what() << endmsg;
2605 StateProtector sp (this);
2606 add_routes (ret, false, false, false);
2609 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2610 PluginPtr plugin = instrument->load (*this);
2612 plugin->load_preset (*pset);
2614 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2615 (*r)->add_processor (p, PreFader);
2626 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2628 boost::shared_ptr<Route> midi_track (wmt.lock());
2634 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2636 if (change.after.n_audio() <= change.before.n_audio()) {
2640 /* new audio ports: make sure the audio goes somewhere useful,
2641 * unless the user has no-auto-connect selected.
2643 * The existing ChanCounts don't matter for this call as they are only
2644 * to do with matching input and output indices, and we are only changing
2647 auto_connect_route (midi_track, false, ChanCount(), change.before);
2651 #ifdef USE_TRACKS_CODE_FEATURES
2654 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2656 return route1->remote_control_id() < route2->remote_control_id();
2660 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2662 // it is not allowed to perform connection
2663 if (!IO::connecting_legal) {
2667 // if we are deleting routes we will call this once at the end
2668 if (_route_deletion_in_progress) {
2672 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2678 // We need to disconnect the route's inputs and outputs first
2679 // basing on autoconnect configuration
2680 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2681 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2683 ChanCount existing_inputs;
2684 ChanCount existing_outputs;
2685 count_existing_track_channels (existing_inputs, existing_outputs);
2687 //ChanCount inputs = ChanCount::ZERO;
2688 //ChanCount outputs = ChanCount::ZERO;
2690 RouteList existing_routes = *routes.reader ();
2691 existing_routes.sort (compare_routes_by_remote_id);
2694 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2696 vector<string> physinputs;
2697 vector<string> physoutputs;
2699 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2700 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2702 uint32_t input_n = 0;
2703 uint32_t output_n = 0;
2704 RouteList::iterator rIter = existing_routes.begin();
2705 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2706 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2707 for (; rIter != existing_routes.end(); ++rIter) {
2708 if (*rIter == _master_out || *rIter == _monitor_out ) {
2712 if (current_output_auto_connection == AutoConnectPhysical) {
2713 (*rIter)->amp()->deactivate();
2714 } else if (current_output_auto_connection == AutoConnectMaster) {
2715 (*rIter)->amp()->activate();
2718 if (reconnectIputs) {
2719 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2721 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2723 if (current_input_auto_connection & AutoConnectPhysical) {
2725 if ( input_n == physinputs.size() ) {
2729 string port = physinputs[input_n];
2731 if (port.empty() ) {
2732 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2735 //GZ: check this; could be heavy
2736 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2742 if (reconnectOutputs) {
2744 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2745 if (current_output_auto_connection & AutoConnectPhysical) {
2747 //GZ: check this; could be heavy
2748 (*rIter)->output()->disconnect (this);
2749 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2751 //GZ: check this; could be heavy
2752 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2754 } else if (current_output_auto_connection & AutoConnectMaster){
2756 if (!reconnect_master) {
2760 //GZ: check this; could be heavy
2761 (*rIter)->output()->disconnect (this);
2764 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2765 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2767 error << error << "Master bus is not available" << endmsg;
2772 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2773 if (current_output_auto_connection & AutoConnectPhysical) {
2775 if ( output_n == physoutputs.size() ) {
2779 string port = physoutputs[output_n];
2781 if (port.empty() ) {
2782 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2785 //GZ: check this; could be heavy
2786 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2789 } else if (current_output_auto_connection & AutoConnectMaster) {
2791 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2795 // connect to master bus
2796 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2798 if (port.empty() ) {
2799 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2803 //GZ: check this; could be heavy
2804 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2811 _master_out->output()->disconnect (this);
2812 auto_connect_master_bus ();
2817 session_routes_reconnected (); /* EMIT SIGNAL */
2821 Session::reconnect_midi_scene_ports(bool inputs)
2825 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2827 scene_in_ptr->disconnect_all ();
2829 std::vector<EngineStateController::MidiPortState> midi_port_states;
2830 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2832 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2834 for (; state_iter != midi_port_states.end(); ++state_iter) {
2835 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2836 scene_in_ptr->connect (state_iter->name);
2843 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2845 if (scene_out_ptr ) {
2846 scene_out_ptr->disconnect_all ();
2848 std::vector<EngineStateController::MidiPortState> midi_port_states;
2849 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2851 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2853 for (; state_iter != midi_port_states.end(); ++state_iter) {
2854 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2855 scene_out_ptr->connect (state_iter->name);
2863 Session::reconnect_mtc_ports ()
2865 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2871 mtc_in_ptr->disconnect_all ();
2873 std::vector<EngineStateController::MidiPortState> midi_port_states;
2874 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2876 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2878 for (; state_iter != midi_port_states.end(); ++state_iter) {
2879 if (state_iter->available && state_iter->mtc_in) {
2880 mtc_in_ptr->connect (state_iter->name);
2884 if (!_midi_ports->mtc_input_port ()->connected () &&
2885 config.get_external_sync () &&
2886 (Config->get_sync_source () == MTC) ) {
2887 config.set_external_sync (false);
2890 if ( ARDOUR::Profile->get_trx () ) {
2891 // Tracks need this signal to update timecode_source_dropdown
2892 MtcOrLtcInputPortChanged (); //emit signal
2897 Session::reconnect_mmc_ports(bool inputs)
2899 if (inputs ) { // get all enabled midi input ports
2901 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2903 mmc_in_ptr->disconnect_all ();
2904 std::vector<std::string> enabled_midi_inputs;
2905 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2907 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2909 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2910 mmc_in_ptr->connect (*port_iter);
2914 } else { // get all enabled midi output ports
2916 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2918 mmc_out_ptr->disconnect_all ();
2919 std::vector<std::string> enabled_midi_outputs;
2920 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2922 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2924 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2925 mmc_out_ptr->connect (*port_iter);
2933 /** Caller must not hold process lock
2934 * @param name_template string to use for the start of the name, or "" to use "Audio".
2936 list< boost::shared_ptr<AudioTrack> >
2937 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2938 uint32_t how_many, string name_template)
2941 uint32_t track_id = 0;
2943 RouteList new_routes;
2944 list<boost::shared_ptr<AudioTrack> > ret;
2946 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2947 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2951 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2952 error << "cannot find name for new audio track" << endmsg;
2956 boost::shared_ptr<AudioTrack> track;
2959 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2961 if (track->init ()) {
2965 if (Profile->get_mixbus ()) {
2966 track->set_strict_io (true);
2970 if (ARDOUR::Profile->get_trx ()) {
2971 // TRACKS considers it's not a USE CASE, it's
2972 // a piece of behavior of the session model:
2974 // Gain for a newly created route depends on
2975 // the current output_auto_connect mode:
2977 // 0 for Stereo Out mode
2979 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2980 track->set_gain (dB_to_coefficient (0), Controllable::NoGroup);
2984 track->use_new_diskstream();
2986 BOOST_MARK_TRACK (track);
2989 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2991 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2992 error << string_compose (
2993 _("cannot configure %1 in/%2 out configuration for new audio track"),
2994 input_channels, output_channels)
2999 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3000 error << string_compose (
3001 _("cannot configure %1 in/%2 out configuration for new audio track"),
3002 input_channels, output_channels)
3009 route_group->add (track);
3012 track->non_realtime_input_change();
3014 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3015 if (Config->get_remote_model() == UserOrdered) {
3016 track->set_remote_control_id (next_control_id());
3019 new_routes.push_back (track);
3020 ret.push_back (track);
3022 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3025 catch (failed_constructor &err) {
3026 error << _("Session: could not create new audio track.") << endmsg;
3030 catch (AudioEngine::PortRegistrationFailure& pfe) {
3032 error << pfe.what() << endmsg;
3040 if (!new_routes.empty()) {
3041 StateProtector sp (this);
3042 if (Profile->get_trx()) {
3043 add_routes (new_routes, false, false, false);
3045 add_routes (new_routes, true, true, false);
3052 /** Caller must not hold process lock.
3053 * @param name_template string to use for the start of the name, or "" to use "Bus".
3056 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
3059 uint32_t bus_id = 0;
3063 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3066 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3067 error << "cannot find name for new audio bus" << endmsg;
3072 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3078 if (Profile->get_mixbus ()) {
3079 bus->set_strict_io (true);
3082 BOOST_MARK_ROUTE(bus);
3085 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3087 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3088 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3089 input_channels, output_channels)
3095 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3096 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3097 input_channels, output_channels)
3104 route_group->add (bus);
3106 if (Config->get_remote_model() == UserOrdered) {
3107 bus->set_remote_control_id (next_control_id());
3110 bus->add_internal_return ();
3112 ret.push_back (bus);
3114 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3120 catch (failed_constructor &err) {
3121 error << _("Session: could not create new audio route.") << endmsg;
3125 catch (AudioEngine::PortRegistrationFailure& pfe) {
3126 error << pfe.what() << endmsg;
3136 StateProtector sp (this);
3137 if (Profile->get_trx()) {
3138 add_routes (ret, false, false, false);
3140 add_routes (ret, false, true, true); // autoconnect // outputs only
3149 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3153 if (!tree.read (template_path.c_str())) {
3157 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3161 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3164 uint32_t control_id;
3165 uint32_t number = 0;
3166 const uint32_t being_added = how_many;
3167 /* This will prevent the use of any existing XML-provided PBD::ID
3170 Stateful::ForceIDRegeneration force_ids;
3171 IO::disable_connecting ();
3173 control_id = next_control_id ();
3177 /* We're going to modify the node contents a bit so take a
3178 * copy. The node may be re-used when duplicating more than once.
3181 XMLNode node_copy (node);
3186 if (!name_base.empty()) {
3188 /* if we're adding more than one routes, force
3189 * all the names of the new routes to be
3190 * numbered, via the final parameter.
3193 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3194 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3200 string const route_name = node_copy.property(X_("name"))->value ();
3202 /* generate a new name by adding a number to the end of the template name */
3203 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3204 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3205 abort(); /*NOTREACHED*/
3209 /* set this name in the XML description that we are about to use */
3211 bool rename_playlist;
3214 rename_playlist = true;
3219 rename_playlist = false;
3222 Route::set_name_in_state (node_copy, name, rename_playlist);
3224 /* trim bitslots from listen sends so that new ones are used */
3225 XMLNodeList children = node_copy.children ();
3226 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3227 if ((*i)->name() == X_("Processor")) {
3228 /* ForceIDRegeneration does not catch the following */
3229 XMLProperty const * role = (*i)->property (X_("role"));
3230 XMLProperty const * type = (*i)->property (X_("type"));
3231 if (role && role->value() == X_("Aux")) {
3232 /* check if the target bus exists.
3233 * we should not save aux-sends in templates.
3235 XMLProperty const * target = (*i)->property (X_("target"));
3237 (*i)->add_property ("type", "dangling-aux-send");
3240 boost::shared_ptr<Route> r = route_by_id (target->value());
3241 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3242 (*i)->add_property ("type", "dangling-aux-send");
3246 if (role && role->value() == X_("Listen")) {
3247 (*i)->remove_property (X_("bitslot"));
3249 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3251 Delivery::Role xrole;
3252 uint32_t bitslot = 0;
3253 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3254 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3255 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3256 (*i)->remove_property (X_("bitslot"));
3257 (*i)->remove_property (X_("name"));
3258 (*i)->add_property ("bitslot", buf);
3259 (*i)->add_property ("name", name);
3261 else if (type && type->value() == X_("return")) {
3262 // Return::set_state() generates a new one
3263 (*i)->remove_property (X_("bitslot"));
3265 else if (type && type->value() == X_("port")) {
3266 // PortInsert::set_state() handles the bitslot
3267 (*i)->remove_property (X_("bitslot"));
3268 (*i)->add_property ("ignore-name", "1");
3273 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3276 error << _("Session: cannot create track/bus from template description") << endmsg;
3280 if (boost::dynamic_pointer_cast<Track>(route)) {
3281 /* force input/output change signals so that the new diskstream
3282 picks up the configuration of the route. During session
3283 loading this normally happens in a different way.
3286 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3288 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3289 change.after = route->input()->n_ports();
3290 route->input()->changed (change, this);
3291 change.after = route->output()->n_ports();
3292 route->output()->changed (change, this);
3295 route->set_remote_control_id (control_id);
3298 boost::shared_ptr<Track> track;
3300 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3303 track->use_new_playlist ();
3306 track->use_copy_playlist ();
3313 ret.push_back (route);
3315 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3318 catch (failed_constructor &err) {
3319 error << _("Session: could not create new route from template") << endmsg;
3323 catch (AudioEngine::PortRegistrationFailure& pfe) {
3324 error << pfe.what() << endmsg;
3333 StateProtector sp (this);
3334 if (Profile->get_trx()) {
3335 add_routes (ret, false, false, false);
3337 add_routes (ret, true, true, false);
3339 IO::enable_connecting ();
3346 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3349 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3350 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3353 error << _("Adding new tracks/busses failed") << endmsg;
3358 update_latency (true);
3359 update_latency (false);
3364 save_state (_current_snapshot_name);
3367 reassign_track_numbers();
3369 update_route_record_state ();
3371 RouteAdded (new_routes); /* EMIT SIGNAL */
3375 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3377 ChanCount existing_inputs;
3378 ChanCount existing_outputs;
3379 uint32_t order = next_control_id();
3382 if (_order_hint > -1) {
3383 order = _order_hint;
3387 count_existing_track_channels (existing_inputs, existing_outputs);
3390 RCUWriter<RouteList> writer (routes);
3391 boost::shared_ptr<RouteList> r = writer.get_copy ();
3392 r->insert (r->end(), new_routes.begin(), new_routes.end());
3394 /* if there is no control out and we're not in the middle of loading,
3395 * resort the graph here. if there is a control out, we will resort
3396 * toward the end of this method. if we are in the middle of loading,
3397 * we will resort when done.
3400 if (!_monitor_out && IO::connecting_legal) {
3401 resort_routes_using (r);
3405 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3407 boost::weak_ptr<Route> wpr (*x);
3408 boost::shared_ptr<Route> r (*x);
3410 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
3411 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3412 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3413 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3414 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3415 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3417 if (r->is_master()) {
3421 if (r->is_monitor()) {
3425 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3427 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3428 track_playlist_changed (boost::weak_ptr<Track> (tr));
3429 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3431 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3433 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3434 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3438 if (input_auto_connect || output_auto_connect) {
3439 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3440 existing_inputs += r->n_inputs();
3441 existing_outputs += r->n_outputs();
3444 /* order keys are a GUI responsibility but we need to set up
3445 reasonable defaults because they also affect the remote control
3446 ID in most situations.
3449 if (!r->has_order_key ()) {
3450 if (r->is_auditioner()) {
3451 /* use an arbitrarily high value */
3452 r->set_order_key (UINT_MAX);
3454 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3455 r->set_order_key (order);
3463 if (_monitor_out && IO::connecting_legal) {
3464 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3466 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3467 if ((*x)->is_monitor()) {
3469 } else if ((*x)->is_master()) {
3472 (*x)->enable_monitor_send ();
3479 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3481 boost::shared_ptr<RouteList> r = routes.reader ();
3482 boost::shared_ptr<Send> s;
3484 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3485 if ((s = (*i)->internal_send_for (dest)) != 0) {
3486 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3492 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3494 boost::shared_ptr<RouteList> r = routes.reader ();
3495 boost::shared_ptr<Send> s;
3497 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3498 if ((s = (*i)->internal_send_for (dest)) != 0) {
3499 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3505 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3507 boost::shared_ptr<RouteList> r = routes.reader ();
3508 boost::shared_ptr<Send> s;
3510 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3511 if ((s = (*i)->internal_send_for (dest)) != 0) {
3512 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3517 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3519 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3521 boost::shared_ptr<RouteList> r = routes.reader ();
3522 boost::shared_ptr<RouteList> t (new RouteList);
3524 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3525 /* no MIDI sends because there are no MIDI busses yet */
3526 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3531 add_internal_sends (dest, p, t);
3535 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3537 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3538 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3543 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3545 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3549 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3551 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3555 if (!dest->internal_return()) {
3556 dest->add_internal_return ();
3559 sender->add_aux_send (dest, before);
3565 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3567 { // RCU Writer scope
3568 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3569 RCUWriter<RouteList> writer (routes);
3570 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3573 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3575 if (*iter == _master_out) {
3579 (*iter)->set_solo (false, Controllable::NoGroup);
3583 /* deleting the master out seems like a dumb
3584 idea, but its more of a UI policy issue
3588 if (*iter == _master_out) {
3589 _master_out = boost::shared_ptr<Route> ();
3592 if (*iter == _monitor_out) {
3593 _monitor_out.reset ();
3596 // We need to disconnect the route's inputs and outputs
3598 (*iter)->input()->disconnect (0);
3599 (*iter)->output()->disconnect (0);
3601 /* if the route had internal sends sending to it, remove them */
3602 if ((*iter)->internal_return()) {
3604 boost::shared_ptr<RouteList> r = routes.reader ();
3605 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3606 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3608 (*i)->remove_processor (s);
3613 /* if the monitoring section had a pointer to this route, remove it */
3614 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3615 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3616 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3617 (*iter)->remove_aux_or_listen (_monitor_out);
3620 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3621 if (mt && mt->step_editing()) {
3622 if (_step_editors > 0) {
3628 /* writer goes out of scope, forces route list update */
3630 } // end of RCU Writer scope
3632 update_route_solo_state ();
3633 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3634 update_latency_compensation ();
3637 /* Re-sort routes to remove the graph's current references to the one that is
3638 * going away, then flush old references out of the graph.
3639 * Wave Tracks: reconnect routes
3642 #ifdef USE_TRACKS_CODE_FEATURES
3643 reconnect_existing_routes(true, false);
3645 routes.flush (); // maybe unsafe, see below.
3649 if (_process_graph && !(_state_of_the_state & Deletion)) {
3650 _process_graph->clear_other_chain ();
3653 /* get rid of it from the dead wood collection in the route list manager */
3654 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3658 /* try to cause everyone to drop their references
3659 * and unregister ports from the backend
3662 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3663 (*iter)->drop_references ();
3666 if (_state_of_the_state & Deletion) {
3670 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3672 /* save the new state of the world */
3674 if (save_state (_current_snapshot_name)) {
3675 save_history (_current_snapshot_name);
3678 reassign_track_numbers();
3679 update_route_record_state ();
3683 Session::remove_route (boost::shared_ptr<Route> route)
3685 boost::shared_ptr<RouteList> rl (new RouteList);
3686 rl->push_back (route);
3691 Session::route_mute_changed ()
3697 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3699 boost::shared_ptr<Route> route = wpr.lock();
3701 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_listen_changed")) << endmsg;
3705 if (route->listening_via_monitor ()) {
3707 if (Config->get_exclusive_solo()) {
3709 RouteGroup* rg = route->route_group ();
3710 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3712 boost::shared_ptr<RouteList> r = routes.reader ();
3714 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3715 if ((*i) == route) {
3716 /* already changed */
3720 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3721 /* route does not get solo propagated to it */
3725 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3726 /* this route is a part of the same solo group as the route
3727 * that was changed. Changing that route did change or will
3728 * change all group members appropriately, so we can ignore it
3733 (*i)->set_listen (false, Controllable::NoGroup);
3739 } else if (_listen_cnt > 0) {
3744 update_route_solo_state ();
3747 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3749 boost::shared_ptr<Route> route = wpr.lock ();
3752 /* should not happen */
3753 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_isolated_changed")) << endmsg;
3757 bool send_changed = false;
3759 if (route->solo_isolated()) {
3760 if (_solo_isolated_cnt == 0) {
3761 send_changed = true;
3763 _solo_isolated_cnt++;
3764 } else if (_solo_isolated_cnt > 0) {
3765 _solo_isolated_cnt--;
3766 if (_solo_isolated_cnt == 0) {
3767 send_changed = true;
3772 IsolatedChanged (); /* EMIT SIGNAL */
3777 Session::route_solo_changed (bool self_solo_change, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3779 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3781 if (!self_solo_change) {
3782 // session doesn't care about changes to soloed-by-others
3786 boost::shared_ptr<Route> route = wpr.lock ();
3789 boost::shared_ptr<RouteList> r = routes.reader ();
3792 if (route->self_soloed()) {
3798 /* the route may be a member of a group that has shared-solo
3799 * semantics. If so, then all members of that group should follow the
3800 * solo of the changed route. But ... this is optional, controlled by a
3801 * Controllable::GroupControlDisposition.
3803 * The first argument to the signal that this method is connected to is the
3804 * GroupControlDisposition value that was used to change solo.
3806 * If the solo change was done with group semantics (either InverseGroup
3807 * (force the entire group to change even if the group shared solo is
3808 * disabled) or UseGroup (use the group, which may or may not have the
3809 * shared solo property enabled)) then as we propagate the change to
3810 * the entire session we should IGNORE THE GROUP that the changed route
3814 RouteGroup* rg = route->route_group ();
3815 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3817 if (delta == 1 && Config->get_exclusive_solo()) {
3819 /* new solo: disable all other solos, but not the group if its solo-enabled */
3821 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3823 if ((*i) == route) {
3824 /* already changed */
3828 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3829 /* route does not get solo propagated to it */
3833 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3834 /* this route is a part of the same solo group as the route
3835 * that was changed. Changing that route did change or will
3836 * change all group members appropriately, so we can ignore it
3842 (*i)->set_solo (false, group_override);
3846 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3848 RouteList uninvolved;
3850 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3852 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3853 bool via_sends_only;
3854 bool in_signal_flow;
3856 if ((*i) == route) {
3857 /* already changed */
3861 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3862 /* route does not get solo propagated to it */
3866 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3867 /* this route is a part of the same solo group as the route
3868 * that was changed. Changing that route did change or will
3869 * change all group members appropriately, so we can ignore it
3875 in_signal_flow = false;
3877 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3879 if ((*i)->feeds (route, &via_sends_only)) {
3880 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3881 if (!via_sends_only) {
3882 if (!route->soloed_by_others_upstream()) {
3883 (*i)->mod_solo_by_others_downstream (delta);
3885 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3888 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3890 in_signal_flow = true;
3892 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3895 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3897 if (route->feeds (*i, &via_sends_only)) {
3898 /* propagate solo upstream only if routing other than
3899 sends is involved, but do consider the other route
3900 (*i) to be part of the signal flow even if only
3903 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3907 route->soloed_by_others_downstream(),
3908 route->soloed_by_others_upstream()));
3909 if (!via_sends_only) {
3910 //NB. Triggers Invert Push, which handles soloed by downstream
3911 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3912 (*i)->mod_solo_by_others_upstream (delta);
3914 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3916 in_signal_flow = true;
3918 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3921 if (!in_signal_flow) {
3922 uninvolved.push_back (*i);
3926 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3928 update_route_solo_state (r);
3930 /* now notify that the mute state of the routes not involved in the signal
3931 pathway of the just-solo-changed route may have altered.
3934 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3935 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3936 (*i)->act_on_mute ();
3937 (*i)->mute_changed ();
3940 SoloChanged (); /* EMIT SIGNAL */
3945 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3947 /* now figure out if anything that matters is soloed (or is "listening")*/
3949 bool something_soloed = false;
3950 bool something_listening = false;
3951 uint32_t listeners = 0;
3952 uint32_t isolated = 0;
3955 r = routes.reader();
3958 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3959 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3960 something_soloed = true;
3963 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3964 if (Config->get_solo_control_is_listen_control()) {
3966 something_listening = true;
3968 (*i)->set_listen (false, Controllable::NoGroup);
3972 if ((*i)->solo_isolated()) {
3977 if (something_soloed != _non_soloed_outs_muted) {
3978 _non_soloed_outs_muted = something_soloed;
3979 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3982 if (something_listening != _listening) {
3983 _listening = something_listening;
3984 SoloActive (_listening);
3987 _listen_cnt = listeners;
3989 if (isolated != _solo_isolated_cnt) {
3990 _solo_isolated_cnt = isolated;
3991 IsolatedChanged (); /* EMIT SIGNAL */
3994 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3995 something_soloed, listeners, isolated));
3998 boost::shared_ptr<RouteList>
3999 Session::get_routes_with_internal_returns() const
4001 boost::shared_ptr<RouteList> r = routes.reader ();
4002 boost::shared_ptr<RouteList> rl (new RouteList);
4004 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4005 if ((*i)->internal_return ()) {
4013 Session::io_name_is_legal (const std::string& name)
4015 boost::shared_ptr<RouteList> r = routes.reader ();
4017 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4018 if (name == *reserved) {
4019 if (!route_by_name (*reserved)) {
4020 /* first instance of a reserved name is allowed */
4023 /* all other instances of a reserved name are not allowed */
4028 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4029 if ((*i)->name() == name) {
4033 if ((*i)->has_io_processor_named (name)) {
4042 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4045 vector<string> connections;
4047 /* if we are passed only a single route and we're not told to turn
4048 * others off, then just do the simple thing.
4051 if (flip_others == false && rl->size() == 1) {
4052 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4054 mt->set_input_active (onoff);
4059 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4061 PortSet& ps ((*rt)->input()->ports());
4063 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4064 p->get_connections (connections);
4067 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4068 routes_using_input_from (*s, rl2);
4071 /* scan all relevant routes to see if others are on or off */
4073 bool others_are_already_on = false;
4075 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4077 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4083 if ((*r) != (*rt)) {
4084 if (mt->input_active()) {
4085 others_are_already_on = true;
4088 /* this one needs changing */
4089 mt->set_input_active (onoff);
4095 /* globally reverse other routes */
4097 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4098 if ((*r) != (*rt)) {
4099 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4101 mt->set_input_active (!others_are_already_on);
4110 Session::routes_using_input_from (const string& str, RouteList& rl)
4112 boost::shared_ptr<RouteList> r = routes.reader();
4114 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4115 if ((*i)->input()->connected_to (str)) {
4121 boost::shared_ptr<Route>
4122 Session::route_by_name (string name)
4124 boost::shared_ptr<RouteList> r = routes.reader ();
4126 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4127 if ((*i)->name() == name) {
4132 return boost::shared_ptr<Route> ((Route*) 0);
4135 boost::shared_ptr<Route>
4136 Session::route_by_id (PBD::ID id)
4138 boost::shared_ptr<RouteList> r = routes.reader ();
4140 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4141 if ((*i)->id() == id) {
4146 return boost::shared_ptr<Route> ((Route*) 0);
4149 boost::shared_ptr<Processor>
4150 Session::processor_by_id (PBD::ID id) const
4152 boost::shared_ptr<RouteList> r = routes.reader ();
4154 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4155 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4161 return boost::shared_ptr<Processor> ();
4164 boost::shared_ptr<Track>
4165 Session::track_by_diskstream_id (PBD::ID id)
4167 boost::shared_ptr<RouteList> r = routes.reader ();
4169 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4170 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4171 if (t && t->using_diskstream_id (id)) {
4176 return boost::shared_ptr<Track> ();
4179 boost::shared_ptr<Route>
4180 Session::route_by_remote_id (uint32_t id)
4182 boost::shared_ptr<RouteList> r = routes.reader ();
4184 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4185 if ((*i)->remote_control_id() == id) {
4190 return boost::shared_ptr<Route> ((Route*) 0);
4194 boost::shared_ptr<Route>
4195 Session::route_by_selected_count (uint32_t id)
4197 boost::shared_ptr<RouteList> r = routes.reader ();
4199 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4200 /* NOT IMPLEMENTED */
4203 return boost::shared_ptr<Route> ((Route*) 0);
4208 Session::reassign_track_numbers ()
4212 RouteList r (*(routes.reader ()));
4213 SignalOrderRouteSorter sorter;
4216 StateProtector sp (this);
4218 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4219 if (boost::dynamic_pointer_cast<Track> (*i)) {
4220 (*i)->set_track_number(++tn);
4222 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4223 (*i)->set_track_number(--bn);
4226 const uint32_t decimals = ceilf (log10f (tn + 1));
4227 const bool decimals_changed = _track_number_decimals != decimals;
4228 _track_number_decimals = decimals;
4230 if (decimals_changed && config.get_track_name_number ()) {
4231 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4232 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4234 t->resync_track_name();
4237 // trigger GUI re-layout
4238 config.ParameterChanged("track-name-number");
4243 Session::playlist_region_added (boost::weak_ptr<Region> w)
4245 boost::shared_ptr<Region> r = w.lock ();
4250 /* These are the operations that are currently in progress... */
4251 list<GQuark> curr = _current_trans_quarks;
4254 /* ...and these are the operations during which we want to update
4255 the session range location markers.
4258 ops.push_back (Operations::capture);
4259 ops.push_back (Operations::paste);
4260 ops.push_back (Operations::duplicate_region);
4261 ops.push_back (Operations::insert_file);
4262 ops.push_back (Operations::insert_region);
4263 ops.push_back (Operations::drag_region_brush);
4264 ops.push_back (Operations::region_drag);
4265 ops.push_back (Operations::selection_grab);
4266 ops.push_back (Operations::region_fill);
4267 ops.push_back (Operations::fill_selection);
4268 ops.push_back (Operations::create_region);
4269 ops.push_back (Operations::region_copy);
4270 ops.push_back (Operations::fixed_time_region_copy);
4273 /* See if any of the current operations match the ones that we want */
4275 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4277 /* If so, update the session range markers */
4279 maybe_update_session_range (r->position (), r->last_frame ());
4283 /** Update the session range markers if a is before the current start or
4284 * b is after the current end.
4287 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4289 if (_state_of_the_state & Loading) {
4293 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4295 if (_session_range_location == 0) {
4297 set_session_range_location (a, b + session_end_marker_shift_samples);
4301 if (a < _session_range_location->start()) {
4302 _session_range_location->set_start (a);
4305 if (b > _session_range_location->end()) {
4306 _session_range_location->set_end (b);
4312 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4314 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4315 maybe_update_session_range (i->to, i->to + i->length);
4320 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4322 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4323 maybe_update_session_range (i->from, i->to);
4327 /* Region management */
4329 boost::shared_ptr<Region>
4330 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4332 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4333 RegionFactory::RegionMap::const_iterator i;
4334 boost::shared_ptr<Region> region;
4336 Glib::Threads::Mutex::Lock lm (region_lock);
4338 for (i = regions.begin(); i != regions.end(); ++i) {
4342 if (region->whole_file()) {
4344 if (child->source_equivalent (region)) {
4350 return boost::shared_ptr<Region> ();
4354 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4356 set<boost::shared_ptr<Region> > relevant_regions;
4358 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4359 RegionFactory::get_regions_using_source (*s, relevant_regions);
4362 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4363 set<boost::shared_ptr<Region> >::iterator tmp;
4368 playlists->destroy_region (*r);
4369 RegionFactory::map_remove (*r);
4371 (*r)->drop_sources ();
4372 (*r)->drop_references ();
4374 relevant_regions.erase (r);
4379 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4382 Glib::Threads::Mutex::Lock ls (source_lock);
4383 /* remove from the main source list */
4384 sources.erase ((*s)->id());
4387 (*s)->mark_for_remove ();
4388 (*s)->drop_references ();
4397 Session::remove_last_capture ()
4399 list<boost::shared_ptr<Source> > srcs;
4401 boost::shared_ptr<RouteList> rl = routes.reader ();
4402 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4403 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4408 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4411 srcs.insert (srcs.end(), l.begin(), l.end());
4416 destroy_sources (srcs);
4418 save_state (_current_snapshot_name);
4423 /* Source Management */
4426 Session::add_source (boost::shared_ptr<Source> source)
4428 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4429 pair<SourceMap::iterator,bool> result;
4431 entry.first = source->id();
4432 entry.second = source;
4435 Glib::Threads::Mutex::Lock lm (source_lock);
4436 result = sources.insert (entry);
4439 if (result.second) {
4441 /* yay, new source */
4443 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4446 if (!fs->within_session()) {
4447 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4453 boost::shared_ptr<AudioFileSource> afs;
4455 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4456 if (Config->get_auto_analyse_audio()) {
4457 Analyser::queue_source_for_analysis (source, false);
4461 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4466 Session::remove_source (boost::weak_ptr<Source> src)
4468 if (_state_of_the_state & Deletion) {
4472 SourceMap::iterator i;
4473 boost::shared_ptr<Source> source = src.lock();
4480 Glib::Threads::Mutex::Lock lm (source_lock);
4482 if ((i = sources.find (source->id())) != sources.end()) {
4487 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4489 /* save state so we don't end up with a session file
4490 referring to non-existent sources.
4493 save_state (_current_snapshot_name);
4497 boost::shared_ptr<Source>
4498 Session::source_by_id (const PBD::ID& id)
4500 Glib::Threads::Mutex::Lock lm (source_lock);
4501 SourceMap::iterator i;
4502 boost::shared_ptr<Source> source;
4504 if ((i = sources.find (id)) != sources.end()) {
4511 boost::shared_ptr<AudioFileSource>
4512 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4514 /* Restricted to audio files because only audio sources have channel
4518 Glib::Threads::Mutex::Lock lm (source_lock);
4520 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4521 boost::shared_ptr<AudioFileSource> afs
4522 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4524 if (afs && afs->path() == path && chn == afs->channel()) {
4529 return boost::shared_ptr<AudioFileSource>();
4532 boost::shared_ptr<MidiSource>
4533 Session::midi_source_by_path (const std::string& path) const
4535 /* Restricted to MIDI files because audio sources require a channel
4536 for unique identification, in addition to a path.
4539 Glib::Threads::Mutex::Lock lm (source_lock);
4541 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4542 boost::shared_ptr<MidiSource> ms
4543 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4544 boost::shared_ptr<FileSource> fs
4545 = boost::dynamic_pointer_cast<FileSource>(s->second);
4547 if (ms && fs && fs->path() == path) {
4552 return boost::shared_ptr<MidiSource>();
4556 Session::count_sources_by_origin (const string& path)
4559 Glib::Threads::Mutex::Lock lm (source_lock);
4561 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4562 boost::shared_ptr<FileSource> fs
4563 = boost::dynamic_pointer_cast<FileSource>(i->second);
4565 if (fs && fs->origin() == path) {
4574 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4576 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4577 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4579 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4584 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4586 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4588 if (Glib::path_is_absolute (filepath)) {
4590 /* rip the session dir from the audiofile source */
4592 string session_path;
4593 bool in_another_session = true;
4595 if (filepath.find (interchange_dir_string) != string::npos) {
4597 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4598 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4599 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4600 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4602 /* see if it is within our session */
4604 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4605 if (i->path == session_path) {
4606 in_another_session = false;
4611 in_another_session = false;
4615 if (in_another_session) {
4616 SessionDirectory sd (session_path);
4617 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4621 /* 1) if file belongs to this session
4622 * it may be a relative path (interchange/...)
4623 * or just basename (session_state, remove source)
4624 * -> just use the basename
4626 std::string filename = Glib::path_get_basename (filepath);
4629 /* 2) if the file is outside our session dir:
4630 * (imported but not copied) add the path for check-summming */
4632 path = Glib::path_get_dirname (filepath);
4635 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4639 Session::new_audio_source_path_for_embedded (const std::string& path)
4643 * we know that the filename is already unique because it exists
4644 * out in the filesystem.
4646 * However, when we bring it into the session, we could get a
4649 * Eg. two embedded files:
4654 * When merged into session, these collide.
4656 * There will not be a conflict with in-memory sources
4657 * because when the source was created we already picked
4658 * a unique name for it.
4660 * This collision is not likely to be common, but we have to guard
4661 * against it. So, if there is a collision, take the md5 hash of the
4662 * the path, and use that as the filename instead.
4665 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4666 string base = Glib::path_get_basename (path);
4667 string newpath = Glib::build_filename (sdir.sound_path(), base);
4669 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4673 md5.digestString (path.c_str());
4674 md5.writeToString ();
4675 base = md5.digestChars;
4677 string ext = get_suffix (path);
4684 newpath = Glib::build_filename (sdir.sound_path(), base);
4686 /* if this collides, we're screwed */
4688 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4689 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4698 /** Return true if there are no audio file sources that use @param name as
4699 * the filename component of their path.
4701 * Return false otherwise.
4703 * This method MUST ONLY be used to check in-session, mono files since it
4704 * hard-codes the channel of the audio file source we are looking for as zero.
4706 * If/when Ardour supports native files in non-mono formats, the logic here
4707 * will need to be revisited.
4710 Session::audio_source_name_is_unique (const string& name)
4712 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4713 vector<space_and_path>::iterator i;
4714 uint32_t existing = 0;
4716 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4718 /* note that we search *without* the extension so that
4719 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4720 in the event that this new name is required for
4721 a file format change.
4724 const string spath = *i;
4726 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4731 /* it is possible that we have the path already
4732 * assigned to a source that has not yet been written
4733 * (ie. the write source for a diskstream). we have to
4734 * check this in order to make sure that our candidate
4735 * path isn't used again, because that can lead to
4736 * two Sources point to the same file with different
4737 * notions of their removability.
4741 string possible_path = Glib::build_filename (spath, name);
4743 if (audio_source_by_path_and_channel (possible_path, 0)) {
4749 return (existing == 0);
4753 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)
4756 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4758 if (Profile->get_trx() && destructive) {
4760 sstr << setfill ('0') << setw (4) << cnt;
4761 sstr << legalized_base;
4763 sstr << legalized_base;
4765 if (take_required || related_exists) {
4777 } else if (nchan > 2) {
4782 /* XXX what? more than 26 channels! */
4793 /** Return a unique name based on \a base for a new internal audio source */
4795 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4798 string possible_name;
4799 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4801 bool some_related_source_name_exists = false;
4803 legalized = legalize_for_path (base);
4805 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4807 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4809 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4811 if (audio_source_name_is_unique (possible_name)) {
4815 some_related_source_name_exists = true;
4818 error << string_compose(
4819 _("There are already %1 recordings for %2, which I consider too many."),
4820 limit, base) << endmsg;
4822 throw failed_constructor();
4826 /* We've established that the new name does not exist in any session
4827 * directory, so now find out which one we should use for this new
4831 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4833 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4838 /** Return a unique name based on `base` for a new internal MIDI source */
4840 Session::new_midi_source_path (const string& base)
4843 char buf[PATH_MAX+1];
4844 const uint32_t limit = 10000;
4846 string possible_path;
4847 string possible_name;
4850 legalized = legalize_for_path (base);
4852 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4853 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4855 /* - the main session folder is the first in the vector.
4856 * - after checking all locations for file-name uniqueness,
4857 * we keep the one from the last iteration as new file name
4858 * - midi files are small and should just be kept in the main session-folder
4860 * -> reverse the array, check main session folder last and use that as location
4863 std::reverse(sdirs.begin(), sdirs.end());
4865 for (cnt = 1; cnt <= limit; ++cnt) {
4867 vector<space_and_path>::iterator i;
4868 uint32_t existing = 0;
4870 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4872 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4873 possible_name = buf;
4875 possible_path = Glib::build_filename (*i, possible_name);
4877 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4881 if (midi_source_by_path (possible_path)) {
4886 if (existing == 0) {
4891 error << string_compose(
4892 _("There are already %1 recordings for %2, which I consider too many."),
4893 limit, base) << endmsg;
4899 /* No need to "find best location" for software/app-based RAID, because
4900 MIDI is so small that we always put it in the same place.
4903 return possible_path;
4907 /** Create a new within-session audio source */
4908 boost::shared_ptr<AudioFileSource>
4909 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4911 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4913 if (!path.empty()) {
4914 return boost::dynamic_pointer_cast<AudioFileSource> (
4915 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4917 throw failed_constructor ();
4921 /** Create a new within-session MIDI source */
4922 boost::shared_ptr<MidiSource>
4923 Session::create_midi_source_for_session (string const & basic_name)
4925 const string path = new_midi_source_path (basic_name);
4927 if (!path.empty()) {
4928 return boost::dynamic_pointer_cast<SMFSource> (
4929 SourceFactory::createWritable (
4930 DataType::MIDI, *this, path, false, frame_rate()));
4932 throw failed_constructor ();
4936 /** Create a new within-session MIDI source */
4937 boost::shared_ptr<MidiSource>
4938 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4940 /* the caller passes in the track the source will be used in,
4941 so that we can keep the numbering sane.
4943 Rationale: a track with the name "Foo" that has had N
4944 captures carried out so far will ALREADY have a write source
4945 named "Foo-N+1.mid" waiting to be used for the next capture.
4947 If we call new_midi_source_name() we will get "Foo-N+2". But
4948 there is no region corresponding to "Foo-N+1", so when
4949 "Foo-N+2" appears in the track, the gap presents the user
4950 with odd behaviour - why did it skip past Foo-N+1?
4952 We could explain this to the user in some odd way, but
4953 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4956 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4959 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4961 std::string name = track->steal_write_source_name ();
4964 return boost::shared_ptr<MidiSource>();
4967 /* MIDI files are small, just put them in the first location of the
4968 session source search path.
4971 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4973 return boost::dynamic_pointer_cast<SMFSource> (
4974 SourceFactory::createWritable (
4975 DataType::MIDI, *this, path, false, frame_rate()));
4980 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4982 if (playlist->hidden()) {
4986 playlists->add (playlist);
4989 playlist->release();
4996 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4998 if (_state_of_the_state & Deletion) {
5002 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5008 playlists->remove (playlist);
5014 Session::set_audition (boost::shared_ptr<Region> r)
5016 pending_audition_region = r;
5017 add_post_transport_work (PostTransportAudition);
5018 _butler->schedule_transport_work ();
5022 Session::audition_playlist ()
5024 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5025 ev->region.reset ();
5031 Session::register_lua_function (
5032 const std::string& name,
5033 const std::string& script,
5034 const LuaScriptParamList& args
5037 Glib::Threads::Mutex::Lock lm (lua_lock);
5039 lua_State* L = lua.getState();
5041 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5042 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5043 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5044 if ((*i)->optional && !(*i)->is_set) { continue; }
5045 tbl_arg[(*i)->name] = (*i)->value;
5047 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5052 Session::unregister_lua_function (const std::string& name)
5054 Glib::Threads::Mutex::Lock lm (lua_lock);
5055 (*_lua_del)(name); // throws luabridge::LuaException
5056 lua.collect_garbage ();
5060 std::vector<std::string>
5061 Session::registered_lua_functions ()
5063 Glib::Threads::Mutex::Lock lm (lua_lock);
5064 std::vector<std::string> rv;
5067 luabridge::LuaRef list ((*_lua_list)());
5068 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5069 if (!i.key ().isString ()) { assert(0); continue; }
5070 rv.push_back (i.key ().cast<std::string> ());
5072 } catch (luabridge::LuaException const& e) { }
5077 static void _lua_print (std::string s) {
5078 std::cout << "SessionLua: " << s << "\n";
5083 Session::try_run_lua (pframes_t nframes)
5085 if (_n_lua_scripts == 0) return;
5086 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5088 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5093 Session::setup_lua ()
5096 lua.Print.connect (&_lua_print);
5099 "function ArdourSession ()"
5100 " local self = { scripts = {}, instances = {} }"
5102 " local remove = function (n)"
5103 " self.scripts[n] = nil"
5104 " self.instances[n] = nil"
5105 " Session:scripts_changed()" // call back
5108 " local addinternal = function (n, f, a)"
5109 " assert(type(n) == 'string', 'function-name must be string')"
5110 " assert(type(f) == 'function', 'Given script is a not a function')"
5111 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5112 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5113 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5114 " 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"
5115 " 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 }"
5116 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5117 " Session:scripts_changed()" // call back
5120 " local add = function (n, b, a)"
5121 " assert(type(b) == 'string', 'ByteCode must be string')"
5122 " load (b)()" // assigns f
5123 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5124 " addinternal (n, load(f), a)"
5127 " local run = function (...)"
5128 " for n, s in pairs (self.instances) do"
5129 " local status, err = pcall (s, ...)"
5130 " if not status then"
5131 " print ('fn \"'.. n .. '\": ', err)"
5138 " local cleanup = function ()"
5139 " self.scripts = nil"
5140 " self.instances = nil"
5143 " local list = function ()"
5145 " for n, _ in pairs (self.scripts) do"
5151 " local function basic_serialize (o)"
5152 " if type(o) == \"number\" then"
5153 " return tostring(o)"
5155 " return string.format(\"%q\", o)"
5159 " local function serialize (name, value)"
5160 " local rv = name .. ' = '"
5162 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5163 " return rv .. basic_serialize(value) .. ' '"
5164 " elseif type(value) == \"table\" then"
5166 " for k,v in pairs(value) do"
5167 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5168 " rv = rv .. serialize(fieldname, v) .. ' '"
5169 " collectgarbage()" // string concatenation allocates a new string :(
5172 " elseif type(value) == \"function\" then"
5173 " return rv .. string.format(\"%q\", string.dump(value, true))"
5175 " error('cannot save a ' .. type(value))"
5180 " local save = function ()"
5181 " return (serialize('scripts', self.scripts))"
5184 " local restore = function (state)"
5185 " self.scripts = {}"
5187 " for n, s in pairs (scripts) do"
5188 " addinternal (n, load(s['f']), s['a'])"
5192 " return { run = run, add = add, remove = remove,"
5193 " list = list, restore = restore, save = save, cleanup = cleanup}"
5196 " sess = ArdourSession ()"
5197 " ArdourSession = nil"
5199 "function ardour () end"
5202 lua_State* L = lua.getState();
5205 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5206 lua.do_command ("sess = nil"); // hide it.
5207 lua.do_command ("collectgarbage()");
5209 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5210 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5211 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5212 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5213 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5214 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5215 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5216 } catch (luabridge::LuaException const& e) {
5217 fatal << string_compose (_("programming error: %1"),
5218 X_("Failed to setup Lua interpreter"))
5220 abort(); /*NOTREACHED*/
5223 LuaBindings::stddef (L);
5224 LuaBindings::common (L);
5225 LuaBindings::dsp (L);
5226 luabridge::push <Session *> (L, this);
5227 lua_setglobal (L, "Session");
5231 Session::scripts_changed ()
5233 assert (!lua_lock.trylock()); // must hold lua_lock
5236 luabridge::LuaRef list ((*_lua_list)());
5238 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5239 if (!i.key ().isString ()) { assert(0); continue; }
5242 _n_lua_scripts = cnt;
5243 } catch (luabridge::LuaException const& e) {
5244 fatal << string_compose (_("programming error: %1"),
5245 X_("Indexing Lua Session Scripts failed."))
5247 abort(); /*NOTREACHED*/
5252 Session::non_realtime_set_audition ()
5254 assert (pending_audition_region);
5255 auditioner->audition_region (pending_audition_region);
5256 pending_audition_region.reset ();
5257 AuditionActive (true); /* EMIT SIGNAL */
5261 Session::audition_region (boost::shared_ptr<Region> r)
5263 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5269 Session::cancel_audition ()
5274 if (auditioner->auditioning()) {
5275 auditioner->cancel_audition ();
5276 AuditionActive (false); /* EMIT SIGNAL */
5281 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5283 if (a->is_monitor()) {
5286 if (b->is_monitor()) {
5289 return a->order_key () < b->order_key ();
5293 Session::is_auditioning () const
5295 /* can be called before we have an auditioner object */
5297 return auditioner->auditioning();
5304 Session::graph_reordered ()
5306 /* don't do this stuff if we are setting up connections
5307 from a set_state() call or creating new tracks. Ditto for deletion.
5310 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5314 /* every track/bus asked for this to be handled but it was deferred because
5315 we were connecting. do it now.
5318 request_input_change_handling ();
5322 /* force all diskstreams to update their capture offset values to
5323 reflect any changes in latencies within the graph.
5326 boost::shared_ptr<RouteList> rl = routes.reader ();
5327 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5328 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5330 tr->set_capture_offset ();
5335 /** @return Number of frames that there is disk space available to write,
5338 boost::optional<framecnt_t>
5339 Session::available_capture_duration ()
5341 Glib::Threads::Mutex::Lock lm (space_lock);
5343 if (_total_free_4k_blocks_uncertain) {
5344 return boost::optional<framecnt_t> ();
5347 float sample_bytes_on_disk = 4.0; // keep gcc happy
5349 switch (config.get_native_file_data_format()) {
5351 sample_bytes_on_disk = 4.0;
5355 sample_bytes_on_disk = 3.0;
5359 sample_bytes_on_disk = 2.0;
5363 /* impossible, but keep some gcc versions happy */
5364 fatal << string_compose (_("programming error: %1"),
5365 X_("illegal native file data format"))
5367 abort(); /*NOTREACHED*/
5370 double scale = 4096.0 / sample_bytes_on_disk;
5372 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5373 return max_framecnt;
5376 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5380 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5383 RCUWriter<BundleList> writer (_bundles);
5384 boost::shared_ptr<BundleList> b = writer.get_copy ();
5385 b->push_back (bundle);
5389 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5396 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5398 bool removed = false;
5401 RCUWriter<BundleList> writer (_bundles);
5402 boost::shared_ptr<BundleList> b = writer.get_copy ();
5403 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5405 if (i != b->end()) {
5412 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5418 boost::shared_ptr<Bundle>
5419 Session::bundle_by_name (string name) const
5421 boost::shared_ptr<BundleList> b = _bundles.reader ();
5423 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5424 if ((*i)->name() == name) {
5429 return boost::shared_ptr<Bundle> ();
5433 Session::tempo_map_changed (const PropertyChange&)
5437 playlists->update_after_tempo_map_change ();
5439 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5445 Session::gui_tempo_map_changed ()
5449 playlists->update_after_tempo_map_change ();
5451 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5455 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5457 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5458 (*i)->recompute_frames_from_bbt ();
5462 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5463 * the given count with the current block size.
5466 Session::ensure_buffers (ChanCount howmany)
5468 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5472 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5474 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5475 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5480 Session::next_insert_id ()
5482 /* this doesn't really loop forever. just think about it */
5485 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5486 if (!insert_bitset[n]) {
5487 insert_bitset[n] = true;
5493 /* none available, so resize and try again */
5495 insert_bitset.resize (insert_bitset.size() + 16, false);
5500 Session::next_send_id ()
5502 /* this doesn't really loop forever. just think about it */
5505 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5506 if (!send_bitset[n]) {
5507 send_bitset[n] = true;
5513 /* none available, so resize and try again */
5515 send_bitset.resize (send_bitset.size() + 16, false);
5520 Session::next_aux_send_id ()
5522 /* this doesn't really loop forever. just think about it */
5525 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5526 if (!aux_send_bitset[n]) {
5527 aux_send_bitset[n] = true;
5533 /* none available, so resize and try again */
5535 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5540 Session::next_return_id ()
5542 /* this doesn't really loop forever. just think about it */
5545 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5546 if (!return_bitset[n]) {
5547 return_bitset[n] = true;
5553 /* none available, so resize and try again */
5555 return_bitset.resize (return_bitset.size() + 16, false);
5560 Session::mark_send_id (uint32_t id)
5562 if (id >= send_bitset.size()) {
5563 send_bitset.resize (id+16, false);
5565 if (send_bitset[id]) {
5566 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5568 send_bitset[id] = true;
5572 Session::mark_aux_send_id (uint32_t id)
5574 if (id >= aux_send_bitset.size()) {
5575 aux_send_bitset.resize (id+16, false);
5577 if (aux_send_bitset[id]) {
5578 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5580 aux_send_bitset[id] = true;
5584 Session::mark_return_id (uint32_t id)
5586 if (id >= return_bitset.size()) {
5587 return_bitset.resize (id+16, false);
5589 if (return_bitset[id]) {
5590 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5592 return_bitset[id] = true;
5596 Session::mark_insert_id (uint32_t id)
5598 if (id >= insert_bitset.size()) {
5599 insert_bitset.resize (id+16, false);
5601 if (insert_bitset[id]) {
5602 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5604 insert_bitset[id] = true;
5608 Session::unmark_send_id (uint32_t id)
5610 if (id < send_bitset.size()) {
5611 send_bitset[id] = false;
5616 Session::unmark_aux_send_id (uint32_t id)
5618 if (id < aux_send_bitset.size()) {
5619 aux_send_bitset[id] = false;
5624 Session::unmark_return_id (uint32_t id)
5626 if (_state_of_the_state & Deletion) { return; }
5627 if (id < return_bitset.size()) {
5628 return_bitset[id] = false;
5633 Session::unmark_insert_id (uint32_t id)
5635 if (id < insert_bitset.size()) {
5636 insert_bitset[id] = false;
5641 Session::reset_native_file_format ()
5643 boost::shared_ptr<RouteList> rl = routes.reader ();
5645 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5646 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5648 /* don't save state as we do this, there's no point
5650 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5651 tr->reset_write_sources (false);
5652 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5658 Session::route_name_unique (string n) const
5660 boost::shared_ptr<RouteList> r = routes.reader ();
5662 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5663 if ((*i)->name() == n) {
5672 Session::route_name_internal (string n) const
5674 if (auditioner && auditioner->name() == n) {
5678 if (_click_io && _click_io->name() == n) {
5686 Session::freeze_all (InterThreadInfo& itt)
5688 boost::shared_ptr<RouteList> r = routes.reader ();
5690 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5692 boost::shared_ptr<Track> t;
5694 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5695 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5705 boost::shared_ptr<Region>
5706 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5707 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5708 InterThreadInfo& itt,
5709 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5710 bool for_export, bool for_freeze)
5712 boost::shared_ptr<Region> result;
5713 boost::shared_ptr<Playlist> playlist;
5714 boost::shared_ptr<Source> source;
5715 ChanCount diskstream_channels (track.n_channels());
5716 framepos_t position;
5717 framecnt_t this_chunk;
5719 framepos_t latency_skip;
5721 framepos_t len = end - start;
5722 bool need_block_size_reset = false;
5723 ChanCount const max_proc = track.max_processor_streams ();
5724 string legal_playlist_name;
5725 string possible_path;
5728 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5729 end, start) << endmsg;
5733 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5734 include_endpoint, for_export, for_freeze);
5736 if (diskstream_channels.n(track.data_type()) < 1) {
5737 error << _("Cannot write a range with no data.") << endmsg;
5741 // block all process callback handling
5743 block_processing ();
5746 // synchronize with AudioEngine::process_callback()
5747 // make sure processing is not currently running
5748 // and processing_blocked() is honored before
5749 // acquiring thread buffers
5750 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5753 _bounce_processing_active = true;
5755 /* call tree *MUST* hold route_lock */
5757 if ((playlist = track.playlist()) == 0) {
5761 legal_playlist_name = legalize_for_path (playlist->name());
5763 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5765 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5766 string path = ((track.data_type() == DataType::AUDIO)
5767 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5768 : new_midi_source_path (legal_playlist_name));
5775 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5778 catch (failed_constructor& err) {
5779 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5783 srcs.push_back (source);
5786 /* tell redirects that care that we are about to use a much larger
5787 * blocksize. this will flush all plugins too, so that they are ready
5788 * to be used for this process.
5791 need_block_size_reset = true;
5792 track.set_block_size (bounce_chunk_size);
5793 _engine.main_thread()->get_buffers ();
5797 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5799 /* create a set of reasonably-sized buffers */
5800 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5801 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5803 buffers.set_count (max_proc);
5805 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5806 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5807 boost::shared_ptr<MidiSource> ms;
5809 afs->prepare_for_peakfile_writes ();
5810 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5811 Source::Lock lock(ms->mutex());
5812 ms->mark_streaming_write_started(lock);
5816 while (to_do && !itt.cancel) {
5818 this_chunk = min (to_do, bounce_chunk_size);
5820 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5824 start += this_chunk;
5825 to_do -= this_chunk;
5826 itt.progress = (float) (1.0 - ((double) to_do / len));
5828 if (latency_skip >= bounce_chunk_size) {
5829 latency_skip -= bounce_chunk_size;
5833 const framecnt_t current_chunk = this_chunk - latency_skip;
5836 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5837 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5838 boost::shared_ptr<MidiSource> ms;
5841 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5844 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5845 Source::Lock lock(ms->mutex());
5847 const MidiBuffer& buf = buffers.get_midi(0);
5848 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5849 Evoral::Event<framepos_t> ev = *i;
5850 ev.set_time(ev.time() - position);
5851 ms->append_event_frames(lock, ev, ms->timeline_position());
5858 /* post-roll, pick up delayed processor output */
5859 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5861 while (latency_skip && !itt.cancel) {
5862 this_chunk = min (latency_skip, bounce_chunk_size);
5863 latency_skip -= this_chunk;
5865 buffers.silence (this_chunk, 0);
5866 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5869 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5870 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5873 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5885 xnow = localtime (&now);
5887 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5888 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5889 boost::shared_ptr<MidiSource> ms;
5892 afs->update_header (position, *xnow, now);
5893 afs->flush_header ();
5894 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5895 Source::Lock lock(ms->mutex());
5896 ms->mark_streaming_write_completed(lock);
5900 /* construct a region to represent the bounced material */
5904 plist.add (Properties::start, 0);
5905 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5906 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5908 result = RegionFactory::create (srcs, plist);
5914 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5915 (*src)->mark_for_remove ();
5916 (*src)->drop_references ();
5920 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5921 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5924 afs->done_with_peakfile_writes ();
5928 _bounce_processing_active = false;
5930 if (need_block_size_reset) {
5931 _engine.main_thread()->drop_buffers ();
5932 track.set_block_size (get_block_size());
5935 unblock_processing ();
5941 Session::gain_automation_buffer() const
5943 return ProcessThread::gain_automation_buffer ();
5947 Session::trim_automation_buffer() const
5949 return ProcessThread::trim_automation_buffer ();
5953 Session::send_gain_automation_buffer() const
5955 return ProcessThread::send_gain_automation_buffer ();
5959 Session::pan_automation_buffer() const
5961 return ProcessThread::pan_automation_buffer ();
5965 Session::get_silent_buffers (ChanCount count)
5967 return ProcessThread::get_silent_buffers (count);
5971 Session::get_scratch_buffers (ChanCount count, bool silence)
5973 return ProcessThread::get_scratch_buffers (count, silence);
5977 Session::get_noinplace_buffers (ChanCount count)
5979 return ProcessThread::get_noinplace_buffers (count);
5983 Session::get_route_buffers (ChanCount count, bool silence)
5985 return ProcessThread::get_route_buffers (count, silence);
5990 Session::get_mix_buffers (ChanCount count)
5992 return ProcessThread::get_mix_buffers (count);
5996 Session::ntracks () const
5999 boost::shared_ptr<RouteList> r = routes.reader ();
6001 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6002 if (boost::dynamic_pointer_cast<Track> (*i)) {
6011 Session::nbusses () const
6014 boost::shared_ptr<RouteList> r = routes.reader ();
6016 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6017 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6026 Session::add_automation_list(AutomationList *al)
6028 automation_lists[al->id()] = al;
6031 /** @return true if there is at least one record-enabled track, otherwise false */
6033 Session::have_rec_enabled_track () const
6035 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6039 Session::have_rec_disabled_track () const
6041 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6044 /** Update the state of our rec-enabled tracks flag */
6046 Session::update_route_record_state ()
6048 boost::shared_ptr<RouteList> rl = routes.reader ();
6049 RouteList::iterator i = rl->begin();
6050 while (i != rl->end ()) {
6052 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6053 if (tr && tr->record_enabled ()) {
6060 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6062 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6064 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6065 RecordStateChanged (); /* EMIT SIGNAL */
6068 for (i = rl->begin(); i != rl->end (); ++i) {
6069 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6070 if (tr && !tr->record_enabled ()) {
6075 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6077 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6079 if (record_status() == Recording && record_arm_state_changed ) {
6080 RecordArmStateChanged ();
6086 Session::listen_position_changed ()
6088 boost::shared_ptr<RouteList> r = routes.reader ();
6090 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6091 (*i)->listen_position_changed ();
6096 Session::solo_control_mode_changed ()
6098 /* cancel all solo or all listen when solo control mode changes */
6101 set_solo (get_routes(), false);
6102 } else if (listening()) {
6103 set_listen (get_routes(), false);
6107 /** Called when a property of one of our route groups changes */
6109 Session::route_group_property_changed (RouteGroup* rg)
6111 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6114 /** Called when a route is added to one of our route groups */
6116 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6118 RouteAddedToRouteGroup (rg, r);
6121 /** Called when a route is removed from one of our route groups */
6123 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6125 update_route_record_state ();
6126 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6129 boost::shared_ptr<RouteList>
6130 Session::get_tracks () const
6132 boost::shared_ptr<RouteList> rl = routes.reader ();
6133 boost::shared_ptr<RouteList> tl (new RouteList);
6135 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6136 if (boost::dynamic_pointer_cast<Track> (*r)) {
6137 if (!(*r)->is_auditioner()) {
6145 boost::shared_ptr<RouteList>
6146 Session::get_routes_with_regions_at (framepos_t const p) const
6148 boost::shared_ptr<RouteList> r = routes.reader ();
6149 boost::shared_ptr<RouteList> rl (new RouteList);
6151 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6152 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6157 boost::shared_ptr<Playlist> pl = tr->playlist ();
6162 if (pl->has_region_at (p)) {
6171 Session::goto_end ()
6173 if (_session_range_location) {
6174 request_locate (_session_range_location->end(), false);
6176 request_locate (0, false);
6181 Session::goto_start ()
6183 if (_session_range_location) {
6184 request_locate (_session_range_location->start(), false);
6186 request_locate (0, false);
6191 Session::current_start_frame () const
6193 return _session_range_location ? _session_range_location->start() : 0;
6197 Session::current_end_frame () const
6199 return _session_range_location ? _session_range_location->end() : 0;
6203 Session::set_session_range_location (framepos_t start, framepos_t end)
6205 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6206 _locations->add (_session_range_location);
6210 Session::step_edit_status_change (bool yn)
6216 send = (_step_editors == 0);
6221 send = (_step_editors == 1);
6224 if (_step_editors > 0) {
6230 StepEditStatusChange (val);
6236 Session::start_time_changed (framepos_t old)
6238 /* Update the auto loop range to match the session range
6239 (unless the auto loop range has been changed by the user)
6242 Location* s = _locations->session_range_location ();
6247 Location* l = _locations->auto_loop_location ();
6249 if (l && l->start() == old) {
6250 l->set_start (s->start(), true);
6255 Session::end_time_changed (framepos_t old)
6257 /* Update the auto loop range to match the session range
6258 (unless the auto loop range has been changed by the user)
6261 Location* s = _locations->session_range_location ();
6266 Location* l = _locations->auto_loop_location ();
6268 if (l && l->end() == old) {
6269 l->set_end (s->end(), true);
6273 std::vector<std::string>
6274 Session::source_search_path (DataType type) const
6278 if (session_dirs.size() == 1) {
6280 case DataType::AUDIO:
6281 sp.push_back (_session_dir->sound_path());
6283 case DataType::MIDI:
6284 sp.push_back (_session_dir->midi_path());
6288 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6289 SessionDirectory sdir (i->path);
6291 case DataType::AUDIO:
6292 sp.push_back (sdir.sound_path());
6294 case DataType::MIDI:
6295 sp.push_back (sdir.midi_path());
6301 if (type == DataType::AUDIO) {
6302 const string sound_path_2X = _session_dir->sound_path_2X();
6303 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6304 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6305 sp.push_back (sound_path_2X);
6310 // now check the explicit (possibly user-specified) search path
6313 case DataType::AUDIO:
6314 sp += Searchpath(config.get_audio_search_path ());
6316 case DataType::MIDI:
6317 sp += Searchpath(config.get_midi_search_path ());
6325 Session::ensure_search_path_includes (const string& path, DataType type)
6334 case DataType::AUDIO:
6335 sp += Searchpath(config.get_audio_search_path ());
6337 case DataType::MIDI:
6338 sp += Searchpath (config.get_midi_search_path ());
6342 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6343 /* No need to add this new directory if it has the same inode as
6344 an existing one; checking inode rather than name prevents duplicated
6345 directories when we are using symlinks.
6347 On Windows, I think we could just do if (*i == path) here.
6349 if (PBD::equivalent_paths (*i, path)) {
6357 case DataType::AUDIO:
6358 config.set_audio_search_path (sp.to_string());
6360 case DataType::MIDI:
6361 config.set_midi_search_path (sp.to_string());
6367 Session::remove_dir_from_search_path (const string& dir, DataType type)
6372 case DataType::AUDIO:
6373 sp = Searchpath(config.get_audio_search_path ());
6375 case DataType::MIDI:
6376 sp = Searchpath (config.get_midi_search_path ());
6383 case DataType::AUDIO:
6384 config.set_audio_search_path (sp.to_string());
6386 case DataType::MIDI:
6387 config.set_midi_search_path (sp.to_string());
6393 boost::shared_ptr<Speakers>
6394 Session::get_speakers()
6400 Session::unknown_processors () const
6404 boost::shared_ptr<RouteList> r = routes.reader ();
6405 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6406 list<string> t = (*i)->unknown_processors ();
6407 copy (t.begin(), t.end(), back_inserter (p));
6417 Session::update_latency (bool playback)
6420 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6422 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6426 boost::shared_ptr<RouteList> r = routes.reader ();
6427 framecnt_t max_latency = 0;
6430 /* reverse the list so that we work backwards from the last route to run to the first */
6431 RouteList* rl = routes.reader().get();
6432 r.reset (new RouteList (*rl));
6433 reverse (r->begin(), r->end());
6436 /* compute actual latency values for the given direction and store them all in per-port
6437 structures. this will also publish the same values (to JACK) so that computation of latency
6438 for routes can consistently use public latency values.
6441 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6442 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6445 /* because we latency compensate playback, our published playback latencies should
6446 be the same for all output ports - all material played back by ardour has
6447 the same latency, whether its caused by plugins or by latency compensation. since
6448 these may differ from the values computed above, reset all playback port latencies
6452 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6454 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6455 (*i)->set_public_port_latencies (max_latency, playback);
6460 post_playback_latency ();
6464 post_capture_latency ();
6467 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6471 Session::post_playback_latency ()
6473 set_worst_playback_latency ();
6475 boost::shared_ptr<RouteList> r = routes.reader ();
6477 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6478 if (!(*i)->is_auditioner() && ((*i)->active())) {
6479 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6483 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6484 (*i)->set_latency_compensation (_worst_track_latency);
6489 Session::post_capture_latency ()
6491 set_worst_capture_latency ();
6493 /* reflect any changes in capture latencies into capture offsets
6496 boost::shared_ptr<RouteList> rl = routes.reader();
6497 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6498 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6500 tr->set_capture_offset ();
6506 Session::initialize_latencies ()
6509 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6510 update_latency (false);
6511 update_latency (true);
6514 set_worst_io_latencies ();
6518 Session::set_worst_io_latencies ()
6520 set_worst_playback_latency ();
6521 set_worst_capture_latency ();
6525 Session::set_worst_playback_latency ()
6527 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6531 _worst_output_latency = 0;
6533 if (!_engine.connected()) {
6537 boost::shared_ptr<RouteList> r = routes.reader ();
6539 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6540 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6543 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6547 Session::set_worst_capture_latency ()
6549 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6553 _worst_input_latency = 0;
6555 if (!_engine.connected()) {
6559 boost::shared_ptr<RouteList> r = routes.reader ();
6561 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6562 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6565 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6569 Session::update_latency_compensation (bool force_whole_graph)
6571 bool some_track_latency_changed = false;
6573 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6577 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6579 _worst_track_latency = 0;
6581 boost::shared_ptr<RouteList> r = routes.reader ();
6583 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6584 if (!(*i)->is_auditioner() && ((*i)->active())) {
6586 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6587 some_track_latency_changed = true;
6589 _worst_track_latency = max (tl, _worst_track_latency);
6593 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6594 (some_track_latency_changed ? "yes" : "no")));
6596 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6598 if (some_track_latency_changed || force_whole_graph) {
6599 _engine.update_latencies ();
6603 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6604 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6608 tr->set_capture_offset ();
6613 Session::session_name_is_legal (const string& path)
6615 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6617 for (int i = 0; illegal_chars[i]; ++i) {
6618 if (path.find (illegal_chars[i]) != string::npos) {
6619 return illegal_chars[i];
6627 Session::next_control_id () const
6631 /* the monitor bus remote ID is in a different
6632 * "namespace" than regular routes. its existence doesn't
6633 * affect normal (low) numbered routes.
6640 /* the same about masterbus in Waves Tracks */
6642 if (Profile->get_trx() && _master_out) {
6646 return nroutes() - subtract;
6650 Session::notify_remote_id_change ()
6652 if (deletion_in_progress()) {
6656 switch (Config->get_remote_model()) {
6658 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6664 #ifdef USE_TRACKS_CODE_FEATURES
6665 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6666 * if track order has been changed by user
6668 reconnect_existing_routes(true, true);
6674 Session::sync_order_keys ()
6676 if (deletion_in_progress()) {
6680 /* tell everyone that something has happened to the sort keys
6681 and let them sync up with the change(s)
6682 this will give objects that manage the sort order keys the
6683 opportunity to keep them in sync if they wish to.
6686 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6688 reassign_track_numbers();
6690 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6692 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6696 Session::operation_in_progress (GQuark op) const
6698 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6701 boost::shared_ptr<Port>
6702 Session::ltc_input_port () const
6704 return _ltc_input->nth (0);
6707 boost::shared_ptr<Port>
6708 Session::ltc_output_port () const
6710 return _ltc_output->nth (0);
6714 Session::reconnect_ltc_input ()
6718 string src = Config->get_ltc_source_port();
6720 _ltc_input->disconnect (this);
6722 if (src != _("None") && !src.empty()) {
6723 _ltc_input->nth (0)->connect (src);
6726 if ( ARDOUR::Profile->get_trx () ) {
6727 // Tracks need this signal to update timecode_source_dropdown
6728 MtcOrLtcInputPortChanged (); //emit signal
6734 Session::reconnect_ltc_output ()
6738 string src = Config->get_ltc_output_port();
6740 _ltc_output->disconnect (this);
6742 if (src != _("None") && !src.empty()) {
6743 _ltc_output->nth (0)->connect (src);
6749 Session::set_range_selection (framepos_t start, framepos_t end)
6751 _range_selection = Evoral::Range<framepos_t> (start, end);
6752 #ifdef USE_TRACKS_CODE_FEATURES
6753 follow_playhead_priority ();
6758 Session::set_object_selection (framepos_t start, framepos_t end)
6760 _object_selection = Evoral::Range<framepos_t> (start, end);
6761 #ifdef USE_TRACKS_CODE_FEATURES
6762 follow_playhead_priority ();
6767 Session::clear_range_selection ()
6769 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6770 #ifdef USE_TRACKS_CODE_FEATURES
6771 follow_playhead_priority ();
6776 Session::clear_object_selection ()
6778 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6779 #ifdef USE_TRACKS_CODE_FEATURES
6780 follow_playhead_priority ();
6785 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6786 const ChanCount& input_start,
6787 const ChanCount& output_start,
6788 const ChanCount& input_offset,
6789 const ChanCount& output_offset)
6791 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6792 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6793 input_start, output_start,
6794 input_offset, output_offset));
6796 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6797 pthread_cond_signal (&_auto_connect_cond);
6798 pthread_mutex_unlock (&_auto_connect_mutex);
6803 Session::auto_connect (const AutoConnectRequest& ar)
6805 boost::shared_ptr<Route> route = ar.route.lock();
6807 if (!route) { return; }
6809 if (!IO::connecting_legal) {
6813 /* If both inputs and outputs are auto-connected to physical ports,
6814 * use the max of input and output offsets to ensure auto-connected
6815 * port numbers always match up (e.g. the first audio input and the
6816 * first audio output of the route will have the same physical
6817 * port number). Otherwise just use the lowest input or output
6821 const bool in_out_physical =
6822 (Config->get_input_auto_connect() & AutoConnectPhysical)
6823 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6824 && ar.connect_inputs;
6826 const ChanCount in_offset = in_out_physical
6827 ? ChanCount::max(ar.input_offset, ar.output_offset)
6830 const ChanCount out_offset = in_out_physical
6831 ? ChanCount::max(ar.input_offset, ar.output_offset)
6834 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6835 vector<string> physinputs;
6836 vector<string> physoutputs;
6838 _engine.get_physical_outputs (*t, physoutputs);
6839 _engine.get_physical_inputs (*t, physinputs);
6841 if (!physinputs.empty() && ar.connect_inputs) {
6842 uint32_t nphysical_in = physinputs.size();
6844 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6847 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6848 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6851 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6857 if (!physoutputs.empty()) {
6858 uint32_t nphysical_out = physoutputs.size();
6859 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6863 * do not create new connections if we reached the limit of physical outputs
6866 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6867 ARDOUR::Profile->get_trx () &&
6868 ar.output_offset.get(*t) == nphysical_out ) {
6872 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6873 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6874 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6875 /* master bus is audio only */
6876 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6877 port = _master_out->input()->ports().port(*t,
6878 i % _master_out->input()->n_ports().get(*t))->name();
6882 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6891 Session::auto_connect_thread_start ()
6893 if (_ac_thread_active) {
6897 while (!_auto_connect_queue.empty ()) {
6898 _auto_connect_queue.pop ();
6901 _ac_thread_active = true;
6902 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6903 _ac_thread_active = false;
6908 Session::auto_connect_thread_terminate ()
6910 if (!_ac_thread_active) {
6913 _ac_thread_active = false;
6916 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6917 while (!_auto_connect_queue.empty ()) {
6918 _auto_connect_queue.pop ();
6922 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6923 pthread_cond_signal (&_auto_connect_cond);
6924 pthread_mutex_unlock (&_auto_connect_mutex);
6928 pthread_join (_auto_connect_thread, &status);
6932 Session::auto_connect_thread (void *arg)
6934 Session *s = static_cast<Session *>(arg);
6935 s->auto_connect_thread_run ();
6941 Session::auto_connect_thread_run ()
6943 pthread_set_name (X_("autoconnect"));
6944 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6945 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6946 pthread_mutex_lock (&_auto_connect_mutex);
6947 while (_ac_thread_active) {
6949 if (!_auto_connect_queue.empty ()) {
6950 // Why would we need the process lock ??
6951 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
6952 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
6953 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
6954 // We have control over those, but what does jack do?
6955 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6957 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6958 while (!_auto_connect_queue.empty ()) {
6959 const AutoConnectRequest ar (_auto_connect_queue.front());
6960 _auto_connect_queue.pop ();
6967 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
6969 pthread_mutex_unlock (&_auto_connect_mutex);