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/solo_isolate_control.h"
102 #include "ardour/source_factory.h"
103 #include "ardour/speakers.h"
104 #include "ardour/tempo.h"
105 #include "ardour/ticker.h"
106 #include "ardour/track.h"
107 #include "ardour/user_bundle.h"
108 #include "ardour/utils.h"
109 #include "ardour/vca_manager.h"
110 #include "ardour/vca.h"
112 #include "midi++/port.h"
113 #include "midi++/mmc.h"
115 #include "LuaBridge/LuaBridge.h"
119 #include <glibmm/checksum.h>
128 using namespace ARDOUR;
131 bool Session::_disable_all_loaded_plugins = false;
132 bool Session::_bypass_all_loaded_plugins = false;
133 guint Session::_name_id_counter = 0;
135 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
136 PBD::Signal1<void,std::string> Session::Dialog;
137 PBD::Signal0<int> Session::AskAboutPendingState;
138 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
139 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
140 PBD::Signal0<void> Session::SendFeedback;
141 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
143 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
144 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
145 PBD::Signal2<void,std::string, std::string> Session::Exported;
146 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
147 PBD::Signal0<void> Session::Quit;
148 PBD::Signal0<void> Session::FeedbackDetected;
149 PBD::Signal0<void> Session::SuccessfulGraphSort;
150 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
152 const framecnt_t Session::bounce_chunk_size = 8192;
153 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
154 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
156 // seconds should be added after the region exceeds end marker
157 #ifdef USE_TRACKS_CODE_FEATURES
158 const uint32_t Session::session_end_shift = 5;
160 const uint32_t Session::session_end_shift = 0;
163 /** @param snapshot_name Snapshot name, without .ardour suffix */
164 Session::Session (AudioEngine &eng,
165 const string& fullpath,
166 const string& snapshot_name,
167 BusProfile* bus_profile,
169 : playlists (new SessionPlaylists)
171 , process_function (&Session::process_with_events)
172 , _bounce_processing_active (false)
173 , waiting_for_sync_offset (false)
174 , _base_frame_rate (0)
175 , _nominal_frame_rate (0)
176 , _current_frame_rate (0)
177 , transport_sub_state (0)
178 , _record_status (Disabled)
179 , _transport_frame (0)
180 , _session_range_location (0)
183 , _transport_speed (0)
184 , _default_transport_speed (1.0)
185 , _last_transport_speed (0)
186 , _target_transport_speed (0.0)
187 , auto_play_legal (false)
188 , _last_slave_transport_frame (0)
189 , maximum_output_latency (0)
190 , _requested_return_frame (-1)
191 , current_block_size (0)
192 , _worst_output_latency (0)
193 , _worst_input_latency (0)
194 , _worst_track_latency (0)
195 , _have_captured (false)
196 , _non_soloed_outs_muted (false)
199 , _solo_isolated_cnt (0)
201 , _was_seamless (Config->get_seamless_loop ())
202 , _under_nsm_control (false)
204 , delta_accumulator_cnt (0)
205 , average_slave_delta (1800) // !!! why 1800 ???
207 , have_first_delta_accumulator (false)
208 , _slave_state (Stopped)
209 , _mtc_active (false)
210 , _ltc_active (false)
211 , post_export_sync (false)
212 , post_export_position (0)
214 , _export_rolling (false)
215 , _export_preroll (0)
216 , _pre_export_mmc_enabled (false)
217 , _name (snapshot_name)
219 , _send_qf_mtc (false)
220 , _pframes_since_last_mtc (0)
221 , session_midi_feedback (0)
223 , loop_changing (false)
225 , _session_dir (new SessionDirectory (fullpath))
226 , _current_snapshot_name (snapshot_name)
228 , state_was_pending (false)
229 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
231 , _save_queued (false)
232 , _last_roll_location (0)
233 , _last_roll_or_reversal_location (0)
234 , _last_record_location (0)
235 , pending_locate_roll (false)
236 , pending_locate_frame (0)
237 , pending_locate_flush (false)
238 , pending_abort (false)
239 , pending_auto_loop (false)
240 , _mempool ("Session", 1048576)
241 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
243 , _butler (new Butler (*this))
244 , _post_transport_work (0)
245 , cumulative_rf_motion (0)
247 , _locations (new Locations (*this))
248 , _ignore_skips_updates (false)
249 , _rt_thread_active (false)
250 , _rt_emit_pending (false)
251 , _ac_thread_active (false)
253 , outbound_mtc_timecode_frame (0)
254 , next_quarter_frame_to_send (-1)
255 , _frames_per_timecode_frame (0)
256 , _frames_per_hour (0)
257 , _timecode_frames_per_hour (0)
258 , last_timecode_valid (false)
259 , last_timecode_when (0)
260 , _send_timecode_update (false)
272 , ltc_timecode_offset (0)
273 , ltc_timecode_negative_offset (false)
274 , midi_control_ui (0)
276 , _all_route_group (new RouteGroup (*this, "all"))
277 , routes (new RouteList)
278 , _adding_routes_in_progress (false)
279 , _reconnecting_routes_in_progress (false)
280 , _route_deletion_in_progress (false)
281 , destructive_index (0)
282 , _track_number_decimals(1)
283 , default_fade_steepness (0)
284 , default_fade_msecs (0)
285 , _total_free_4k_blocks (0)
286 , _total_free_4k_blocks_uncertain (false)
287 , no_questions_about_missing_files (false)
290 , _bundles (new BundleList)
291 , _bundle_xml_node (0)
295 , click_emphasis_data (0)
297 , click_emphasis_length (0)
298 , _clicks_cleared (0)
299 , _play_range (false)
300 , _range_selection (-1,-1)
301 , _object_selection (-1,-1)
303 , first_file_data_format_reset (true)
304 , first_file_header_format_reset (true)
305 , have_looped (false)
306 , _have_rec_enabled_track (false)
307 , _have_rec_disabled_track (true)
309 , _suspend_timecode_transmission (0)
310 , _speakers (new Speakers)
312 , ignore_route_processor_changes (false)
317 , _vca_manager (new VCAManager (*this))
321 pthread_mutex_init (&_rt_emit_mutex, 0);
322 pthread_cond_init (&_rt_emit_cond, 0);
324 pthread_mutex_init (&_auto_connect_mutex, 0);
325 pthread_cond_init (&_auto_connect_cond, 0);
327 init_name_id_counter (1); // reset for new sessions, start at 1
328 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
330 pre_engine_init (fullpath);
336 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
338 #ifdef USE_TRACKS_CODE_FEATURES
339 sr = EngineStateController::instance()->get_current_sample_rate();
341 if (ensure_engine (sr, true)) {
343 throw SessionException (_("Cannot connect to audio/midi engine"));
346 // set samplerate for plugins added early
347 // e.g from templates or MB channelstrip
348 set_block_size (_engine.samples_per_cycle());
349 set_frame_rate (_engine.sample_rate());
351 if (create (mix_template, bus_profile)) {
353 throw SessionException (_("Session initialization failed"));
356 /* if a mix template was provided, then ::create() will
357 * have copied it into the session and we need to load it
358 * so that we have the state ready for ::set_state()
359 * after the engine is started.
361 * Note that we do NOT try to get the sample rate from
362 * the template at this time, though doing so would
363 * be easy if we decided this was an appropriate part
367 if (!mix_template.empty()) {
368 if (load_state (_current_snapshot_name)) {
369 throw SessionException (_("Failed to load template/snapshot state"));
371 store_recent_templates (mix_template);
374 /* load default session properties - if any */
379 if (load_state (_current_snapshot_name)) {
380 throw SessionException (_("Failed to load state"));
383 /* try to get sample rate from XML state so that we
384 * can influence the SR if we set up the audio
389 XMLProperty const * prop;
390 XMLNode const * root (state_tree->root());
391 if ((prop = root->property (X_("sample-rate"))) != 0) {
392 sr = atoi (prop->value());
396 if (ensure_engine (sr, false)) {
398 throw SessionException (_("Cannot connect to audio/midi engine"));
402 if (post_engine_init ()) {
404 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
407 store_recent_sessions (_name, _path);
409 bool was_dirty = dirty();
411 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
413 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
414 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
417 DirtyChanged (); /* EMIT SIGNAL */
420 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
421 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
423 emit_thread_start ();
424 auto_connect_thread_start ();
426 /* hook us up to the engine since we are now completely constructed */
428 BootMessage (_("Connect to engine"));
430 _engine.set_session (this);
431 _engine.reset_timebase ();
433 #ifdef USE_TRACKS_CODE_FEATURES
435 EngineStateController::instance()->set_session(this);
438 if ( ARDOUR::Profile->get_trx () ) {
440 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
441 * each available input must have corresponding track when session starts.
444 uint32_t how_many (0);
446 std::vector<std::string> inputs;
447 EngineStateController::instance()->get_physical_audio_inputs(inputs);
449 how_many = inputs.size();
451 list<boost::shared_ptr<AudioTrack> > tracks;
453 // Track names after driver
454 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
455 string track_name = "";
456 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
458 track_name = inputs[i];
459 replace_all (track_name, "system:capture", "");
461 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
462 tracks.insert(tracks.begin(), single_track.front());
464 } else { // Default track names
465 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
468 if (tracks.size() != how_many) {
470 throw failed_constructor ();
479 BootMessage (_("Session loading complete"));
491 Session::next_name_id ()
493 return g_atomic_int_add (&_name_id_counter, 1);
497 Session::name_id_counter ()
499 return g_atomic_int_get (&_name_id_counter);
503 Session::init_name_id_counter (guint n)
505 g_atomic_int_set (&_name_id_counter, n);
509 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
511 if (_engine.current_backend() == 0) {
512 /* backend is unknown ... */
513 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
514 if (r.get_value_or (-1) != 0) {
517 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
519 } else if (_engine.setup_required()) {
520 /* backend is known, but setup is needed */
521 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
522 if (r.get_value_or (-1) != 0) {
525 } else if (!_engine.running()) {
526 if (_engine.start()) {
531 /* at this point the engine should be running */
533 if (!_engine.running()) {
537 return immediately_post_engine ();
542 Session::immediately_post_engine ()
544 /* Do various initializations that should take place directly after we
545 * know that the engine is running, but before we either create a
546 * session or set state for an existing one.
549 if (how_many_dsp_threads () > 1) {
550 /* For now, only create the graph if we are using >1 DSP threads, as
551 it is a bit slower than the old code with 1 thread.
553 _process_graph.reset (new Graph (*this));
556 /* every time we reconnect, recompute worst case output latencies */
558 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
560 if (synced_to_engine()) {
561 _engine.transport_stop ();
564 if (config.get_jack_time_master()) {
565 _engine.transport_locate (_transport_frame);
570 BootMessage (_("Set up LTC"));
572 BootMessage (_("Set up Click"));
574 BootMessage (_("Set up standard connections"));
578 catch (failed_constructor& err) {
582 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
584 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
592 vector<void*> debug_pointers;
594 /* if we got to here, leaving pending capture state around
598 remove_pending_capture_state ();
602 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
604 /* stop autoconnecting */
605 auto_connect_thread_terminate ();
607 /* disconnect from any and all signals that we are connected to */
609 Port::PortSignalDrop (); /* EMIT SIGNAL */
612 /* shutdown control surface protocols while we still have ports
613 and the engine to move data to any devices.
616 ControlProtocolManager::instance().drop_protocols ();
618 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
620 _engine.remove_session ();
622 #ifdef USE_TRACKS_CODE_FEATURES
623 EngineStateController::instance()->remove_session();
626 /* deregister all ports - there will be no process or any other
627 * callbacks from the engine any more.
630 Port::PortDrop (); /* EMIT SIGNAL */
634 /* clear history so that no references to objects are held any more */
638 /* clear state tree so that no references to objects are held any more */
643 // unregister all lua functions, drop held references (if any)
645 lua.do_command ("Session = nil");
653 lua.collect_garbage ();
655 /* reset dynamic state version back to default */
656 Stateful::loading_state_version = 0;
658 _butler->drop_references ();
662 delete _all_route_group;
664 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
665 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
669 if (click_data != default_click) {
670 delete [] click_data;
673 if (click_emphasis_data != default_click_emphasis) {
674 delete [] click_emphasis_data;
679 /* need to remove auditioner before monitoring section
680 * otherwise it is re-connected */
683 /* drop references to routes held by the monitoring section
684 * specifically _monitor_out aux/listen references */
685 remove_monitor_section();
687 /* clear out any pending dead wood from RCU managed objects */
692 AudioDiskstream::free_working_buffers();
694 /* tell everyone who is still standing that we're about to die */
697 /* tell everyone to drop references and delete objects as we go */
699 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
700 RegionFactory::delete_all_regions ();
702 /* Do this early so that VCAs no longer hold references to routes */
704 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
707 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
709 /* reset these three references to special routes before we do the usual route delete thing */
711 _master_out.reset ();
712 _monitor_out.reset ();
715 RCUWriter<RouteList> writer (routes);
716 boost::shared_ptr<RouteList> r = writer.get_copy ();
718 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
719 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
720 (*i)->drop_references ();
724 /* writer goes out of scope and updates master */
729 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
730 Glib::Threads::Mutex::Lock lm (source_lock);
731 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
732 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
733 i->second->drop_references ();
739 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
742 emit_thread_terminate ();
744 pthread_cond_destroy (&_rt_emit_cond);
745 pthread_mutex_destroy (&_rt_emit_mutex);
747 pthread_cond_destroy (&_auto_connect_cond);
748 pthread_mutex_destroy (&_auto_connect_mutex);
750 delete _scene_changer; _scene_changer = 0;
751 delete midi_control_ui; midi_control_ui = 0;
753 delete _mmc; _mmc = 0;
754 delete _midi_ports; _midi_ports = 0;
755 delete _locations; _locations = 0;
760 /* clear event queue, the session is gone, nobody is interested in
761 * those anymore, but they do leak memory if not removed
763 while (!immediate_events.empty ()) {
764 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
765 SessionEvent *ev = immediate_events.front ();
766 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
767 immediate_events.pop_front ();
771 case SessionEvent::AutoLoop:
772 case SessionEvent::AutoLoopDeclick:
773 case SessionEvent::Skip:
774 case SessionEvent::PunchIn:
775 case SessionEvent::PunchOut:
776 case SessionEvent::StopOnce:
777 case SessionEvent::RangeStop:
778 case SessionEvent::RangeLocate:
782 case SessionEvent::RealTimeOperation:
789 del = del && !_remove_event (ev);
796 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
798 BOOST_SHOW_POINTERS ();
802 Session::setup_ltc ()
806 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
807 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
809 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
810 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
813 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
814 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
816 reconnect_ltc_input ();
819 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
820 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
823 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
824 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
826 reconnect_ltc_output ();
829 /* fix up names of LTC ports because we don't want the normal
830 * IO style of NAME/TYPE-{in,out}N
833 _ltc_input->nth (0)->set_name (X_("LTC-in"));
834 _ltc_output->nth (0)->set_name (X_("LTC-out"));
838 Session::setup_click ()
842 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
843 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
845 _click_io.reset (new ClickIO (*this, X_("Click")));
846 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
847 _click_gain->activate ();
849 setup_click_state (state_tree->root());
851 setup_click_state (0);
856 Session::setup_click_state (const XMLNode* node)
858 const XMLNode* child = 0;
860 if (node && (child = find_named_node (*node, "Click")) != 0) {
862 /* existing state for Click */
865 if (Stateful::loading_state_version < 3000) {
866 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
868 const XMLNodeList& children (child->children());
869 XMLNodeList::const_iterator i = children.begin();
870 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
872 if (i != children.end()) {
873 c = _click_gain->set_state (**i, Stateful::loading_state_version);
879 _clicking = Config->get_clicking ();
883 error << _("could not setup Click I/O") << endmsg;
890 /* default state for Click: dual-mono to first 2 physical outputs */
893 _engine.get_physical_outputs (DataType::AUDIO, outs);
895 for (uint32_t physport = 0; physport < 2; ++physport) {
896 if (outs.size() > physport) {
897 if (_click_io->add_port (outs[physport], this)) {
898 // relax, even though its an error
903 if (_click_io->n_ports () > ChanCount::ZERO) {
904 _clicking = Config->get_clicking ();
910 Session::setup_bundles ()
914 RCUWriter<BundleList> writer (_bundles);
915 boost::shared_ptr<BundleList> b = writer.get_copy ();
916 for (BundleList::iterator i = b->begin(); i != b->end();) {
917 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
925 vector<string> inputs[DataType::num_types];
926 vector<string> outputs[DataType::num_types];
927 for (uint32_t i = 0; i < DataType::num_types; ++i) {
928 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
929 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
932 /* Create a set of Bundle objects that map
933 to the physical I/O currently available. We create both
934 mono and stereo bundles, so that the common cases of mono
935 and stereo tracks get bundles to put in their mixer strip
936 in / out menus. There may be a nicer way of achieving that;
937 it doesn't really scale that well to higher channel counts
940 /* mono output bundles */
942 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
944 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
946 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
948 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
951 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
952 c->add_channel (_("mono"), DataType::AUDIO);
953 c->set_port (0, outputs[DataType::AUDIO][np]);
955 add_bundle (c, false);
958 /* stereo output bundles */
960 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
961 if (np + 1 < outputs[DataType::AUDIO].size()) {
963 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
964 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
965 c->add_channel (_("L"), DataType::AUDIO);
966 c->set_port (0, outputs[DataType::AUDIO][np]);
967 c->add_channel (_("R"), DataType::AUDIO);
968 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
970 add_bundle (c, false);
974 /* mono input bundles */
976 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
978 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
980 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
982 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
985 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
986 c->add_channel (_("mono"), DataType::AUDIO);
987 c->set_port (0, inputs[DataType::AUDIO][np]);
989 add_bundle (c, false);
992 /* stereo input bundles */
994 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
995 if (np + 1 < inputs[DataType::AUDIO].size()) {
997 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
999 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1000 c->add_channel (_("L"), DataType::AUDIO);
1001 c->set_port (0, inputs[DataType::AUDIO][np]);
1002 c->add_channel (_("R"), DataType::AUDIO);
1003 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1005 add_bundle (c, false);
1009 /* MIDI input bundles */
1011 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1012 string n = inputs[DataType::MIDI][np];
1013 std::string pn = _engine.get_pretty_name_by_name (n);
1017 boost::erase_first (n, X_("alsa_pcm:"));
1019 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1020 c->add_channel ("", DataType::MIDI);
1021 c->set_port (0, inputs[DataType::MIDI][np]);
1022 add_bundle (c, false);
1025 /* MIDI output bundles */
1027 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1028 string n = outputs[DataType::MIDI][np];
1029 std::string pn = _engine.get_pretty_name_by_name (n);
1033 boost::erase_first (n, X_("alsa_pcm:"));
1035 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1036 c->add_channel ("", DataType::MIDI);
1037 c->set_port (0, outputs[DataType::MIDI][np]);
1038 add_bundle (c, false);
1041 // we trust the backend to only calls us if there's a change
1042 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1046 Session::auto_connect_master_bus ()
1048 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1052 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1053 // In this case it means "Multi Out" output mode
1054 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1058 /* if requested auto-connect the outputs to the first N physical ports.
1061 uint32_t limit = _master_out->n_outputs().n_total();
1062 vector<string> outputs[DataType::num_types];
1064 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1065 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1068 for (uint32_t n = 0; n < limit; ++n) {
1069 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1071 if (outputs[p->type()].size() > n) {
1072 connect_to = outputs[p->type()][n];
1075 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1076 if (_master_out->output()->connect (p, connect_to, this)) {
1077 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1086 Session::remove_monitor_section ()
1088 if (!_monitor_out || Profile->get_trx()) {
1092 /* force reversion to Solo-In-Place */
1093 Config->set_solo_control_is_listen_control (false);
1095 /* if we are auditioning, cancel it ... this is a workaround
1096 to a problem (auditioning does not execute the process graph,
1097 which is needed to remove routes when using >1 core for processing)
1102 /* Hold process lock while doing this so that we don't hear bits and
1103 * pieces of audio as we work on each route.
1106 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1108 /* Connect tracks to monitor section. Note that in an
1109 existing session, the internal sends will already exist, but we want the
1110 routes to notice that they connect to the control out specifically.
1114 boost::shared_ptr<RouteList> r = routes.reader ();
1115 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1117 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1119 if ((*x)->is_monitor()) {
1121 } else if ((*x)->is_master()) {
1124 (*x)->remove_aux_or_listen (_monitor_out);
1129 remove_route (_monitor_out);
1130 if (_state_of_the_state & Deletion) {
1134 auto_connect_master_bus ();
1137 auditioner->connect ();
1140 Config->ParameterChanged ("use-monitor-bus");
1144 Session::add_monitor_section ()
1148 if (_monitor_out || !_master_out || Profile->get_trx()) {
1152 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1158 BOOST_MARK_ROUTE(r);
1161 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1162 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1163 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1165 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1170 add_routes (rl, false, false, false);
1172 assert (_monitor_out);
1174 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1175 are undefined, at best.
1178 uint32_t limit = _monitor_out->n_inputs().n_audio();
1182 /* connect the inputs to the master bus outputs. this
1183 * represents a separate data feed from the internal sends from
1184 * each route. as of jan 2011, it allows the monitor section to
1185 * conditionally ignore either the internal sends or the normal
1186 * input feed, but we should really find a better way to do
1190 _master_out->output()->disconnect (this);
1192 for (uint32_t n = 0; n < limit; ++n) {
1193 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1194 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1197 string connect_to = o->name();
1198 if (_monitor_out->input()->connect (p, connect_to, this)) {
1199 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1207 /* if monitor section is not connected, connect it to physical outs
1210 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1212 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1214 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1217 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1219 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1220 Config->get_monitor_bus_preferred_bundle())
1226 /* Monitor bus is audio only */
1228 vector<string> outputs[DataType::num_types];
1230 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1231 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1234 uint32_t mod = outputs[DataType::AUDIO].size();
1235 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1239 for (uint32_t n = 0; n < limit; ++n) {
1241 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1243 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1244 connect_to = outputs[DataType::AUDIO][n % mod];
1247 if (!connect_to.empty()) {
1248 if (_monitor_out->output()->connect (p, connect_to, this)) {
1249 error << string_compose (
1250 _("cannot connect control output %1 to %2"),
1261 /* Hold process lock while doing this so that we don't hear bits and
1262 * pieces of audio as we work on each route.
1265 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1267 /* Connect tracks to monitor section. Note that in an
1268 existing session, the internal sends will already exist, but we want the
1269 routes to notice that they connect to the control out specifically.
1273 boost::shared_ptr<RouteList> rls = routes.reader ();
1275 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1277 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1279 if ((*x)->is_monitor()) {
1281 } else if ((*x)->is_master()) {
1284 (*x)->enable_monitor_send ();
1289 auditioner->connect ();
1291 Config->ParameterChanged ("use-monitor-bus");
1295 Session::reset_monitor_section ()
1297 /* Process lock should be held by the caller.*/
1299 if (!_monitor_out || Profile->get_trx()) {
1303 uint32_t limit = _master_out->n_outputs().n_audio();
1305 /* connect the inputs to the master bus outputs. this
1306 * represents a separate data feed from the internal sends from
1307 * each route. as of jan 2011, it allows the monitor section to
1308 * conditionally ignore either the internal sends or the normal
1309 * input feed, but we should really find a better way to do
1313 _master_out->output()->disconnect (this);
1314 _monitor_out->output()->disconnect (this);
1316 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1317 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1319 for (uint32_t n = 0; n < limit; ++n) {
1320 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1321 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1324 string connect_to = o->name();
1325 if (_monitor_out->input()->connect (p, connect_to, this)) {
1326 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1333 /* connect monitor section to physical outs
1336 if (Config->get_auto_connect_standard_busses()) {
1338 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1340 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1343 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1345 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1346 Config->get_monitor_bus_preferred_bundle())
1352 /* Monitor bus is audio only */
1354 vector<string> outputs[DataType::num_types];
1356 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1357 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1360 uint32_t mod = outputs[DataType::AUDIO].size();
1361 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1365 for (uint32_t n = 0; n < limit; ++n) {
1367 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1369 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1370 connect_to = outputs[DataType::AUDIO][n % mod];
1373 if (!connect_to.empty()) {
1374 if (_monitor_out->output()->connect (p, connect_to, this)) {
1375 error << string_compose (
1376 _("cannot connect control output %1 to %2"),
1387 /* Connect tracks to monitor section. Note that in an
1388 existing session, the internal sends will already exist, but we want the
1389 routes to notice that they connect to the control out specifically.
1393 boost::shared_ptr<RouteList> rls = routes.reader ();
1395 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1397 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1399 if ((*x)->is_monitor()) {
1401 } else if ((*x)->is_master()) {
1404 (*x)->enable_monitor_send ();
1410 Session::hookup_io ()
1412 /* stop graph reordering notifications from
1413 causing resorts, etc.
1416 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1420 /* we delay creating the auditioner till now because
1421 it makes its own connections to ports.
1425 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1427 throw failed_constructor ();
1429 a->use_new_diskstream ();
1433 catch (failed_constructor& err) {
1434 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1438 /* load bundles, which we may have postponed earlier on */
1439 if (_bundle_xml_node) {
1440 load_bundles (*_bundle_xml_node);
1441 delete _bundle_xml_node;
1444 /* Tell all IO objects to connect themselves together */
1446 IO::enable_connecting ();
1448 /* Now tell all "floating" ports to connect to whatever
1449 they should be connected to.
1452 AudioEngine::instance()->reconnect_ports ();
1454 /* Anyone who cares about input state, wake up and do something */
1456 IOConnectionsComplete (); /* EMIT SIGNAL */
1458 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1460 /* now handle the whole enchilada as if it was one
1461 graph reorder event.
1466 /* update the full solo state, which can't be
1467 correctly determined on a per-route basis, but
1468 needs the global overview that only the session
1472 update_route_solo_state ();
1476 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1478 boost::shared_ptr<Track> track = wp.lock ();
1483 boost::shared_ptr<Playlist> playlist;
1485 if ((playlist = track->playlist()) != 0) {
1486 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1487 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1488 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1493 Session::record_enabling_legal () const
1495 /* this used to be in here, but survey says.... we don't need to restrict it */
1496 // if (record_status() == Recording) {
1500 if (Config->get_all_safe()) {
1507 Session::set_track_monitor_input_status (bool yn)
1509 boost::shared_ptr<RouteList> rl = routes.reader ();
1510 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1511 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1512 if (tr && tr->rec_enable_control()->get_value()) {
1513 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1514 tr->request_input_monitoring (yn);
1520 Session::auto_punch_start_changed (Location* location)
1522 replace_event (SessionEvent::PunchIn, location->start());
1524 if (get_record_enabled() && config.get_punch_in()) {
1525 /* capture start has been changed, so save new pending state */
1526 save_state ("", true);
1531 Session::auto_punch_end_changed (Location* location)
1533 framepos_t when_to_stop = location->end();
1534 // when_to_stop += _worst_output_latency + _worst_input_latency;
1535 replace_event (SessionEvent::PunchOut, when_to_stop);
1539 Session::auto_punch_changed (Location* location)
1541 framepos_t when_to_stop = location->end();
1543 replace_event (SessionEvent::PunchIn, location->start());
1544 //when_to_stop += _worst_output_latency + _worst_input_latency;
1545 replace_event (SessionEvent::PunchOut, when_to_stop);
1548 /** @param loc A loop location.
1549 * @param pos Filled in with the start time of the required fade-out (in session frames).
1550 * @param length Filled in with the length of the required fade-out.
1553 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1555 pos = max (loc->start(), loc->end() - 64);
1556 length = loc->end() - pos;
1560 Session::auto_loop_changed (Location* location)
1562 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1565 auto_loop_declick_range (location, dcp, dcl);
1567 if (transport_rolling() && play_loop) {
1569 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1571 // if (_transport_frame > location->end()) {
1573 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1574 // relocate to beginning of loop
1575 clear_events (SessionEvent::LocateRoll);
1577 request_locate (location->start(), true);
1580 else if (Config->get_seamless_loop() && !loop_changing) {
1582 // schedule a locate-roll to refill the diskstreams at the
1583 // previous loop end
1584 loop_changing = true;
1586 if (location->end() > last_loopend) {
1587 clear_events (SessionEvent::LocateRoll);
1588 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1594 clear_events (SessionEvent::AutoLoopDeclick);
1595 clear_events (SessionEvent::AutoLoop);
1598 /* possibly move playhead if not rolling; if we are rolling we'll move
1599 to the loop start on stop if that is appropriate.
1604 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1605 if (pos == location->start()) {
1606 request_locate (pos);
1611 last_loopend = location->end();
1616 Session::set_auto_punch_location (Location* location)
1620 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1621 punch_connections.drop_connections();
1622 existing->set_auto_punch (false, this);
1623 remove_event (existing->start(), SessionEvent::PunchIn);
1624 clear_events (SessionEvent::PunchOut);
1625 auto_punch_location_changed (0);
1630 if (location == 0) {
1634 if (location->end() <= location->start()) {
1635 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1639 punch_connections.drop_connections ();
1641 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1642 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1643 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1645 location->set_auto_punch (true, this);
1647 auto_punch_changed (location);
1649 auto_punch_location_changed (location);
1653 Session::set_session_extents (framepos_t start, framepos_t end)
1656 if ((existing = _locations->session_range_location()) == 0) {
1657 //if there is no existing session, we need to make a new session location (should never happen)
1658 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1662 error << _("Session: you can't use that location for session start/end)") << endmsg;
1666 existing->set( start, end );
1672 Session::set_auto_loop_location (Location* location)
1676 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1677 loop_connections.drop_connections ();
1678 existing->set_auto_loop (false, this);
1679 remove_event (existing->end(), SessionEvent::AutoLoop);
1682 auto_loop_declick_range (existing, dcp, dcl);
1683 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1684 auto_loop_location_changed (0);
1689 if (location == 0) {
1693 if (location->end() <= location->start()) {
1694 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1698 last_loopend = location->end();
1700 loop_connections.drop_connections ();
1702 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1703 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1704 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1705 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1707 location->set_auto_loop (true, this);
1709 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1710 // set all tracks to use internal looping
1711 boost::shared_ptr<RouteList> rl = routes.reader ();
1712 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1713 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1714 if (tr && !tr->hidden()) {
1715 tr->set_loop (location);
1720 /* take care of our stuff first */
1722 auto_loop_changed (location);
1724 /* now tell everyone else */
1726 auto_loop_location_changed (location);
1730 Session::update_marks (Location*)
1736 Session::update_skips (Location* loc, bool consolidate)
1738 if (_ignore_skips_updates) {
1742 Locations::LocationList skips;
1745 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1746 consolidate_skips (loc);
1749 sync_locations_to_skips ();
1755 Session::consolidate_skips (Location* loc)
1757 Locations::LocationList all_locations = _locations->list ();
1759 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1761 if (!(*l)->is_skip ()) {
1766 /* don't test against self */
1773 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1774 case Evoral::OverlapInternal:
1775 case Evoral::OverlapExternal:
1776 case Evoral::OverlapStart:
1777 case Evoral::OverlapEnd:
1778 /* adjust new location to cover existing one */
1779 loc->set_start (min (loc->start(), (*l)->start()));
1780 loc->set_end (max (loc->end(), (*l)->end()));
1781 /* we don't need this one any more */
1782 _locations->remove (*l);
1783 /* the location has been deleted, so remove reference to it in our local list */
1784 l = all_locations.erase (l);
1787 case Evoral::OverlapNone:
1795 Session::sync_locations_to_skips ()
1797 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1798 * Session::_sync_locations_to_skips() from the audioengine thread.
1800 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1804 Session::_sync_locations_to_skips ()
1806 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1808 Locations::LocationList const & locs (_locations->list());
1810 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1812 Location* location = *i;
1814 if (location->is_skip() && location->is_skipping()) {
1815 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1823 Session::location_added (Location *location)
1825 if (location->is_auto_punch()) {
1826 set_auto_punch_location (location);
1829 if (location->is_auto_loop()) {
1830 set_auto_loop_location (location);
1833 if (location->is_session_range()) {
1834 /* no need for any signal handling or event setting with the session range,
1835 because we keep a direct reference to it and use its start/end directly.
1837 _session_range_location = location;
1840 if (location->is_mark()) {
1841 /* listen for per-location signals that require us to do any * global updates for marks */
1843 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1844 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1845 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1846 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1849 if (location->is_skip()) {
1850 /* listen for per-location signals that require us to update skip-locate events */
1852 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1853 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1854 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1855 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1857 update_skips (location, true);
1864 Session::location_removed (Location *location)
1866 if (location->is_auto_loop()) {
1867 set_auto_loop_location (0);
1868 set_track_loop (false);
1871 if (location->is_auto_punch()) {
1872 set_auto_punch_location (0);
1875 if (location->is_session_range()) {
1876 /* this is never supposed to happen */
1877 error << _("programming error: session range removed!") << endl;
1880 if (location->is_skip()) {
1882 update_skips (location, false);
1889 Session::locations_changed ()
1891 _locations->apply (*this, &Session::_locations_changed);
1895 Session::_locations_changed (const Locations::LocationList& locations)
1897 /* There was some mass-change in the Locations object.
1899 We might be re-adding a location here but it doesn't actually matter
1900 for all the locations that the Session takes an interest in.
1904 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1905 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1906 location_added (*i);
1910 update_skips (NULL, false);
1914 Session::enable_record ()
1916 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1917 /* no recording at anything except normal speed */
1922 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1924 if (rs == Recording) {
1928 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1930 _last_record_location = _transport_frame;
1931 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1933 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1934 set_track_monitor_input_status (true);
1937 RecordStateChanged ();
1944 Session::set_all_tracks_record_enabled (bool enable )
1946 boost::shared_ptr<RouteList> rl = routes.reader();
1947 set_controls (route_list_to_control_list (rl, &Track::rec_enable_control), enable, Controllable::NoGroup);
1951 Session::disable_record (bool rt_context, bool force)
1955 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1957 if (!Config->get_latched_record_enable () || force) {
1958 g_atomic_int_set (&_record_status, Disabled);
1959 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1961 if (rs == Recording) {
1962 g_atomic_int_set (&_record_status, Enabled);
1966 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1967 set_track_monitor_input_status (false);
1970 RecordStateChanged (); /* emit signal */
1973 remove_pending_capture_state ();
1979 Session::step_back_from_record ()
1981 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1983 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1984 set_track_monitor_input_status (false);
1987 RecordStateChanged (); /* emit signal */
1992 Session::maybe_enable_record ()
1994 if (_step_editors > 0) {
1998 g_atomic_int_set (&_record_status, Enabled);
2000 /* This function is currently called from somewhere other than an RT thread.
2001 This save_state() call therefore doesn't impact anything. Doing it here
2002 means that we save pending state of which sources the next record will use,
2003 which gives us some chance of recovering from a crash during the record.
2006 save_state ("", true);
2008 if (_transport_speed) {
2009 if (!config.get_punch_in()) {
2013 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2014 RecordStateChanged (); /* EMIT SIGNAL */
2021 Session::audible_frame () const
2027 offset = worst_playback_latency ();
2029 if (synced_to_engine()) {
2030 /* Note: this is basically just sync-to-JACK */
2031 tf = _engine.transport_frame();
2033 tf = _transport_frame;
2038 if (!non_realtime_work_pending()) {
2042 /* Check to see if we have passed the first guaranteed
2043 audible frame past our last start position. if not,
2044 return that last start point because in terms
2045 of audible frames, we have not moved yet.
2047 `Start position' in this context means the time we last
2048 either started, located, or changed transport direction.
2051 if (_transport_speed > 0.0f) {
2053 if (!play_loop || !have_looped) {
2054 if (tf < _last_roll_or_reversal_location + offset) {
2055 return _last_roll_or_reversal_location;
2063 } else if (_transport_speed < 0.0f) {
2065 /* XXX wot? no backward looping? */
2067 if (tf > _last_roll_or_reversal_location - offset) {
2068 return _last_roll_or_reversal_location;
2080 Session::set_frame_rate (framecnt_t frames_per_second)
2082 /** \fn void Session::set_frame_size(framecnt_t)
2083 the AudioEngine object that calls this guarantees
2084 that it will not be called while we are also in
2085 ::process(). Its fine to do things that block
2089 if (_base_frame_rate == 0) {
2090 _base_frame_rate = frames_per_second;
2092 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2093 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2095 _nominal_frame_rate = frames_per_second;
2100 reset_write_sources (false);
2102 // XXX we need some equivalent to this, somehow
2103 // SndFileSource::setup_standard_crossfades (frames_per_second);
2107 /* XXX need to reset/reinstantiate all LADSPA plugins */
2111 Session::set_block_size (pframes_t nframes)
2113 /* the AudioEngine guarantees
2114 that it will not be called while we are also in
2115 ::process(). It is therefore fine to do things that block
2120 current_block_size = nframes;
2124 boost::shared_ptr<RouteList> r = routes.reader ();
2126 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2127 (*i)->set_block_size (nframes);
2130 boost::shared_ptr<RouteList> rl = routes.reader ();
2131 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2132 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2134 tr->set_block_size (nframes);
2138 set_worst_io_latencies ();
2144 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2146 boost::shared_ptr<Route> r2;
2148 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2149 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2153 /* make a copy of the existing list of routes that feed r1 */
2155 Route::FedBy existing (r1->fed_by());
2157 /* for each route that feeds r1, recurse, marking it as feeding
2161 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2162 if (!(r2 = i->r.lock ())) {
2163 /* (*i) went away, ignore it */
2167 /* r2 is a route that feeds r1 which somehow feeds base. mark
2168 base as being fed by r2
2171 rbase->add_fed_by (r2, i->sends_only);
2175 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2179 if (r1->feeds (r2) && r2->feeds (r1)) {
2183 /* now recurse, so that we can mark base as being fed by
2184 all routes that feed r2
2187 trace_terminal (r2, rbase);
2194 Session::resort_routes ()
2196 /* don't do anything here with signals emitted
2197 by Routes during initial setup or while we
2198 are being destroyed.
2201 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2205 if (_route_deletion_in_progress) {
2210 RCUWriter<RouteList> writer (routes);
2211 boost::shared_ptr<RouteList> r = writer.get_copy ();
2212 resort_routes_using (r);
2213 /* writer goes out of scope and forces update */
2217 if (DEBUG_ENABLED(DEBUG::Graph)) {
2218 boost::shared_ptr<RouteList> rl = routes.reader ();
2219 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2220 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2222 const Route::FedBy& fb ((*i)->fed_by());
2224 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2225 boost::shared_ptr<Route> sf = f->r.lock();
2227 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2236 /** This is called whenever we need to rebuild the graph of how we will process
2238 * @param r List of routes, in any order.
2242 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2244 /* We are going to build a directed graph of our routes;
2245 this is where the edges of that graph are put.
2250 /* Go through all routes doing two things:
2252 * 1. Collect the edges of the route graph. Each of these edges
2253 * is a pair of routes, one of which directly feeds the other
2254 * either by a JACK connection or by an internal send.
2256 * 2. Begin the process of making routes aware of which other
2257 * routes directly or indirectly feed them. This information
2258 * is used by the solo code.
2261 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2263 /* Clear out the route's list of direct or indirect feeds */
2264 (*i)->clear_fed_by ();
2266 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2268 bool via_sends_only;
2270 /* See if this *j feeds *i according to the current state of the JACK
2271 connections and internal sends.
2273 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2274 /* add the edge to the graph (part #1) */
2275 edges.add (*j, *i, via_sends_only);
2276 /* tell the route (for part #2) */
2277 (*i)->add_fed_by (*j, via_sends_only);
2282 /* Attempt a topological sort of the route graph */
2283 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2285 if (sorted_routes) {
2286 /* We got a satisfactory topological sort, so there is no feedback;
2289 Note: the process graph rechain does not require a
2290 topologically-sorted list, but hey ho.
2292 if (_process_graph) {
2293 _process_graph->rechain (sorted_routes, edges);
2296 _current_route_graph = edges;
2298 /* Complete the building of the routes' lists of what directly
2299 or indirectly feeds them.
2301 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2302 trace_terminal (*i, *i);
2305 *r = *sorted_routes;
2308 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2309 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2310 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2311 (*i)->name(), (*i)->order_key ()));
2315 SuccessfulGraphSort (); /* EMIT SIGNAL */
2318 /* The topological sort failed, so we have a problem. Tell everyone
2319 and stick to the old graph; this will continue to be processed, so
2320 until the feedback is fixed, what is played back will not quite
2321 reflect what is actually connected. Note also that we do not
2322 do trace_terminal here, as it would fail due to an endless recursion,
2323 so the solo code will think that everything is still connected
2327 FeedbackDetected (); /* EMIT SIGNAL */
2332 /** Find a route name starting with \a base, maybe followed by the
2333 * lowest \a id. \a id will always be added if \a definitely_add_number
2334 * is true on entry; otherwise it will only be added if required
2335 * to make the name unique.
2337 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2338 * The available route name with the lowest ID will be used, and \a id
2339 * will be set to the ID.
2341 * \return false if a route name could not be found, and \a track_name
2342 * and \a id do not reflect a free route name.
2345 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2347 /* the base may conflict with ports that do not belong to existing
2348 routes, but hidden objects like the click track. So check port names
2349 before anything else.
2352 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2353 if (base == *reserved) {
2354 /* Check if this reserved name already exists, and if
2355 so, disallow it without a numeric suffix.
2357 if (route_by_name (*reserved)) {
2358 definitely_add_number = true;
2367 if (!definitely_add_number && route_by_name (base) == 0) {
2368 /* juse use the base */
2374 name = string_compose ("%1 %2", base, id);
2376 if (route_by_name (name) == 0) {
2382 } while (id < (UINT_MAX-1));
2387 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2389 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2391 in = ChanCount::ZERO;
2392 out = ChanCount::ZERO;
2394 boost::shared_ptr<RouteList> r = routes.reader ();
2396 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2397 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2398 if (tr && !tr->is_auditioner()) {
2399 in += tr->n_inputs();
2400 out += tr->n_outputs();
2406 Session::default_track_name_pattern (DataType t)
2409 case DataType::AUDIO:
2410 if (Profile->get_trx()) {
2417 case DataType::MIDI:
2424 /** Caller must not hold process lock
2425 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2426 * @param instrument plugin info for the instrument to insert pre-fader, if any
2428 list<boost::shared_ptr<MidiTrack> >
2429 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2430 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template, Plugin::PresetRecord* pset)
2433 uint32_t track_id = 0;
2435 RouteList new_routes;
2436 list<boost::shared_ptr<MidiTrack> > ret;
2438 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2439 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2442 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2443 error << "cannot find name for new midi track" << endmsg;
2447 boost::shared_ptr<MidiTrack> track;
2450 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2452 if (track->init ()) {
2456 if (Profile->get_mixbus ()) {
2457 track->set_strict_io (true);
2460 track->use_new_diskstream();
2462 BOOST_MARK_TRACK (track);
2465 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2466 if (track->input()->ensure_io (input, false, this)) {
2467 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2471 if (track->output()->ensure_io (output, false, this)) {
2472 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2477 track->non_realtime_input_change();
2480 route_group->add (track);
2483 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2485 if (Config->get_remote_model() == UserOrdered) {
2486 track->set_remote_control_id (next_control_id());
2489 new_routes.push_back (track);
2490 ret.push_back (track);
2492 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2495 catch (failed_constructor &err) {
2496 error << _("Session: could not create new midi track.") << endmsg;
2500 catch (AudioEngine::PortRegistrationFailure& pfe) {
2502 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;
2510 if (!new_routes.empty()) {
2511 StateProtector sp (this);
2512 if (Profile->get_trx()) {
2513 add_routes (new_routes, false, false, false);
2515 add_routes (new_routes, true, true, false);
2519 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2520 PluginPtr plugin = instrument->load (*this);
2522 plugin->load_preset (*pset);
2524 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2525 (*r)->add_processor (p, PreFader);
2535 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset)
2538 uint32_t bus_id = 0;
2542 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2545 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2546 error << "cannot find name for new midi bus" << endmsg;
2551 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
2557 if (Profile->get_mixbus ()) {
2558 bus->set_strict_io (true);
2561 BOOST_MARK_ROUTE(bus);
2564 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2566 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2567 error << _("cannot configure new midi bus input") << endmsg;
2572 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2573 error << _("cannot configure new midi bus output") << endmsg;
2579 route_group->add (bus);
2581 if (Config->get_remote_model() == UserOrdered) {
2582 bus->set_remote_control_id (next_control_id());
2585 ret.push_back (bus);
2586 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2590 catch (failed_constructor &err) {
2591 error << _("Session: could not create new audio route.") << endmsg;
2595 catch (AudioEngine::PortRegistrationFailure& pfe) {
2596 error << pfe.what() << endmsg;
2606 StateProtector sp (this);
2607 add_routes (ret, false, false, false);
2610 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2611 PluginPtr plugin = instrument->load (*this);
2613 plugin->load_preset (*pset);
2615 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2616 (*r)->add_processor (p, PreFader);
2627 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2629 boost::shared_ptr<Route> midi_track (wmt.lock());
2635 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2637 if (change.after.n_audio() <= change.before.n_audio()) {
2641 /* new audio ports: make sure the audio goes somewhere useful,
2642 * unless the user has no-auto-connect selected.
2644 * The existing ChanCounts don't matter for this call as they are only
2645 * to do with matching input and output indices, and we are only changing
2648 auto_connect_route (midi_track, false, ChanCount(), change.before);
2652 #ifdef USE_TRACKS_CODE_FEATURES
2655 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2657 return route1->remote_control_id() < route2->remote_control_id();
2661 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2663 // it is not allowed to perform connection
2664 if (!IO::connecting_legal) {
2668 // if we are deleting routes we will call this once at the end
2669 if (_route_deletion_in_progress) {
2673 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2679 // We need to disconnect the route's inputs and outputs first
2680 // basing on autoconnect configuration
2681 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2682 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2684 ChanCount existing_inputs;
2685 ChanCount existing_outputs;
2686 count_existing_track_channels (existing_inputs, existing_outputs);
2688 //ChanCount inputs = ChanCount::ZERO;
2689 //ChanCount outputs = ChanCount::ZERO;
2691 RouteList existing_routes = *routes.reader ();
2692 existing_routes.sort (compare_routes_by_remote_id);
2695 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2697 vector<string> physinputs;
2698 vector<string> physoutputs;
2700 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2701 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2703 uint32_t input_n = 0;
2704 uint32_t output_n = 0;
2705 RouteList::iterator rIter = existing_routes.begin();
2706 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2707 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2708 for (; rIter != existing_routes.end(); ++rIter) {
2709 if (*rIter == _master_out || *rIter == _monitor_out ) {
2713 if (current_output_auto_connection == AutoConnectPhysical) {
2714 (*rIter)->amp()->deactivate();
2715 } else if (current_output_auto_connection == AutoConnectMaster) {
2716 (*rIter)->amp()->activate();
2719 if (reconnectIputs) {
2720 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2722 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2724 if (current_input_auto_connection & AutoConnectPhysical) {
2726 if ( input_n == physinputs.size() ) {
2730 string port = physinputs[input_n];
2732 if (port.empty() ) {
2733 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2736 //GZ: check this; could be heavy
2737 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2743 if (reconnectOutputs) {
2745 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2746 if (current_output_auto_connection & AutoConnectPhysical) {
2748 //GZ: check this; could be heavy
2749 (*rIter)->output()->disconnect (this);
2750 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2752 //GZ: check this; could be heavy
2753 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2755 } else if (current_output_auto_connection & AutoConnectMaster){
2757 if (!reconnect_master) {
2761 //GZ: check this; could be heavy
2762 (*rIter)->output()->disconnect (this);
2765 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2766 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2768 error << error << "Master bus is not available" << endmsg;
2773 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2774 if (current_output_auto_connection & AutoConnectPhysical) {
2776 if ( output_n == physoutputs.size() ) {
2780 string port = physoutputs[output_n];
2782 if (port.empty() ) {
2783 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2786 //GZ: check this; could be heavy
2787 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2790 } else if (current_output_auto_connection & AutoConnectMaster) {
2792 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2796 // connect to master bus
2797 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2799 if (port.empty() ) {
2800 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2804 //GZ: check this; could be heavy
2805 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2812 _master_out->output()->disconnect (this);
2813 auto_connect_master_bus ();
2818 session_routes_reconnected (); /* EMIT SIGNAL */
2822 Session::reconnect_midi_scene_ports(bool inputs)
2826 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2828 scene_in_ptr->disconnect_all ();
2830 std::vector<EngineStateController::MidiPortState> midi_port_states;
2831 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2833 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2835 for (; state_iter != midi_port_states.end(); ++state_iter) {
2836 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2837 scene_in_ptr->connect (state_iter->name);
2844 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2846 if (scene_out_ptr ) {
2847 scene_out_ptr->disconnect_all ();
2849 std::vector<EngineStateController::MidiPortState> midi_port_states;
2850 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2852 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2854 for (; state_iter != midi_port_states.end(); ++state_iter) {
2855 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2856 scene_out_ptr->connect (state_iter->name);
2864 Session::reconnect_mtc_ports ()
2866 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2872 mtc_in_ptr->disconnect_all ();
2874 std::vector<EngineStateController::MidiPortState> midi_port_states;
2875 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2877 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2879 for (; state_iter != midi_port_states.end(); ++state_iter) {
2880 if (state_iter->available && state_iter->mtc_in) {
2881 mtc_in_ptr->connect (state_iter->name);
2885 if (!_midi_ports->mtc_input_port ()->connected () &&
2886 config.get_external_sync () &&
2887 (Config->get_sync_source () == MTC) ) {
2888 config.set_external_sync (false);
2891 if ( ARDOUR::Profile->get_trx () ) {
2892 // Tracks need this signal to update timecode_source_dropdown
2893 MtcOrLtcInputPortChanged (); //emit signal
2898 Session::reconnect_mmc_ports(bool inputs)
2900 if (inputs ) { // get all enabled midi input ports
2902 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2904 mmc_in_ptr->disconnect_all ();
2905 std::vector<std::string> enabled_midi_inputs;
2906 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2908 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2910 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2911 mmc_in_ptr->connect (*port_iter);
2915 } else { // get all enabled midi output ports
2917 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2919 mmc_out_ptr->disconnect_all ();
2920 std::vector<std::string> enabled_midi_outputs;
2921 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2923 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2925 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2926 mmc_out_ptr->connect (*port_iter);
2934 /** Caller must not hold process lock
2935 * @param name_template string to use for the start of the name, or "" to use "Audio".
2937 list< boost::shared_ptr<AudioTrack> >
2938 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2939 uint32_t how_many, string name_template)
2942 uint32_t track_id = 0;
2944 RouteList new_routes;
2945 list<boost::shared_ptr<AudioTrack> > ret;
2947 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2948 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2952 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2953 error << "cannot find name for new audio track" << endmsg;
2957 boost::shared_ptr<AudioTrack> track;
2960 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2962 if (track->init ()) {
2966 if (Profile->get_mixbus ()) {
2967 track->set_strict_io (true);
2971 if (ARDOUR::Profile->get_trx ()) {
2972 // TRACKS considers it's not a USE CASE, it's
2973 // a piece of behavior of the session model:
2975 // Gain for a newly created route depends on
2976 // the current output_auto_connect mode:
2978 // 0 for Stereo Out mode
2980 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2981 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
2985 track->use_new_diskstream();
2987 BOOST_MARK_TRACK (track);
2990 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2992 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2993 error << string_compose (
2994 _("cannot configure %1 in/%2 out configuration for new audio track"),
2995 input_channels, output_channels)
3000 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3001 error << string_compose (
3002 _("cannot configure %1 in/%2 out configuration for new audio track"),
3003 input_channels, output_channels)
3010 route_group->add (track);
3013 track->non_realtime_input_change();
3015 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3016 if (Config->get_remote_model() == UserOrdered) {
3017 track->set_remote_control_id (next_control_id());
3020 new_routes.push_back (track);
3021 ret.push_back (track);
3023 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3026 catch (failed_constructor &err) {
3027 error << _("Session: could not create new audio track.") << endmsg;
3031 catch (AudioEngine::PortRegistrationFailure& pfe) {
3033 error << pfe.what() << endmsg;
3041 if (!new_routes.empty()) {
3042 StateProtector sp (this);
3043 if (Profile->get_trx()) {
3044 add_routes (new_routes, false, false, false);
3046 add_routes (new_routes, true, true, false);
3053 /** Caller must not hold process lock.
3054 * @param name_template string to use for the start of the name, or "" to use "Bus".
3057 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
3060 uint32_t bus_id = 0;
3064 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3067 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3068 error << "cannot find name for new audio bus" << endmsg;
3073 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3079 if (Profile->get_mixbus ()) {
3080 bus->set_strict_io (true);
3083 BOOST_MARK_ROUTE(bus);
3086 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3088 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3089 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3090 input_channels, output_channels)
3096 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3097 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3098 input_channels, output_channels)
3105 route_group->add (bus);
3107 if (Config->get_remote_model() == UserOrdered) {
3108 bus->set_remote_control_id (next_control_id());
3111 bus->add_internal_return ();
3113 ret.push_back (bus);
3115 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3121 catch (failed_constructor &err) {
3122 error << _("Session: could not create new audio route.") << endmsg;
3126 catch (AudioEngine::PortRegistrationFailure& pfe) {
3127 error << pfe.what() << endmsg;
3137 StateProtector sp (this);
3138 if (Profile->get_trx()) {
3139 add_routes (ret, false, false, false);
3141 add_routes (ret, false, true, true); // autoconnect // outputs only
3150 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3154 if (!tree.read (template_path.c_str())) {
3158 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3162 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3165 uint32_t control_id;
3166 uint32_t number = 0;
3167 const uint32_t being_added = how_many;
3168 /* This will prevent the use of any existing XML-provided PBD::ID
3171 Stateful::ForceIDRegeneration force_ids;
3172 IO::disable_connecting ();
3174 control_id = next_control_id ();
3178 /* We're going to modify the node contents a bit so take a
3179 * copy. The node may be re-used when duplicating more than once.
3182 XMLNode node_copy (node);
3187 if (!name_base.empty()) {
3189 /* if we're adding more than one routes, force
3190 * all the names of the new routes to be
3191 * numbered, via the final parameter.
3194 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3195 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3201 string const route_name = node_copy.property(X_("name"))->value ();
3203 /* generate a new name by adding a number to the end of the template name */
3204 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3205 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3206 abort(); /*NOTREACHED*/
3210 /* set this name in the XML description that we are about to use */
3212 bool rename_playlist;
3215 rename_playlist = true;
3220 rename_playlist = false;
3223 Route::set_name_in_state (node_copy, name, rename_playlist);
3225 /* trim bitslots from listen sends so that new ones are used */
3226 XMLNodeList children = node_copy.children ();
3227 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3228 if ((*i)->name() == X_("Processor")) {
3229 /* ForceIDRegeneration does not catch the following */
3230 XMLProperty const * role = (*i)->property (X_("role"));
3231 XMLProperty const * type = (*i)->property (X_("type"));
3232 if (role && role->value() == X_("Aux")) {
3233 /* check if the target bus exists.
3234 * we should not save aux-sends in templates.
3236 XMLProperty const * target = (*i)->property (X_("target"));
3238 (*i)->add_property ("type", "dangling-aux-send");
3241 boost::shared_ptr<Route> r = route_by_id (target->value());
3242 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3243 (*i)->add_property ("type", "dangling-aux-send");
3247 if (role && role->value() == X_("Listen")) {
3248 (*i)->remove_property (X_("bitslot"));
3250 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3252 Delivery::Role xrole;
3253 uint32_t bitslot = 0;
3254 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3255 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3256 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3257 (*i)->remove_property (X_("bitslot"));
3258 (*i)->remove_property (X_("name"));
3259 (*i)->add_property ("bitslot", buf);
3260 (*i)->add_property ("name", name);
3262 else if (type && type->value() == X_("return")) {
3263 // Return::set_state() generates a new one
3264 (*i)->remove_property (X_("bitslot"));
3266 else if (type && type->value() == X_("port")) {
3267 // PortInsert::set_state() handles the bitslot
3268 (*i)->remove_property (X_("bitslot"));
3269 (*i)->add_property ("ignore-name", "1");
3274 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3277 error << _("Session: cannot create track/bus from template description") << endmsg;
3281 if (boost::dynamic_pointer_cast<Track>(route)) {
3282 /* force input/output change signals so that the new diskstream
3283 picks up the configuration of the route. During session
3284 loading this normally happens in a different way.
3287 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3289 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3290 change.after = route->input()->n_ports();
3291 route->input()->changed (change, this);
3292 change.after = route->output()->n_ports();
3293 route->output()->changed (change, this);
3296 route->set_remote_control_id (control_id);
3299 boost::shared_ptr<Track> track;
3301 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3304 track->use_new_playlist ();
3307 track->use_copy_playlist ();
3314 ret.push_back (route);
3316 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3319 catch (failed_constructor &err) {
3320 error << _("Session: could not create new route from template") << endmsg;
3324 catch (AudioEngine::PortRegistrationFailure& pfe) {
3325 error << pfe.what() << endmsg;
3334 StateProtector sp (this);
3335 if (Profile->get_trx()) {
3336 add_routes (ret, false, false, false);
3338 add_routes (ret, true, true, false);
3340 IO::enable_connecting ();
3347 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3350 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3351 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3354 error << _("Adding new tracks/busses failed") << endmsg;
3359 update_latency (true);
3360 update_latency (false);
3365 save_state (_current_snapshot_name);
3368 reassign_track_numbers();
3370 update_route_record_state ();
3372 RouteAdded (new_routes); /* EMIT SIGNAL */
3376 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3378 ChanCount existing_inputs;
3379 ChanCount existing_outputs;
3380 uint32_t order = next_control_id();
3383 if (_order_hint > -1) {
3384 order = _order_hint;
3388 count_existing_track_channels (existing_inputs, existing_outputs);
3391 RCUWriter<RouteList> writer (routes);
3392 boost::shared_ptr<RouteList> r = writer.get_copy ();
3393 r->insert (r->end(), new_routes.begin(), new_routes.end());
3395 /* if there is no control out and we're not in the middle of loading,
3396 * resort the graph here. if there is a control out, we will resort
3397 * toward the end of this method. if we are in the middle of loading,
3398 * we will resort when done.
3401 if (!_monitor_out && IO::connecting_legal) {
3402 resort_routes_using (r);
3406 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3408 boost::weak_ptr<Route> wpr (*x);
3409 boost::shared_ptr<Route> r (*x);
3411 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3412 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3413 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3415 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3416 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3418 if (r->is_master()) {
3422 if (r->is_monitor()) {
3426 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3428 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3429 track_playlist_changed (boost::weak_ptr<Track> (tr));
3430 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3432 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3434 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3435 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3439 if (input_auto_connect || output_auto_connect) {
3440 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3441 existing_inputs += r->n_inputs();
3442 existing_outputs += r->n_outputs();
3445 /* order keys are a GUI responsibility but we need to set up
3446 reasonable defaults because they also affect the remote control
3447 ID in most situations.
3450 if (!r->has_order_key ()) {
3451 if (r->is_auditioner()) {
3452 /* use an arbitrarily high value */
3453 r->set_order_key (UINT_MAX);
3455 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3456 r->set_order_key (order);
3464 if (_monitor_out && IO::connecting_legal) {
3465 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3467 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3468 if ((*x)->is_monitor()) {
3470 } else if ((*x)->is_master()) {
3473 (*x)->enable_monitor_send ();
3480 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3482 boost::shared_ptr<RouteList> r = routes.reader ();
3483 boost::shared_ptr<Send> s;
3485 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3486 if ((s = (*i)->internal_send_for (dest)) != 0) {
3487 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3493 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3495 boost::shared_ptr<RouteList> r = routes.reader ();
3496 boost::shared_ptr<Send> s;
3498 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3499 if ((s = (*i)->internal_send_for (dest)) != 0) {
3500 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3506 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3508 boost::shared_ptr<RouteList> r = routes.reader ();
3509 boost::shared_ptr<Send> s;
3511 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3512 if ((s = (*i)->internal_send_for (dest)) != 0) {
3513 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3518 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3520 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3522 boost::shared_ptr<RouteList> r = routes.reader ();
3523 boost::shared_ptr<RouteList> t (new RouteList);
3525 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3526 /* no MIDI sends because there are no MIDI busses yet */
3527 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3532 add_internal_sends (dest, p, t);
3536 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3538 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3539 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3544 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3546 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3550 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3552 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3556 if (!dest->internal_return()) {
3557 dest->add_internal_return ();
3560 sender->add_aux_send (dest, before);
3566 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3568 { // RCU Writer scope
3569 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3570 RCUWriter<RouteList> writer (routes);
3571 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3574 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3576 if (*iter == _master_out) {
3580 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3584 /* deleting the master out seems like a dumb
3585 idea, but its more of a UI policy issue
3589 if (*iter == _master_out) {
3590 _master_out = boost::shared_ptr<Route> ();
3593 if (*iter == _monitor_out) {
3594 _monitor_out.reset ();
3597 // We need to disconnect the route's inputs and outputs
3599 (*iter)->input()->disconnect (0);
3600 (*iter)->output()->disconnect (0);
3602 /* if the route had internal sends sending to it, remove them */
3603 if ((*iter)->internal_return()) {
3605 boost::shared_ptr<RouteList> r = routes.reader ();
3606 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3607 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3609 (*i)->remove_processor (s);
3614 /* if the monitoring section had a pointer to this route, remove it */
3615 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3616 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3617 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3618 (*iter)->remove_aux_or_listen (_monitor_out);
3621 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3622 if (mt && mt->step_editing()) {
3623 if (_step_editors > 0) {
3629 /* writer goes out of scope, forces route list update */
3631 } // end of RCU Writer scope
3633 update_route_solo_state ();
3634 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3635 update_latency_compensation ();
3638 /* Re-sort routes to remove the graph's current references to the one that is
3639 * going away, then flush old references out of the graph.
3640 * Wave Tracks: reconnect routes
3643 #ifdef USE_TRACKS_CODE_FEATURES
3644 reconnect_existing_routes(true, false);
3646 routes.flush (); // maybe unsafe, see below.
3650 if (_process_graph && !(_state_of_the_state & Deletion)) {
3651 _process_graph->clear_other_chain ();
3654 /* get rid of it from the dead wood collection in the route list manager */
3655 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3659 /* try to cause everyone to drop their references
3660 * and unregister ports from the backend
3663 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3664 (*iter)->drop_references ();
3667 if (_state_of_the_state & Deletion) {
3671 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3673 /* save the new state of the world */
3675 if (save_state (_current_snapshot_name)) {
3676 save_history (_current_snapshot_name);
3679 reassign_track_numbers();
3680 update_route_record_state ();
3684 Session::remove_route (boost::shared_ptr<Route> route)
3686 boost::shared_ptr<RouteList> rl (new RouteList);
3687 rl->push_back (route);
3692 Session::route_mute_changed ()
3698 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3700 boost::shared_ptr<Route> route (wpr.lock());
3706 assert (Config->get_solo_control_is_listen_control());
3708 if (route->solo_control()->soloed_by_self_or_masters()) {
3710 if (Config->get_exclusive_solo()) {
3712 RouteGroup* rg = route->route_group ();
3713 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3715 boost::shared_ptr<RouteList> r = routes.reader ();
3717 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3718 if ((*i) == route) {
3719 /* already changed */
3723 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3724 /* route does not get solo propagated to it */
3728 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3729 /* this route is a part of the same solo group as the route
3730 * that was changed. Changing that route did change or will
3731 * change all group members appropriately, so we can ignore it
3736 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3742 } else if (_listen_cnt > 0) {
3747 update_route_solo_state ();
3751 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3753 boost::shared_ptr<Route> route (wpr.lock());
3759 bool send_changed = false;
3761 if (route->solo_isolate_control()->solo_isolated()) {
3762 if (_solo_isolated_cnt == 0) {
3763 send_changed = true;
3765 _solo_isolated_cnt++;
3766 } else if (_solo_isolated_cnt > 0) {
3767 _solo_isolated_cnt--;
3768 if (_solo_isolated_cnt == 0) {
3769 send_changed = true;
3774 IsolatedChanged (); /* EMIT SIGNAL */
3779 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3781 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_changed));
3783 boost::shared_ptr<Route> route (wpr.lock());
3789 if (Config->get_solo_control_is_listen_control()) {
3790 route_listen_changed (group_override, wpr);
3794 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: self %2 masters %3 transition %4\n", route->name(), route->self_soloed(), route->solo_control()->get_masters_value(), route->solo_control()->transitioned_into_solo()));
3796 if (route->solo_control()->transitioned_into_solo() == 0) {
3797 /* route solo changed by upstream/downstream; not interesting
3800 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 not self-soloed nor soloed by master (%2), ignoring\n", route->name(), route->solo_control()->get_masters_value()));
3804 if (route->solo_control()->transitioned_into_solo() == 0) {
3805 /* reason for being soloed changed (e.g. master went away, we
3806 * took over the master state), but actual status did
3807 * not. nothing to do.
3809 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: solo change was change in reason, not status\n", route->name()));
3812 boost::shared_ptr<RouteList> r = routes.reader ();
3813 int32_t delta = route->solo_control()->transitioned_into_solo ();
3815 /* the route may be a member of a group that has shared-solo
3816 * semantics. If so, then all members of that group should follow the
3817 * solo of the changed route. But ... this is optional, controlled by a
3818 * Controllable::GroupControlDisposition.
3820 * The first argument to the signal that this method is connected to is the
3821 * GroupControlDisposition value that was used to change solo.
3823 * If the solo change was done with group semantics (either InverseGroup
3824 * (force the entire group to change even if the group shared solo is
3825 * disabled) or UseGroup (use the group, which may or may not have the
3826 * shared solo property enabled)) then as we propagate the change to
3827 * the entire session we should IGNORE THE GROUP that the changed route
3831 RouteGroup* rg = route->route_group ();
3832 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3834 if (delta == 1 && Config->get_exclusive_solo()) {
3836 /* new solo: disable all other solos, but not the group if its solo-enabled */
3838 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3840 if ((*i) == route) {
3841 /* already changed */
3845 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3846 /* route does not get solo propagated to it */
3850 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3851 /* this route is a part of the same solo group as the route
3852 * that was changed. Changing that route did change or will
3853 * change all group members appropriately, so we can ignore it
3859 (*i)->solo_control()->set_value (0.0, group_override);
3863 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3865 RouteList uninvolved;
3867 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3869 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3870 bool via_sends_only;
3871 bool in_signal_flow;
3873 if ((*i) == route) {
3874 /* already changed */
3878 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3879 /* route does not get solo propagated to it */
3883 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3884 /* this route is a part of the same solo group as the route
3885 * that was changed. Changing that route did change or will
3886 * change all group members appropriately, so we can ignore it
3892 in_signal_flow = false;
3894 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3896 if ((*i)->feeds (route, &via_sends_only)) {
3897 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3898 if (!via_sends_only) {
3899 if (!route->soloed_by_others_upstream()) {
3900 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3902 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3905 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3907 in_signal_flow = true;
3909 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3912 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3914 if (route->feeds (*i, &via_sends_only)) {
3915 /* propagate solo upstream only if routing other than
3916 sends is involved, but do consider the other route
3917 (*i) to be part of the signal flow even if only
3920 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3924 route->soloed_by_others_downstream(),
3925 route->soloed_by_others_upstream()));
3926 if (!via_sends_only) {
3927 //NB. Triggers Invert Push, which handles soloed by downstream
3928 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3929 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3931 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3933 in_signal_flow = true;
3935 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3938 if (!in_signal_flow) {
3939 uninvolved.push_back (*i);
3943 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3945 update_route_solo_state (r);
3947 /* now notify that the mute state of the routes not involved in the signal
3948 pathway of the just-solo-changed route may have altered.
3951 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3952 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3953 (*i)->act_on_mute ();
3954 (*i)->mute_control()->Changed (false, Controllable::NoGroup);
3957 SoloChanged (); /* EMIT SIGNAL */
3962 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3964 /* now figure out if anything that matters is soloed (or is "listening")*/
3966 bool something_soloed = false;
3967 bool something_listening = false;
3968 uint32_t listeners = 0;
3969 uint32_t isolated = 0;
3972 r = routes.reader();
3975 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3976 if ((*i)->can_solo()) {
3977 if (Config->get_solo_control_is_listen_control()) {
3978 if ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value()) {
3980 something_listening = true;
3983 (*i)->set_listen (false);
3984 if ((*i)->can_solo() && ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value())) {
3985 something_soloed = true;
3990 if ((*i)->solo_isolate_control()->solo_isolated()) {
3995 if (something_soloed != _non_soloed_outs_muted) {
3996 _non_soloed_outs_muted = something_soloed;
3997 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4000 if (something_listening != _listening) {
4001 _listening = something_listening;
4002 SoloActive (_listening);
4005 _listen_cnt = listeners;
4007 if (isolated != _solo_isolated_cnt) {
4008 _solo_isolated_cnt = isolated;
4009 IsolatedChanged (); /* EMIT SIGNAL */
4012 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4013 something_soloed, listeners, isolated));
4016 boost::shared_ptr<RouteList>
4017 Session::get_routes_with_internal_returns() const
4019 boost::shared_ptr<RouteList> r = routes.reader ();
4020 boost::shared_ptr<RouteList> rl (new RouteList);
4022 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4023 if ((*i)->internal_return ()) {
4031 Session::io_name_is_legal (const std::string& name)
4033 boost::shared_ptr<RouteList> r = routes.reader ();
4035 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4036 if (name == *reserved) {
4037 if (!route_by_name (*reserved)) {
4038 /* first instance of a reserved name is allowed */
4041 /* all other instances of a reserved name are not allowed */
4046 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4047 if ((*i)->name() == name) {
4051 if ((*i)->has_io_processor_named (name)) {
4060 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4063 vector<string> connections;
4065 /* if we are passed only a single route and we're not told to turn
4066 * others off, then just do the simple thing.
4069 if (flip_others == false && rl->size() == 1) {
4070 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4072 mt->set_input_active (onoff);
4077 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4079 PortSet& ps ((*rt)->input()->ports());
4081 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4082 p->get_connections (connections);
4085 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4086 routes_using_input_from (*s, rl2);
4089 /* scan all relevant routes to see if others are on or off */
4091 bool others_are_already_on = false;
4093 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4095 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4101 if ((*r) != (*rt)) {
4102 if (mt->input_active()) {
4103 others_are_already_on = true;
4106 /* this one needs changing */
4107 mt->set_input_active (onoff);
4113 /* globally reverse other routes */
4115 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4116 if ((*r) != (*rt)) {
4117 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4119 mt->set_input_active (!others_are_already_on);
4128 Session::routes_using_input_from (const string& str, RouteList& rl)
4130 boost::shared_ptr<RouteList> r = routes.reader();
4132 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4133 if ((*i)->input()->connected_to (str)) {
4139 boost::shared_ptr<Route>
4140 Session::route_by_name (string name)
4142 boost::shared_ptr<RouteList> r = routes.reader ();
4144 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4145 if ((*i)->name() == name) {
4150 return boost::shared_ptr<Route> ((Route*) 0);
4153 boost::shared_ptr<Route>
4154 Session::route_by_id (PBD::ID id)
4156 boost::shared_ptr<RouteList> r = routes.reader ();
4158 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4159 if ((*i)->id() == id) {
4164 return boost::shared_ptr<Route> ((Route*) 0);
4167 boost::shared_ptr<Processor>
4168 Session::processor_by_id (PBD::ID id) const
4170 boost::shared_ptr<RouteList> r = routes.reader ();
4172 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4173 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4179 return boost::shared_ptr<Processor> ();
4182 boost::shared_ptr<Track>
4183 Session::track_by_diskstream_id (PBD::ID id)
4185 boost::shared_ptr<RouteList> r = routes.reader ();
4187 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4188 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4189 if (t && t->using_diskstream_id (id)) {
4194 return boost::shared_ptr<Track> ();
4197 boost::shared_ptr<Route>
4198 Session::route_by_remote_id (uint32_t id)
4200 boost::shared_ptr<RouteList> r = routes.reader ();
4202 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4203 if ((*i)->remote_control_id() == id) {
4208 return boost::shared_ptr<Route> ((Route*) 0);
4212 boost::shared_ptr<Stripable>
4213 Session::stripable_by_remote_id (uint32_t id)
4215 boost::shared_ptr<RouteList> r = routes.reader ();
4217 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4218 if ((*i)->remote_control_id() == id) {
4223 return boost::shared_ptr<Route> ((Route*) 0);
4227 boost::shared_ptr<Route>
4228 Session::route_by_selected_count (uint32_t id)
4230 boost::shared_ptr<RouteList> r = routes.reader ();
4232 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4233 /* NOT IMPLEMENTED */
4236 return boost::shared_ptr<Route> ((Route*) 0);
4241 Session::reassign_track_numbers ()
4245 RouteList r (*(routes.reader ()));
4246 SignalOrderRouteSorter sorter;
4249 StateProtector sp (this);
4251 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4252 if (boost::dynamic_pointer_cast<Track> (*i)) {
4253 (*i)->set_track_number(++tn);
4255 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4256 (*i)->set_track_number(--bn);
4259 const uint32_t decimals = ceilf (log10f (tn + 1));
4260 const bool decimals_changed = _track_number_decimals != decimals;
4261 _track_number_decimals = decimals;
4263 if (decimals_changed && config.get_track_name_number ()) {
4264 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4265 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4267 t->resync_track_name();
4270 // trigger GUI re-layout
4271 config.ParameterChanged("track-name-number");
4276 Session::playlist_region_added (boost::weak_ptr<Region> w)
4278 boost::shared_ptr<Region> r = w.lock ();
4283 /* These are the operations that are currently in progress... */
4284 list<GQuark> curr = _current_trans_quarks;
4287 /* ...and these are the operations during which we want to update
4288 the session range location markers.
4291 ops.push_back (Operations::capture);
4292 ops.push_back (Operations::paste);
4293 ops.push_back (Operations::duplicate_region);
4294 ops.push_back (Operations::insert_file);
4295 ops.push_back (Operations::insert_region);
4296 ops.push_back (Operations::drag_region_brush);
4297 ops.push_back (Operations::region_drag);
4298 ops.push_back (Operations::selection_grab);
4299 ops.push_back (Operations::region_fill);
4300 ops.push_back (Operations::fill_selection);
4301 ops.push_back (Operations::create_region);
4302 ops.push_back (Operations::region_copy);
4303 ops.push_back (Operations::fixed_time_region_copy);
4306 /* See if any of the current operations match the ones that we want */
4308 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4310 /* If so, update the session range markers */
4312 maybe_update_session_range (r->position (), r->last_frame ());
4316 /** Update the session range markers if a is before the current start or
4317 * b is after the current end.
4320 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4322 if (_state_of_the_state & Loading) {
4326 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4328 if (_session_range_location == 0) {
4330 set_session_range_location (a, b + session_end_marker_shift_samples);
4334 if (a < _session_range_location->start()) {
4335 _session_range_location->set_start (a);
4338 if (b > _session_range_location->end()) {
4339 _session_range_location->set_end (b);
4345 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4347 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4348 maybe_update_session_range (i->to, i->to + i->length);
4353 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4355 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4356 maybe_update_session_range (i->from, i->to);
4360 /* Region management */
4362 boost::shared_ptr<Region>
4363 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4365 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4366 RegionFactory::RegionMap::const_iterator i;
4367 boost::shared_ptr<Region> region;
4369 Glib::Threads::Mutex::Lock lm (region_lock);
4371 for (i = regions.begin(); i != regions.end(); ++i) {
4375 if (region->whole_file()) {
4377 if (child->source_equivalent (region)) {
4383 return boost::shared_ptr<Region> ();
4387 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4389 set<boost::shared_ptr<Region> > relevant_regions;
4391 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4392 RegionFactory::get_regions_using_source (*s, relevant_regions);
4395 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4396 set<boost::shared_ptr<Region> >::iterator tmp;
4401 playlists->destroy_region (*r);
4402 RegionFactory::map_remove (*r);
4404 (*r)->drop_sources ();
4405 (*r)->drop_references ();
4407 relevant_regions.erase (r);
4412 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4415 Glib::Threads::Mutex::Lock ls (source_lock);
4416 /* remove from the main source list */
4417 sources.erase ((*s)->id());
4420 (*s)->mark_for_remove ();
4421 (*s)->drop_references ();
4430 Session::remove_last_capture ()
4432 list<boost::shared_ptr<Source> > srcs;
4434 boost::shared_ptr<RouteList> rl = routes.reader ();
4435 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4436 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4441 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4444 srcs.insert (srcs.end(), l.begin(), l.end());
4449 destroy_sources (srcs);
4451 save_state (_current_snapshot_name);
4456 /* Source Management */
4459 Session::add_source (boost::shared_ptr<Source> source)
4461 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4462 pair<SourceMap::iterator,bool> result;
4464 entry.first = source->id();
4465 entry.second = source;
4468 Glib::Threads::Mutex::Lock lm (source_lock);
4469 result = sources.insert (entry);
4472 if (result.second) {
4474 /* yay, new source */
4476 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4479 if (!fs->within_session()) {
4480 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4486 boost::shared_ptr<AudioFileSource> afs;
4488 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4489 if (Config->get_auto_analyse_audio()) {
4490 Analyser::queue_source_for_analysis (source, false);
4494 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4499 Session::remove_source (boost::weak_ptr<Source> src)
4501 if (_state_of_the_state & Deletion) {
4505 SourceMap::iterator i;
4506 boost::shared_ptr<Source> source = src.lock();
4513 Glib::Threads::Mutex::Lock lm (source_lock);
4515 if ((i = sources.find (source->id())) != sources.end()) {
4520 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4522 /* save state so we don't end up with a session file
4523 referring to non-existent sources.
4526 save_state (_current_snapshot_name);
4530 boost::shared_ptr<Source>
4531 Session::source_by_id (const PBD::ID& id)
4533 Glib::Threads::Mutex::Lock lm (source_lock);
4534 SourceMap::iterator i;
4535 boost::shared_ptr<Source> source;
4537 if ((i = sources.find (id)) != sources.end()) {
4544 boost::shared_ptr<AudioFileSource>
4545 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4547 /* Restricted to audio files because only audio sources have channel
4551 Glib::Threads::Mutex::Lock lm (source_lock);
4553 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4554 boost::shared_ptr<AudioFileSource> afs
4555 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4557 if (afs && afs->path() == path && chn == afs->channel()) {
4562 return boost::shared_ptr<AudioFileSource>();
4565 boost::shared_ptr<MidiSource>
4566 Session::midi_source_by_path (const std::string& path) const
4568 /* Restricted to MIDI files because audio sources require a channel
4569 for unique identification, in addition to a path.
4572 Glib::Threads::Mutex::Lock lm (source_lock);
4574 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4575 boost::shared_ptr<MidiSource> ms
4576 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4577 boost::shared_ptr<FileSource> fs
4578 = boost::dynamic_pointer_cast<FileSource>(s->second);
4580 if (ms && fs && fs->path() == path) {
4585 return boost::shared_ptr<MidiSource>();
4589 Session::count_sources_by_origin (const string& path)
4592 Glib::Threads::Mutex::Lock lm (source_lock);
4594 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4595 boost::shared_ptr<FileSource> fs
4596 = boost::dynamic_pointer_cast<FileSource>(i->second);
4598 if (fs && fs->origin() == path) {
4607 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4609 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4610 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4612 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4617 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4619 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4621 if (Glib::path_is_absolute (filepath)) {
4623 /* rip the session dir from the audiofile source */
4625 string session_path;
4626 bool in_another_session = true;
4628 if (filepath.find (interchange_dir_string) != string::npos) {
4630 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4631 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4632 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4633 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4635 /* see if it is within our session */
4637 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4638 if (i->path == session_path) {
4639 in_another_session = false;
4644 in_another_session = false;
4648 if (in_another_session) {
4649 SessionDirectory sd (session_path);
4650 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4654 /* 1) if file belongs to this session
4655 * it may be a relative path (interchange/...)
4656 * or just basename (session_state, remove source)
4657 * -> just use the basename
4659 std::string filename = Glib::path_get_basename (filepath);
4662 /* 2) if the file is outside our session dir:
4663 * (imported but not copied) add the path for check-summming */
4665 path = Glib::path_get_dirname (filepath);
4668 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4672 Session::new_audio_source_path_for_embedded (const std::string& path)
4676 * we know that the filename is already unique because it exists
4677 * out in the filesystem.
4679 * However, when we bring it into the session, we could get a
4682 * Eg. two embedded files:
4687 * When merged into session, these collide.
4689 * There will not be a conflict with in-memory sources
4690 * because when the source was created we already picked
4691 * a unique name for it.
4693 * This collision is not likely to be common, but we have to guard
4694 * against it. So, if there is a collision, take the md5 hash of the
4695 * the path, and use that as the filename instead.
4698 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4699 string base = Glib::path_get_basename (path);
4700 string newpath = Glib::build_filename (sdir.sound_path(), base);
4702 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4706 md5.digestString (path.c_str());
4707 md5.writeToString ();
4708 base = md5.digestChars;
4710 string ext = get_suffix (path);
4717 newpath = Glib::build_filename (sdir.sound_path(), base);
4719 /* if this collides, we're screwed */
4721 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4722 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4731 /** Return true if there are no audio file sources that use @param name as
4732 * the filename component of their path.
4734 * Return false otherwise.
4736 * This method MUST ONLY be used to check in-session, mono files since it
4737 * hard-codes the channel of the audio file source we are looking for as zero.
4739 * If/when Ardour supports native files in non-mono formats, the logic here
4740 * will need to be revisited.
4743 Session::audio_source_name_is_unique (const string& name)
4745 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4746 vector<space_and_path>::iterator i;
4747 uint32_t existing = 0;
4749 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4751 /* note that we search *without* the extension so that
4752 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4753 in the event that this new name is required for
4754 a file format change.
4757 const string spath = *i;
4759 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4764 /* it is possible that we have the path already
4765 * assigned to a source that has not yet been written
4766 * (ie. the write source for a diskstream). we have to
4767 * check this in order to make sure that our candidate
4768 * path isn't used again, because that can lead to
4769 * two Sources point to the same file with different
4770 * notions of their removability.
4774 string possible_path = Glib::build_filename (spath, name);
4776 if (audio_source_by_path_and_channel (possible_path, 0)) {
4782 return (existing == 0);
4786 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)
4789 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4791 if (Profile->get_trx() && destructive) {
4793 sstr << setfill ('0') << setw (4) << cnt;
4794 sstr << legalized_base;
4796 sstr << legalized_base;
4798 if (take_required || related_exists) {
4810 } else if (nchan > 2) {
4815 /* XXX what? more than 26 channels! */
4826 /** Return a unique name based on \a base for a new internal audio source */
4828 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4831 string possible_name;
4832 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4834 bool some_related_source_name_exists = false;
4836 legalized = legalize_for_path (base);
4838 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4840 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4842 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4844 if (audio_source_name_is_unique (possible_name)) {
4848 some_related_source_name_exists = true;
4851 error << string_compose(
4852 _("There are already %1 recordings for %2, which I consider too many."),
4853 limit, base) << endmsg;
4855 throw failed_constructor();
4859 /* We've established that the new name does not exist in any session
4860 * directory, so now find out which one we should use for this new
4864 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4866 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4871 /** Return a unique name based on `base` for a new internal MIDI source */
4873 Session::new_midi_source_path (const string& base)
4876 char buf[PATH_MAX+1];
4877 const uint32_t limit = 10000;
4879 string possible_path;
4880 string possible_name;
4883 legalized = legalize_for_path (base);
4885 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4886 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4888 /* - the main session folder is the first in the vector.
4889 * - after checking all locations for file-name uniqueness,
4890 * we keep the one from the last iteration as new file name
4891 * - midi files are small and should just be kept in the main session-folder
4893 * -> reverse the array, check main session folder last and use that as location
4896 std::reverse(sdirs.begin(), sdirs.end());
4898 for (cnt = 1; cnt <= limit; ++cnt) {
4900 vector<space_and_path>::iterator i;
4901 uint32_t existing = 0;
4903 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4905 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4906 possible_name = buf;
4908 possible_path = Glib::build_filename (*i, possible_name);
4910 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4914 if (midi_source_by_path (possible_path)) {
4919 if (existing == 0) {
4924 error << string_compose(
4925 _("There are already %1 recordings for %2, which I consider too many."),
4926 limit, base) << endmsg;
4932 /* No need to "find best location" for software/app-based RAID, because
4933 MIDI is so small that we always put it in the same place.
4936 return possible_path;
4940 /** Create a new within-session audio source */
4941 boost::shared_ptr<AudioFileSource>
4942 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4944 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4946 if (!path.empty()) {
4947 return boost::dynamic_pointer_cast<AudioFileSource> (
4948 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4950 throw failed_constructor ();
4954 /** Create a new within-session MIDI source */
4955 boost::shared_ptr<MidiSource>
4956 Session::create_midi_source_for_session (string const & basic_name)
4958 const string path = new_midi_source_path (basic_name);
4960 if (!path.empty()) {
4961 return boost::dynamic_pointer_cast<SMFSource> (
4962 SourceFactory::createWritable (
4963 DataType::MIDI, *this, path, false, frame_rate()));
4965 throw failed_constructor ();
4969 /** Create a new within-session MIDI source */
4970 boost::shared_ptr<MidiSource>
4971 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4973 /* the caller passes in the track the source will be used in,
4974 so that we can keep the numbering sane.
4976 Rationale: a track with the name "Foo" that has had N
4977 captures carried out so far will ALREADY have a write source
4978 named "Foo-N+1.mid" waiting to be used for the next capture.
4980 If we call new_midi_source_name() we will get "Foo-N+2". But
4981 there is no region corresponding to "Foo-N+1", so when
4982 "Foo-N+2" appears in the track, the gap presents the user
4983 with odd behaviour - why did it skip past Foo-N+1?
4985 We could explain this to the user in some odd way, but
4986 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4989 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4992 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4994 std::string name = track->steal_write_source_name ();
4997 return boost::shared_ptr<MidiSource>();
5000 /* MIDI files are small, just put them in the first location of the
5001 session source search path.
5004 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5006 return boost::dynamic_pointer_cast<SMFSource> (
5007 SourceFactory::createWritable (
5008 DataType::MIDI, *this, path, false, frame_rate()));
5013 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5015 if (playlist->hidden()) {
5019 playlists->add (playlist);
5022 playlist->release();
5029 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5031 if (_state_of_the_state & Deletion) {
5035 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5041 playlists->remove (playlist);
5047 Session::set_audition (boost::shared_ptr<Region> r)
5049 pending_audition_region = r;
5050 add_post_transport_work (PostTransportAudition);
5051 _butler->schedule_transport_work ();
5055 Session::audition_playlist ()
5057 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5058 ev->region.reset ();
5064 Session::register_lua_function (
5065 const std::string& name,
5066 const std::string& script,
5067 const LuaScriptParamList& args
5070 Glib::Threads::Mutex::Lock lm (lua_lock);
5072 lua_State* L = lua.getState();
5074 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5075 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5076 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5077 if ((*i)->optional && !(*i)->is_set) { continue; }
5078 tbl_arg[(*i)->name] = (*i)->value;
5080 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5085 Session::unregister_lua_function (const std::string& name)
5087 Glib::Threads::Mutex::Lock lm (lua_lock);
5088 (*_lua_del)(name); // throws luabridge::LuaException
5089 lua.collect_garbage ();
5093 std::vector<std::string>
5094 Session::registered_lua_functions ()
5096 Glib::Threads::Mutex::Lock lm (lua_lock);
5097 std::vector<std::string> rv;
5100 luabridge::LuaRef list ((*_lua_list)());
5101 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5102 if (!i.key ().isString ()) { assert(0); continue; }
5103 rv.push_back (i.key ().cast<std::string> ());
5105 } catch (luabridge::LuaException const& e) { }
5110 static void _lua_print (std::string s) {
5111 std::cout << "SessionLua: " << s << "\n";
5116 Session::try_run_lua (pframes_t nframes)
5118 if (_n_lua_scripts == 0) return;
5119 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5121 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5126 Session::setup_lua ()
5129 lua.Print.connect (&_lua_print);
5132 "function ArdourSession ()"
5133 " local self = { scripts = {}, instances = {} }"
5135 " local remove = function (n)"
5136 " self.scripts[n] = nil"
5137 " self.instances[n] = nil"
5138 " Session:scripts_changed()" // call back
5141 " local addinternal = function (n, f, a)"
5142 " assert(type(n) == 'string', 'function-name must be string')"
5143 " assert(type(f) == 'function', 'Given script is a not a function')"
5144 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5145 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5146 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5147 " 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"
5148 " 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 }"
5149 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5150 " Session:scripts_changed()" // call back
5153 " local add = function (n, b, a)"
5154 " assert(type(b) == 'string', 'ByteCode must be string')"
5155 " load (b)()" // assigns f
5156 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5157 " addinternal (n, load(f), a)"
5160 " local run = function (...)"
5161 " for n, s in pairs (self.instances) do"
5162 " local status, err = pcall (s, ...)"
5163 " if not status then"
5164 " print ('fn \"'.. n .. '\": ', err)"
5171 " local cleanup = function ()"
5172 " self.scripts = nil"
5173 " self.instances = nil"
5176 " local list = function ()"
5178 " for n, _ in pairs (self.scripts) do"
5184 " local function basic_serialize (o)"
5185 " if type(o) == \"number\" then"
5186 " return tostring(o)"
5188 " return string.format(\"%q\", o)"
5192 " local function serialize (name, value)"
5193 " local rv = name .. ' = '"
5195 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5196 " return rv .. basic_serialize(value) .. ' '"
5197 " elseif type(value) == \"table\" then"
5199 " for k,v in pairs(value) do"
5200 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5201 " rv = rv .. serialize(fieldname, v) .. ' '"
5202 " collectgarbage()" // string concatenation allocates a new string :(
5205 " elseif type(value) == \"function\" then"
5206 " return rv .. string.format(\"%q\", string.dump(value, true))"
5208 " error('cannot save a ' .. type(value))"
5213 " local save = function ()"
5214 " return (serialize('scripts', self.scripts))"
5217 " local restore = function (state)"
5218 " self.scripts = {}"
5220 " for n, s in pairs (scripts) do"
5221 " addinternal (n, load(s['f']), s['a'])"
5225 " return { run = run, add = add, remove = remove,"
5226 " list = list, restore = restore, save = save, cleanup = cleanup}"
5229 " sess = ArdourSession ()"
5230 " ArdourSession = nil"
5232 "function ardour () end"
5235 lua_State* L = lua.getState();
5238 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5239 lua.do_command ("sess = nil"); // hide it.
5240 lua.do_command ("collectgarbage()");
5242 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5243 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5244 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5245 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5246 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5247 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5248 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5249 } catch (luabridge::LuaException const& e) {
5250 fatal << string_compose (_("programming error: %1"),
5251 X_("Failed to setup Lua interpreter"))
5253 abort(); /*NOTREACHED*/
5256 LuaBindings::stddef (L);
5257 LuaBindings::common (L);
5258 LuaBindings::dsp (L);
5259 luabridge::push <Session *> (L, this);
5260 lua_setglobal (L, "Session");
5264 Session::scripts_changed ()
5266 assert (!lua_lock.trylock()); // must hold lua_lock
5269 luabridge::LuaRef list ((*_lua_list)());
5271 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5272 if (!i.key ().isString ()) { assert(0); continue; }
5275 _n_lua_scripts = cnt;
5276 } catch (luabridge::LuaException const& e) {
5277 fatal << string_compose (_("programming error: %1"),
5278 X_("Indexing Lua Session Scripts failed."))
5280 abort(); /*NOTREACHED*/
5285 Session::non_realtime_set_audition ()
5287 assert (pending_audition_region);
5288 auditioner->audition_region (pending_audition_region);
5289 pending_audition_region.reset ();
5290 AuditionActive (true); /* EMIT SIGNAL */
5294 Session::audition_region (boost::shared_ptr<Region> r)
5296 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5302 Session::cancel_audition ()
5307 if (auditioner->auditioning()) {
5308 auditioner->cancel_audition ();
5309 AuditionActive (false); /* EMIT SIGNAL */
5314 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5316 if (a->is_monitor()) {
5319 if (b->is_monitor()) {
5322 return a->order_key () < b->order_key ();
5326 Session::is_auditioning () const
5328 /* can be called before we have an auditioner object */
5330 return auditioner->auditioning();
5337 Session::graph_reordered ()
5339 /* don't do this stuff if we are setting up connections
5340 from a set_state() call or creating new tracks. Ditto for deletion.
5343 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5347 /* every track/bus asked for this to be handled but it was deferred because
5348 we were connecting. do it now.
5351 request_input_change_handling ();
5355 /* force all diskstreams to update their capture offset values to
5356 reflect any changes in latencies within the graph.
5359 boost::shared_ptr<RouteList> rl = routes.reader ();
5360 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5361 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5363 tr->set_capture_offset ();
5368 /** @return Number of frames that there is disk space available to write,
5371 boost::optional<framecnt_t>
5372 Session::available_capture_duration ()
5374 Glib::Threads::Mutex::Lock lm (space_lock);
5376 if (_total_free_4k_blocks_uncertain) {
5377 return boost::optional<framecnt_t> ();
5380 float sample_bytes_on_disk = 4.0; // keep gcc happy
5382 switch (config.get_native_file_data_format()) {
5384 sample_bytes_on_disk = 4.0;
5388 sample_bytes_on_disk = 3.0;
5392 sample_bytes_on_disk = 2.0;
5396 /* impossible, but keep some gcc versions happy */
5397 fatal << string_compose (_("programming error: %1"),
5398 X_("illegal native file data format"))
5400 abort(); /*NOTREACHED*/
5403 double scale = 4096.0 / sample_bytes_on_disk;
5405 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5406 return max_framecnt;
5409 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5413 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5416 RCUWriter<BundleList> writer (_bundles);
5417 boost::shared_ptr<BundleList> b = writer.get_copy ();
5418 b->push_back (bundle);
5422 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5429 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5431 bool removed = false;
5434 RCUWriter<BundleList> writer (_bundles);
5435 boost::shared_ptr<BundleList> b = writer.get_copy ();
5436 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5438 if (i != b->end()) {
5445 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5451 boost::shared_ptr<Bundle>
5452 Session::bundle_by_name (string name) const
5454 boost::shared_ptr<BundleList> b = _bundles.reader ();
5456 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5457 if ((*i)->name() == name) {
5462 return boost::shared_ptr<Bundle> ();
5466 Session::tempo_map_changed (const PropertyChange&)
5470 playlists->update_after_tempo_map_change ();
5472 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5478 Session::gui_tempo_map_changed ()
5482 playlists->update_after_tempo_map_change ();
5484 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5488 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5490 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5491 (*i)->recompute_frames_from_bbt ();
5495 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5496 * the given count with the current block size.
5499 Session::ensure_buffers (ChanCount howmany)
5501 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5505 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5507 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5508 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5513 Session::next_insert_id ()
5515 /* this doesn't really loop forever. just think about it */
5518 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5519 if (!insert_bitset[n]) {
5520 insert_bitset[n] = true;
5526 /* none available, so resize and try again */
5528 insert_bitset.resize (insert_bitset.size() + 16, false);
5533 Session::next_send_id ()
5535 /* this doesn't really loop forever. just think about it */
5538 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5539 if (!send_bitset[n]) {
5540 send_bitset[n] = true;
5546 /* none available, so resize and try again */
5548 send_bitset.resize (send_bitset.size() + 16, false);
5553 Session::next_aux_send_id ()
5555 /* this doesn't really loop forever. just think about it */
5558 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5559 if (!aux_send_bitset[n]) {
5560 aux_send_bitset[n] = true;
5566 /* none available, so resize and try again */
5568 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5573 Session::next_return_id ()
5575 /* this doesn't really loop forever. just think about it */
5578 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5579 if (!return_bitset[n]) {
5580 return_bitset[n] = true;
5586 /* none available, so resize and try again */
5588 return_bitset.resize (return_bitset.size() + 16, false);
5593 Session::mark_send_id (uint32_t id)
5595 if (id >= send_bitset.size()) {
5596 send_bitset.resize (id+16, false);
5598 if (send_bitset[id]) {
5599 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5601 send_bitset[id] = true;
5605 Session::mark_aux_send_id (uint32_t id)
5607 if (id >= aux_send_bitset.size()) {
5608 aux_send_bitset.resize (id+16, false);
5610 if (aux_send_bitset[id]) {
5611 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5613 aux_send_bitset[id] = true;
5617 Session::mark_return_id (uint32_t id)
5619 if (id >= return_bitset.size()) {
5620 return_bitset.resize (id+16, false);
5622 if (return_bitset[id]) {
5623 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5625 return_bitset[id] = true;
5629 Session::mark_insert_id (uint32_t id)
5631 if (id >= insert_bitset.size()) {
5632 insert_bitset.resize (id+16, false);
5634 if (insert_bitset[id]) {
5635 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5637 insert_bitset[id] = true;
5641 Session::unmark_send_id (uint32_t id)
5643 if (id < send_bitset.size()) {
5644 send_bitset[id] = false;
5649 Session::unmark_aux_send_id (uint32_t id)
5651 if (id < aux_send_bitset.size()) {
5652 aux_send_bitset[id] = false;
5657 Session::unmark_return_id (uint32_t id)
5659 if (_state_of_the_state & Deletion) { return; }
5660 if (id < return_bitset.size()) {
5661 return_bitset[id] = false;
5666 Session::unmark_insert_id (uint32_t id)
5668 if (id < insert_bitset.size()) {
5669 insert_bitset[id] = false;
5674 Session::reset_native_file_format ()
5676 boost::shared_ptr<RouteList> rl = routes.reader ();
5678 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5679 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5681 /* don't save state as we do this, there's no point
5683 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5684 tr->reset_write_sources (false);
5685 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5691 Session::route_name_unique (string n) const
5693 boost::shared_ptr<RouteList> r = routes.reader ();
5695 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5696 if ((*i)->name() == n) {
5705 Session::route_name_internal (string n) const
5707 if (auditioner && auditioner->name() == n) {
5711 if (_click_io && _click_io->name() == n) {
5719 Session::freeze_all (InterThreadInfo& itt)
5721 boost::shared_ptr<RouteList> r = routes.reader ();
5723 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5725 boost::shared_ptr<Track> t;
5727 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5728 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5738 boost::shared_ptr<Region>
5739 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5740 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5741 InterThreadInfo& itt,
5742 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5743 bool for_export, bool for_freeze)
5745 boost::shared_ptr<Region> result;
5746 boost::shared_ptr<Playlist> playlist;
5747 boost::shared_ptr<Source> source;
5748 ChanCount diskstream_channels (track.n_channels());
5749 framepos_t position;
5750 framecnt_t this_chunk;
5752 framepos_t latency_skip;
5754 framepos_t len = end - start;
5755 bool need_block_size_reset = false;
5756 ChanCount const max_proc = track.max_processor_streams ();
5757 string legal_playlist_name;
5758 string possible_path;
5761 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5762 end, start) << endmsg;
5766 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5767 include_endpoint, for_export, for_freeze);
5769 if (diskstream_channels.n(track.data_type()) < 1) {
5770 error << _("Cannot write a range with no data.") << endmsg;
5774 // block all process callback handling
5776 block_processing ();
5779 // synchronize with AudioEngine::process_callback()
5780 // make sure processing is not currently running
5781 // and processing_blocked() is honored before
5782 // acquiring thread buffers
5783 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5786 _bounce_processing_active = true;
5788 /* call tree *MUST* hold route_lock */
5790 if ((playlist = track.playlist()) == 0) {
5794 legal_playlist_name = legalize_for_path (playlist->name());
5796 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5798 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5799 string path = ((track.data_type() == DataType::AUDIO)
5800 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5801 : new_midi_source_path (legal_playlist_name));
5808 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5811 catch (failed_constructor& err) {
5812 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5816 srcs.push_back (source);
5819 /* tell redirects that care that we are about to use a much larger
5820 * blocksize. this will flush all plugins too, so that they are ready
5821 * to be used for this process.
5824 need_block_size_reset = true;
5825 track.set_block_size (bounce_chunk_size);
5826 _engine.main_thread()->get_buffers ();
5830 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5832 /* create a set of reasonably-sized buffers */
5833 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5834 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5836 buffers.set_count (max_proc);
5838 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5839 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5840 boost::shared_ptr<MidiSource> ms;
5842 afs->prepare_for_peakfile_writes ();
5843 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5844 Source::Lock lock(ms->mutex());
5845 ms->mark_streaming_write_started(lock);
5849 while (to_do && !itt.cancel) {
5851 this_chunk = min (to_do, bounce_chunk_size);
5853 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5857 start += this_chunk;
5858 to_do -= this_chunk;
5859 itt.progress = (float) (1.0 - ((double) to_do / len));
5861 if (latency_skip >= bounce_chunk_size) {
5862 latency_skip -= bounce_chunk_size;
5866 const framecnt_t current_chunk = this_chunk - latency_skip;
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);
5871 boost::shared_ptr<MidiSource> ms;
5874 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5877 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5878 Source::Lock lock(ms->mutex());
5880 const MidiBuffer& buf = buffers.get_midi(0);
5881 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5882 Evoral::Event<framepos_t> ev = *i;
5883 ev.set_time(ev.time() - position);
5884 ms->append_event_frames(lock, ev, ms->timeline_position());
5891 /* post-roll, pick up delayed processor output */
5892 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5894 while (latency_skip && !itt.cancel) {
5895 this_chunk = min (latency_skip, bounce_chunk_size);
5896 latency_skip -= this_chunk;
5898 buffers.silence (this_chunk, 0);
5899 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5902 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5903 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5906 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5918 xnow = localtime (&now);
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);
5922 boost::shared_ptr<MidiSource> ms;
5925 afs->update_header (position, *xnow, now);
5926 afs->flush_header ();
5927 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5928 Source::Lock lock(ms->mutex());
5929 ms->mark_streaming_write_completed(lock);
5933 /* construct a region to represent the bounced material */
5937 plist.add (Properties::start, 0);
5938 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5939 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5941 result = RegionFactory::create (srcs, plist);
5947 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5948 (*src)->mark_for_remove ();
5949 (*src)->drop_references ();
5953 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5954 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5957 afs->done_with_peakfile_writes ();
5961 _bounce_processing_active = false;
5963 if (need_block_size_reset) {
5964 _engine.main_thread()->drop_buffers ();
5965 track.set_block_size (get_block_size());
5968 unblock_processing ();
5974 Session::gain_automation_buffer() const
5976 return ProcessThread::gain_automation_buffer ();
5980 Session::trim_automation_buffer() const
5982 return ProcessThread::trim_automation_buffer ();
5986 Session::send_gain_automation_buffer() const
5988 return ProcessThread::send_gain_automation_buffer ();
5992 Session::pan_automation_buffer() const
5994 return ProcessThread::pan_automation_buffer ();
5998 Session::get_silent_buffers (ChanCount count)
6000 return ProcessThread::get_silent_buffers (count);
6004 Session::get_scratch_buffers (ChanCount count, bool silence)
6006 return ProcessThread::get_scratch_buffers (count, silence);
6010 Session::get_noinplace_buffers (ChanCount count)
6012 return ProcessThread::get_noinplace_buffers (count);
6016 Session::get_route_buffers (ChanCount count, bool silence)
6018 return ProcessThread::get_route_buffers (count, silence);
6023 Session::get_mix_buffers (ChanCount count)
6025 return ProcessThread::get_mix_buffers (count);
6029 Session::ntracks () const
6032 boost::shared_ptr<RouteList> r = routes.reader ();
6034 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6035 if (boost::dynamic_pointer_cast<Track> (*i)) {
6044 Session::nbusses () const
6047 boost::shared_ptr<RouteList> r = routes.reader ();
6049 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6050 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6059 Session::add_automation_list(AutomationList *al)
6061 automation_lists[al->id()] = al;
6064 /** @return true if there is at least one record-enabled track, otherwise false */
6066 Session::have_rec_enabled_track () const
6068 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6072 Session::have_rec_disabled_track () const
6074 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6077 /** Update the state of our rec-enabled tracks flag */
6079 Session::update_route_record_state ()
6081 boost::shared_ptr<RouteList> rl = routes.reader ();
6082 RouteList::iterator i = rl->begin();
6083 while (i != rl->end ()) {
6085 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6086 if (tr && tr->rec_enable_control()->get_value()) {
6093 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6095 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6097 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6098 RecordStateChanged (); /* EMIT SIGNAL */
6101 for (i = rl->begin(); i != rl->end (); ++i) {
6102 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6103 if (tr && !tr->rec_enable_control()->get_value()) {
6108 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6110 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6112 if (record_status() == Recording && record_arm_state_changed ) {
6113 RecordArmStateChanged ();
6119 Session::listen_position_changed ()
6121 boost::shared_ptr<RouteList> r = routes.reader ();
6123 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6124 (*i)->listen_position_changed ();
6129 Session::solo_control_mode_changed ()
6131 if (soloing() || listening()) {
6132 /* We can't use ::clear_all_solo_state() here because during
6133 session loading at program startup, that will queue a call
6134 to rt_clear_all_solo_state() that will not execute until
6135 AFTER solo states have been established (thus throwing away
6136 the session's saved solo state). So just explicitly turn
6139 set_controls (route_list_to_control_list (get_routes(), &Route::solo_control), 0.0, Controllable::NoGroup);
6143 /** Called when a property of one of our route groups changes */
6145 Session::route_group_property_changed (RouteGroup* rg)
6147 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6150 /** Called when a route is added to one of our route groups */
6152 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6154 RouteAddedToRouteGroup (rg, r);
6157 /** Called when a route is removed from one of our route groups */
6159 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6161 update_route_record_state ();
6162 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6165 boost::shared_ptr<RouteList>
6166 Session::get_tracks () const
6168 boost::shared_ptr<RouteList> rl = routes.reader ();
6169 boost::shared_ptr<RouteList> tl (new RouteList);
6171 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6172 if (boost::dynamic_pointer_cast<Track> (*r)) {
6173 if (!(*r)->is_auditioner()) {
6181 boost::shared_ptr<RouteList>
6182 Session::get_routes_with_regions_at (framepos_t const p) const
6184 boost::shared_ptr<RouteList> r = routes.reader ();
6185 boost::shared_ptr<RouteList> rl (new RouteList);
6187 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6188 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6193 boost::shared_ptr<Playlist> pl = tr->playlist ();
6198 if (pl->has_region_at (p)) {
6207 Session::goto_end ()
6209 if (_session_range_location) {
6210 request_locate (_session_range_location->end(), false);
6212 request_locate (0, false);
6217 Session::goto_start ()
6219 if (_session_range_location) {
6220 request_locate (_session_range_location->start(), false);
6222 request_locate (0, false);
6227 Session::current_start_frame () const
6229 return _session_range_location ? _session_range_location->start() : 0;
6233 Session::current_end_frame () const
6235 return _session_range_location ? _session_range_location->end() : 0;
6239 Session::set_session_range_location (framepos_t start, framepos_t end)
6241 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6242 _locations->add (_session_range_location);
6246 Session::step_edit_status_change (bool yn)
6252 send = (_step_editors == 0);
6257 send = (_step_editors == 1);
6260 if (_step_editors > 0) {
6266 StepEditStatusChange (val);
6272 Session::start_time_changed (framepos_t old)
6274 /* Update the auto loop range to match the session range
6275 (unless the auto loop range has been changed by the user)
6278 Location* s = _locations->session_range_location ();
6283 Location* l = _locations->auto_loop_location ();
6285 if (l && l->start() == old) {
6286 l->set_start (s->start(), true);
6291 Session::end_time_changed (framepos_t old)
6293 /* Update the auto loop range to match the session range
6294 (unless the auto loop range has been changed by the user)
6297 Location* s = _locations->session_range_location ();
6302 Location* l = _locations->auto_loop_location ();
6304 if (l && l->end() == old) {
6305 l->set_end (s->end(), true);
6309 std::vector<std::string>
6310 Session::source_search_path (DataType type) const
6314 if (session_dirs.size() == 1) {
6316 case DataType::AUDIO:
6317 sp.push_back (_session_dir->sound_path());
6319 case DataType::MIDI:
6320 sp.push_back (_session_dir->midi_path());
6324 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6325 SessionDirectory sdir (i->path);
6327 case DataType::AUDIO:
6328 sp.push_back (sdir.sound_path());
6330 case DataType::MIDI:
6331 sp.push_back (sdir.midi_path());
6337 if (type == DataType::AUDIO) {
6338 const string sound_path_2X = _session_dir->sound_path_2X();
6339 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6340 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6341 sp.push_back (sound_path_2X);
6346 // now check the explicit (possibly user-specified) search path
6349 case DataType::AUDIO:
6350 sp += Searchpath(config.get_audio_search_path ());
6352 case DataType::MIDI:
6353 sp += Searchpath(config.get_midi_search_path ());
6361 Session::ensure_search_path_includes (const string& path, DataType type)
6370 case DataType::AUDIO:
6371 sp += Searchpath(config.get_audio_search_path ());
6373 case DataType::MIDI:
6374 sp += Searchpath (config.get_midi_search_path ());
6378 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6379 /* No need to add this new directory if it has the same inode as
6380 an existing one; checking inode rather than name prevents duplicated
6381 directories when we are using symlinks.
6383 On Windows, I think we could just do if (*i == path) here.
6385 if (PBD::equivalent_paths (*i, path)) {
6393 case DataType::AUDIO:
6394 config.set_audio_search_path (sp.to_string());
6396 case DataType::MIDI:
6397 config.set_midi_search_path (sp.to_string());
6403 Session::remove_dir_from_search_path (const string& dir, DataType type)
6408 case DataType::AUDIO:
6409 sp = Searchpath(config.get_audio_search_path ());
6411 case DataType::MIDI:
6412 sp = Searchpath (config.get_midi_search_path ());
6419 case DataType::AUDIO:
6420 config.set_audio_search_path (sp.to_string());
6422 case DataType::MIDI:
6423 config.set_midi_search_path (sp.to_string());
6429 boost::shared_ptr<Speakers>
6430 Session::get_speakers()
6436 Session::unknown_processors () const
6440 boost::shared_ptr<RouteList> r = routes.reader ();
6441 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6442 list<string> t = (*i)->unknown_processors ();
6443 copy (t.begin(), t.end(), back_inserter (p));
6453 Session::update_latency (bool playback)
6456 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6458 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6462 boost::shared_ptr<RouteList> r = routes.reader ();
6463 framecnt_t max_latency = 0;
6466 /* reverse the list so that we work backwards from the last route to run to the first */
6467 RouteList* rl = routes.reader().get();
6468 r.reset (new RouteList (*rl));
6469 reverse (r->begin(), r->end());
6472 /* compute actual latency values for the given direction and store them all in per-port
6473 structures. this will also publish the same values (to JACK) so that computation of latency
6474 for routes can consistently use public latency values.
6477 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6478 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6481 /* because we latency compensate playback, our published playback latencies should
6482 be the same for all output ports - all material played back by ardour has
6483 the same latency, whether its caused by plugins or by latency compensation. since
6484 these may differ from the values computed above, reset all playback port latencies
6488 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6490 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6491 (*i)->set_public_port_latencies (max_latency, playback);
6496 post_playback_latency ();
6500 post_capture_latency ();
6503 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6507 Session::post_playback_latency ()
6509 set_worst_playback_latency ();
6511 boost::shared_ptr<RouteList> r = routes.reader ();
6513 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6514 if (!(*i)->is_auditioner() && ((*i)->active())) {
6515 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6520 (*i)->set_latency_compensation (_worst_track_latency);
6525 Session::post_capture_latency ()
6527 set_worst_capture_latency ();
6529 /* reflect any changes in capture latencies into capture offsets
6532 boost::shared_ptr<RouteList> rl = routes.reader();
6533 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6534 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6536 tr->set_capture_offset ();
6542 Session::initialize_latencies ()
6545 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6546 update_latency (false);
6547 update_latency (true);
6550 set_worst_io_latencies ();
6554 Session::set_worst_io_latencies ()
6556 set_worst_playback_latency ();
6557 set_worst_capture_latency ();
6561 Session::set_worst_playback_latency ()
6563 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6567 _worst_output_latency = 0;
6569 if (!_engine.connected()) {
6573 boost::shared_ptr<RouteList> r = routes.reader ();
6575 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6576 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6579 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6583 Session::set_worst_capture_latency ()
6585 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6589 _worst_input_latency = 0;
6591 if (!_engine.connected()) {
6595 boost::shared_ptr<RouteList> r = routes.reader ();
6597 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6598 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6601 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6605 Session::update_latency_compensation (bool force_whole_graph)
6607 bool some_track_latency_changed = false;
6609 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6613 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6615 _worst_track_latency = 0;
6617 boost::shared_ptr<RouteList> r = routes.reader ();
6619 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6620 if (!(*i)->is_auditioner() && ((*i)->active())) {
6622 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6623 some_track_latency_changed = true;
6625 _worst_track_latency = max (tl, _worst_track_latency);
6629 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6630 (some_track_latency_changed ? "yes" : "no")));
6632 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6634 if (some_track_latency_changed || force_whole_graph) {
6635 _engine.update_latencies ();
6639 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6640 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6644 tr->set_capture_offset ();
6649 Session::session_name_is_legal (const string& path)
6651 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6653 for (int i = 0; illegal_chars[i]; ++i) {
6654 if (path.find (illegal_chars[i]) != string::npos) {
6655 return illegal_chars[i];
6663 Session::next_control_id () const
6667 /* the monitor bus remote ID is in a different
6668 * "namespace" than regular routes. its existence doesn't
6669 * affect normal (low) numbered routes.
6676 /* the same about masterbus in Waves Tracks */
6678 if (Profile->get_trx() && _master_out) {
6682 return nroutes() - subtract;
6686 Session::notify_remote_id_change ()
6688 if (deletion_in_progress()) {
6692 switch (Config->get_remote_model()) {
6694 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6700 #ifdef USE_TRACKS_CODE_FEATURES
6701 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6702 * if track order has been changed by user
6704 reconnect_existing_routes(true, true);
6710 Session::sync_order_keys ()
6712 if (deletion_in_progress()) {
6716 /* tell everyone that something has happened to the sort keys
6717 and let them sync up with the change(s)
6718 this will give objects that manage the sort order keys the
6719 opportunity to keep them in sync if they wish to.
6722 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6724 reassign_track_numbers();
6726 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6728 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6732 Session::operation_in_progress (GQuark op) const
6734 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6737 boost::shared_ptr<Port>
6738 Session::ltc_input_port () const
6740 return _ltc_input->nth (0);
6743 boost::shared_ptr<Port>
6744 Session::ltc_output_port () const
6746 return _ltc_output->nth (0);
6750 Session::reconnect_ltc_input ()
6754 string src = Config->get_ltc_source_port();
6756 _ltc_input->disconnect (this);
6758 if (src != _("None") && !src.empty()) {
6759 _ltc_input->nth (0)->connect (src);
6762 if ( ARDOUR::Profile->get_trx () ) {
6763 // Tracks need this signal to update timecode_source_dropdown
6764 MtcOrLtcInputPortChanged (); //emit signal
6770 Session::reconnect_ltc_output ()
6774 string src = Config->get_ltc_output_port();
6776 _ltc_output->disconnect (this);
6778 if (src != _("None") && !src.empty()) {
6779 _ltc_output->nth (0)->connect (src);
6785 Session::set_range_selection (framepos_t start, framepos_t end)
6787 _range_selection = Evoral::Range<framepos_t> (start, end);
6788 #ifdef USE_TRACKS_CODE_FEATURES
6789 follow_playhead_priority ();
6794 Session::set_object_selection (framepos_t start, framepos_t end)
6796 _object_selection = Evoral::Range<framepos_t> (start, end);
6797 #ifdef USE_TRACKS_CODE_FEATURES
6798 follow_playhead_priority ();
6803 Session::clear_range_selection ()
6805 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6806 #ifdef USE_TRACKS_CODE_FEATURES
6807 follow_playhead_priority ();
6812 Session::clear_object_selection ()
6814 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6815 #ifdef USE_TRACKS_CODE_FEATURES
6816 follow_playhead_priority ();
6821 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6822 const ChanCount& input_start,
6823 const ChanCount& output_start,
6824 const ChanCount& input_offset,
6825 const ChanCount& output_offset)
6827 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6828 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6829 input_start, output_start,
6830 input_offset, output_offset));
6832 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6833 pthread_cond_signal (&_auto_connect_cond);
6834 pthread_mutex_unlock (&_auto_connect_mutex);
6839 Session::auto_connect (const AutoConnectRequest& ar)
6841 boost::shared_ptr<Route> route = ar.route.lock();
6843 if (!route) { return; }
6845 if (!IO::connecting_legal) {
6849 /* If both inputs and outputs are auto-connected to physical ports,
6850 * use the max of input and output offsets to ensure auto-connected
6851 * port numbers always match up (e.g. the first audio input and the
6852 * first audio output of the route will have the same physical
6853 * port number). Otherwise just use the lowest input or output
6857 const bool in_out_physical =
6858 (Config->get_input_auto_connect() & AutoConnectPhysical)
6859 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6860 && ar.connect_inputs;
6862 const ChanCount in_offset = in_out_physical
6863 ? ChanCount::max(ar.input_offset, ar.output_offset)
6866 const ChanCount out_offset = in_out_physical
6867 ? ChanCount::max(ar.input_offset, ar.output_offset)
6870 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6871 vector<string> physinputs;
6872 vector<string> physoutputs;
6874 _engine.get_physical_outputs (*t, physoutputs);
6875 _engine.get_physical_inputs (*t, physinputs);
6877 if (!physinputs.empty() && ar.connect_inputs) {
6878 uint32_t nphysical_in = physinputs.size();
6880 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6883 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6884 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6887 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6893 if (!physoutputs.empty()) {
6894 uint32_t nphysical_out = physoutputs.size();
6895 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6899 * do not create new connections if we reached the limit of physical outputs
6902 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6903 ARDOUR::Profile->get_trx () &&
6904 ar.output_offset.get(*t) == nphysical_out ) {
6908 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6909 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6910 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6911 /* master bus is audio only */
6912 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6913 port = _master_out->input()->ports().port(*t,
6914 i % _master_out->input()->n_ports().get(*t))->name();
6918 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6927 Session::auto_connect_thread_start ()
6929 if (_ac_thread_active) {
6933 while (!_auto_connect_queue.empty ()) {
6934 _auto_connect_queue.pop ();
6937 _ac_thread_active = true;
6938 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6939 _ac_thread_active = false;
6944 Session::auto_connect_thread_terminate ()
6946 if (!_ac_thread_active) {
6949 _ac_thread_active = false;
6952 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6953 while (!_auto_connect_queue.empty ()) {
6954 _auto_connect_queue.pop ();
6958 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6959 pthread_cond_signal (&_auto_connect_cond);
6960 pthread_mutex_unlock (&_auto_connect_mutex);
6964 pthread_join (_auto_connect_thread, &status);
6968 Session::auto_connect_thread (void *arg)
6970 Session *s = static_cast<Session *>(arg);
6971 s->auto_connect_thread_run ();
6977 Session::auto_connect_thread_run ()
6979 pthread_set_name (X_("autoconnect"));
6980 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6981 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6982 pthread_mutex_lock (&_auto_connect_mutex);
6983 while (_ac_thread_active) {
6985 if (!_auto_connect_queue.empty ()) {
6986 // Why would we need the process lock ??
6987 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
6988 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
6989 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
6990 // We have control over those, but what does jack do?
6991 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6993 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6994 while (!_auto_connect_queue.empty ()) {
6995 const AutoConnectRequest ar (_auto_connect_queue.front());
6996 _auto_connect_queue.pop ();
7003 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7005 pthread_mutex_unlock (&_auto_connect_mutex);