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/error.h"
41 #include "pbd/file_utils.h"
43 #include "pbd/pthread_utils.h"
44 #include "pbd/search_path.h"
45 #include "pbd/stacktrace.h"
46 #include "pbd/stl_delete.h"
47 #include "pbd/replace_all.h"
48 #include "pbd/types_convert.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_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/boost_debug.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/disk_reader.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/playlist_factory.h"
86 #include "ardour/plugin.h"
87 #include "ardour/plugin_insert.h"
88 #include "ardour/process_thread.h"
89 #include "ardour/profile.h"
90 #include "ardour/rc_configuration.h"
91 #include "ardour/recent_sessions.h"
92 #include "ardour/region.h"
93 #include "ardour/region_factory.h"
94 #include "ardour/revision.h"
95 #include "ardour/route_graph.h"
96 #include "ardour/route_group.h"
97 #include "ardour/rt_tasklist.h"
98 #include "ardour/send.h"
99 #include "ardour/selection.h"
100 #include "ardour/session.h"
101 #include "ardour/session_directory.h"
102 #include "ardour/session_playlists.h"
103 #include "ardour/smf_source.h"
104 #include "ardour/solo_isolate_control.h"
105 #include "ardour/source_factory.h"
106 #include "ardour/speakers.h"
107 #include "ardour/tempo.h"
108 #include "ardour/ticker.h"
109 #include "ardour/transport_master.h"
110 #include "ardour/track.h"
111 #include "ardour/types_convert.h"
112 #include "ardour/user_bundle.h"
113 #include "ardour/utils.h"
114 #include "ardour/vca_manager.h"
115 #include "ardour/vca.h"
117 #include "midi++/port.h"
118 #include "midi++/mmc.h"
120 #include "LuaBridge/LuaBridge.h"
122 #include "pbd/i18n.h"
124 #include <glibmm/checksum.h>
133 using namespace ARDOUR;
136 bool Session::_disable_all_loaded_plugins = false;
137 bool Session::_bypass_all_loaded_plugins = false;
138 guint Session::_name_id_counter = 0;
140 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
141 PBD::Signal1<void,std::string> Session::Dialog;
142 PBD::Signal0<int> Session::AskAboutPendingState;
143 PBD::Signal2<int, samplecnt_t, samplecnt_t> Session::AskAboutSampleRateMismatch;
144 PBD::Signal2<void, samplecnt_t, samplecnt_t> Session::NotifyAboutSampleRateMismatch;
145 PBD::Signal0<void> Session::SendFeedback;
146 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
148 PBD::Signal1<void, samplepos_t> Session::StartTimeChanged;
149 PBD::Signal1<void, samplepos_t> Session::EndTimeChanged;
150 PBD::Signal2<void,std::string, std::string> Session::Exported;
151 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
152 PBD::Signal0<void> Session::Quit;
153 PBD::Signal0<void> Session::FeedbackDetected;
154 PBD::Signal0<void> Session::SuccessfulGraphSort;
155 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
157 const samplecnt_t Session::bounce_chunk_size = 8192;
158 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
159 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
161 // seconds should be added after the region exceeds end marker
162 #ifdef USE_TRACKS_CODE_FEATURES
163 const uint32_t Session::session_end_shift = 5;
165 const uint32_t Session::session_end_shift = 0;
168 /** @param snapshot_name Snapshot name, without .ardour suffix */
169 Session::Session (AudioEngine &eng,
170 const string& fullpath,
171 const string& snapshot_name,
172 BusProfile* bus_profile,
174 : _playlists (new SessionPlaylists)
176 , process_function (&Session::process_with_events)
177 , _bounce_processing_active (false)
178 , waiting_for_sync_offset (false)
179 , _base_sample_rate (0)
180 , _nominal_sample_rate (0)
181 , _current_sample_rate (0)
182 , transport_sub_state (0)
183 , _record_status (Disabled)
184 , _transport_sample (0)
186 , _session_range_location (0)
187 , _session_range_is_free (true)
189 , _remaining_latency_preroll (0)
190 , _engine_speed (1.0)
191 , _transport_speed (0)
192 , _default_transport_speed (1.0)
193 , _last_transport_speed (0)
194 , _signalled_varispeed (0)
195 , _target_transport_speed (0.0)
196 , auto_play_legal (false)
197 , _requested_return_sample (-1)
198 , current_block_size (0)
199 , _worst_output_latency (0)
200 , _worst_input_latency (0)
201 , _worst_route_latency (0)
202 , _send_latency_changes (0)
203 , _have_captured (false)
204 , _non_soloed_outs_muted (false)
207 , _solo_isolated_cnt (0)
209 , _was_seamless (Config->get_seamless_loop ())
210 , _under_nsm_control (false)
212 , transport_master_tracking_state (Stopped)
213 , master_wait_end (0)
214 , post_export_sync (false)
215 , post_export_position (0)
217 , _export_rolling (false)
218 , _realtime_export (false)
219 , _region_export (false)
220 , _export_preroll (0)
221 , _pre_export_mmc_enabled (false)
222 , _name (snapshot_name)
224 , _send_qf_mtc (false)
225 , _pframes_since_last_mtc (0)
227 , loop_changing (false)
229 , _session_dir (new SessionDirectory (fullpath))
230 , _current_snapshot_name (snapshot_name)
232 , state_was_pending (false)
233 , _state_of_the_state (StateOfTheState (CannotSave | InitialConnecting | Loading))
235 , _save_queued (false)
236 , _last_roll_location (0)
237 , _last_roll_or_reversal_location (0)
238 , _last_record_location (0)
239 , pending_auto_loop (false)
240 , _mempool ("Session", 3145728)
241 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
243 , _butler (new Butler (*this))
244 , _post_transport_work (0)
245 , _locations (new Locations (*this))
246 , _ignore_skips_updates (false)
247 , _rt_thread_active (false)
248 , _rt_emit_pending (false)
249 , _ac_thread_active (0)
250 , _latency_recompute_pending (0)
252 , outbound_mtc_timecode_frame (0)
253 , next_quarter_frame_to_send (-1)
254 , _samples_per_timecode_frame (0)
255 , _frames_per_hour (0)
256 , _timecode_frames_per_hour (0)
257 , last_timecode_valid (false)
258 , last_timecode_when (0)
259 , _send_timecode_update (false)
271 , ltc_timecode_offset (0)
272 , ltc_timecode_negative_offset (false)
273 , midi_control_ui (0)
275 , _all_route_group (new RouteGroup (*this, "all"))
276 , routes (new RouteList)
277 , _adding_routes_in_progress (false)
278 , _reconnecting_routes_in_progress (false)
279 , _route_deletion_in_progress (false)
280 , destructive_index (0)
281 , _track_number_decimals(1)
282 , default_fade_steepness (0)
283 , default_fade_msecs (0)
284 , _total_free_4k_blocks (0)
285 , _total_free_4k_blocks_uncertain (false)
286 , no_questions_about_missing_files (false)
289 , _bundles (new BundleList)
290 , _bundle_xml_node (0)
293 , _click_rec_only (false)
295 , click_emphasis_data (0)
297 , click_emphasis_length (0)
298 , _clicks_cleared (0)
299 , _count_in_samples (0)
300 , _play_range (false)
301 , _range_selection (-1,-1)
302 , _object_selection (-1,-1)
303 , _preroll_record_trim_len (0)
304 , _count_in_once (false)
306 , first_file_data_format_reset (true)
307 , first_file_header_format_reset (true)
308 , have_looped (false)
309 , _have_rec_enabled_track (false)
310 , _have_rec_disabled_track (true)
312 , _suspend_timecode_transmission (0)
313 , _speakers (new Speakers)
314 , _ignore_route_processor_changes (0)
319 , _vca_manager (new VCAManager (*this))
320 , _selection (new CoreSelection (*this))
321 , _global_locate_pending (false)
325 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
327 pthread_mutex_init (&_rt_emit_mutex, 0);
328 pthread_cond_init (&_rt_emit_cond, 0);
330 pthread_mutex_init (&_auto_connect_mutex, 0);
331 pthread_cond_init (&_auto_connect_cond, 0);
333 init_name_id_counter (1); // reset for new sessions, start at 1
334 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
336 pre_engine_init (fullpath); // sets _is_new
342 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
344 #ifdef USE_TRACKS_CODE_FEATURES
345 sr = EngineStateController::instance()->get_current_sample_rate();
347 if (ensure_engine (sr, true)) {
349 throw SessionException (_("Cannot connect to audio/midi engine"));
352 // set samplerate for plugins added early
353 // e.g from templates or MB channelstrip
354 set_block_size (_engine.samples_per_cycle());
355 set_sample_rate (_engine.sample_rate());
357 if (create (mix_template, bus_profile)) {
359 throw SessionException (_("Session initialization failed"));
362 /* if a mix template was provided, then ::create() will
363 * have copied it into the session and we need to load it
364 * so that we have the state ready for ::set_state()
365 * after the engine is started.
367 * Note that we do NOT try to get the sample rate from
368 * the template at this time, though doing so would
369 * be easy if we decided this was an appropriate part
373 if (!mix_template.empty()) {
375 if (load_state (_current_snapshot_name)) {
376 throw SessionException (_("Failed to load template/snapshot state"));
378 } catch (PBD::unknown_enumeration& e) {
379 throw SessionException (_("Failed to parse template/snapshot state"));
381 store_recent_templates (mix_template);
384 /* load default session properties - if any */
389 if (load_state (_current_snapshot_name)) {
390 throw SessionException (_("Failed to load state"));
393 /* try to get sample rate from XML state so that we
394 * can influence the SR if we set up the audio
399 XMLProperty const * prop;
400 XMLNode const * root (state_tree->root());
401 if ((prop = root->property (X_("sample-rate"))) != 0) {
402 sr = atoi (prop->value());
406 if (ensure_engine (sr, false)) {
408 throw SessionException (_("Cannot connect to audio/midi engine"));
412 int err = post_engine_init ();
417 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
421 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
424 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
427 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
430 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Unexpected exception during session setup, possibly invalid audio/midi engine parameters. Please see stdout/stderr for details")));
435 store_recent_sessions (_name, _path);
437 bool was_dirty = dirty();
440 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
442 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
443 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
446 DirtyChanged (); /* EMIT SIGNAL */
449 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
450 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
452 Send::ChangedLatency.connect_same_thread (*this, boost::bind (&Session::send_latency_compensation_change, this));
454 emit_thread_start ();
455 auto_connect_thread_start ();
457 /* hook us up to the engine since we are now completely constructed */
459 BootMessage (_("Connect to engine"));
461 _engine.set_session (this);
462 _engine.reset_timebase ();
464 #ifdef USE_TRACKS_CODE_FEATURES
466 EngineStateController::instance()->set_session(this);
469 if ( ARDOUR::Profile->get_trx () ) {
471 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
472 * each available input must have corresponding track when session starts.
475 uint32_t how_many (0);
477 std::vector<std::string> inputs;
478 EngineStateController::instance()->get_physical_audio_inputs(inputs);
480 how_many = inputs.size();
482 list<boost::shared_ptr<AudioTrack> > tracks;
484 // Track names after driver
485 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
486 string track_name = "";
487 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
489 track_name = inputs[i];
490 replace_all (track_name, "system:capture", "");
492 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
493 tracks.insert(tracks.begin(), single_track.front());
495 } else { // Default track names
496 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
499 if (tracks.size() != how_many) {
501 throw failed_constructor ();
507 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
509 if (!mix_template.empty ()) {
510 /* ::create() unsets _is_new after creating the session.
511 * But for templated sessions, the sample-rate is initially unset
512 * (not read from template), so we need to save it (again).
520 BootMessage (_("Session loading complete"));
532 Session::next_name_id ()
534 return g_atomic_int_add (&_name_id_counter, 1);
538 Session::name_id_counter ()
540 return g_atomic_int_get (&_name_id_counter);
544 Session::init_name_id_counter (guint n)
546 g_atomic_int_set (&_name_id_counter, n);
550 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
552 if (_engine.current_backend() == 0) {
553 /* backend is unknown ... */
554 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
555 if (r.get_value_or (-1) != 0) {
558 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
560 } else if (_engine.setup_required()) {
561 /* backend is known, but setup is needed */
562 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
563 if (r.get_value_or (-1) != 0) {
566 } else if (!_engine.running()) {
567 if (_engine.start()) {
572 /* at this point the engine should be running */
574 if (!_engine.running()) {
578 return immediately_post_engine ();
583 Session::immediately_post_engine ()
585 /* Do various initializations that should take place directly after we
586 * know that the engine is running, but before we either create a
587 * session or set state for an existing one.
590 _rt_tasklist.reset (new RTTaskList ());
592 if (how_many_dsp_threads () > 1) {
593 /* For now, only create the graph if we are using >1 DSP threads, as
594 it is a bit slower than the old code with 1 thread.
596 _process_graph.reset (new Graph (*this));
599 /* every time we reconnect, recompute worst case output latencies */
601 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
603 if (synced_to_engine()) {
604 _engine.transport_stop ();
607 if (config.get_jack_time_master()) {
608 _engine.transport_locate (_transport_sample);
612 BootMessage (_("Set up LTC"));
614 BootMessage (_("Set up Click"));
616 BootMessage (_("Set up standard connections"));
620 catch (failed_constructor& err) {
624 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
626 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
634 vector<void*> debug_pointers;
636 /* if we got to here, leaving pending capture state around
640 remove_pending_capture_state ();
644 _state_of_the_state = StateOfTheState (CannotSave | Deletion);
647 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
651 /* disconnect from any and all signals that we are connected to */
653 Port::PortSignalDrop (); /* EMIT SIGNAL */
656 /* shutdown control surface protocols while we still have ports
657 * and the engine to move data to any devices.
660 /* remove I/O objects before unsetting the engine session */
662 _ltc_output.reset ();
664 ControlProtocolManager::instance().drop_protocols ();
666 /* stop auto dis/connecting */
667 auto_connect_thread_terminate ();
669 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
671 _engine.remove_session ();
673 #ifdef USE_TRACKS_CODE_FEATURES
674 EngineStateController::instance()->remove_session();
677 /* deregister all ports - there will be no process or any other
678 * callbacks from the engine any more.
681 Port::PortDrop (); /* EMIT SIGNAL */
684 Glib::Threads::Mutex::Lock lm (controllables_lock);
685 for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
686 (*i)->DropReferences (); /* EMIT SIGNAL */
688 controllables.clear ();
691 /* clear history so that no references to objects are held any more */
695 /* clear state tree so that no references to objects are held any more */
701 /* unregister all lua functions, drop held references (if any) */
702 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
704 lua.do_command ("Session = nil");
712 lua.collect_garbage ();
715 /* reset dynamic state version back to default */
716 Stateful::loading_state_version = 0;
718 _butler->drop_references ();
722 delete _all_route_group;
724 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
725 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
729 if (click_data != default_click) {
730 delete [] click_data;
733 if (click_emphasis_data != default_click_emphasis) {
734 delete [] click_emphasis_data;
739 /* need to remove auditioner before monitoring section
740 * otherwise it is re-connected.
741 * Note: If a session was never successfully loaded, there
742 * may not yet be an auditioner.
745 auditioner->drop_references ();
749 /* drop references to routes held by the monitoring section
750 * specifically _monitor_out aux/listen references */
751 remove_monitor_section();
753 /* clear out any pending dead wood from RCU managed objects */
758 DiskReader::free_working_buffers();
760 /* tell everyone who is still standing that we're about to die */
763 /* tell everyone to drop references and delete objects as we go */
765 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
766 RegionFactory::delete_all_regions ();
768 /* Do this early so that VCAs no longer hold references to routes */
770 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
773 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
775 /* reset these three references to special routes before we do the usual route delete thing */
777 _master_out.reset ();
778 _monitor_out.reset ();
781 RCUWriter<RouteList> writer (routes);
782 boost::shared_ptr<RouteList> r = writer.get_copy ();
784 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
785 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
786 (*i)->drop_references ();
790 /* writer goes out of scope and updates master */
795 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
796 Glib::Threads::Mutex::Lock lm (source_lock);
797 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
798 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
799 i->second->drop_references ();
805 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
808 emit_thread_terminate ();
810 pthread_cond_destroy (&_rt_emit_cond);
811 pthread_mutex_destroy (&_rt_emit_mutex);
813 pthread_cond_destroy (&_auto_connect_cond);
814 pthread_mutex_destroy (&_auto_connect_mutex);
816 delete _scene_changer; _scene_changer = 0;
817 delete midi_control_ui; midi_control_ui = 0;
819 delete _mmc; _mmc = 0;
820 delete _midi_ports; _midi_ports = 0;
821 delete _locations; _locations = 0;
826 /* clear event queue, the session is gone, nobody is interested in
827 * those anymore, but they do leak memory if not removed
829 while (!immediate_events.empty ()) {
830 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
831 SessionEvent *ev = immediate_events.front ();
832 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
833 immediate_events.pop_front ();
837 case SessionEvent::AutoLoop:
838 case SessionEvent::Skip:
839 case SessionEvent::PunchIn:
840 case SessionEvent::PunchOut:
841 case SessionEvent::StopOnce:
842 case SessionEvent::RangeStop:
843 case SessionEvent::RangeLocate:
847 case SessionEvent::RealTimeOperation:
854 del = del && !_remove_event (ev);
862 /* unregister all dropped ports, process pending port deletion. */
863 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
864 // jack1 cannot cope with removing ports while processing
865 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
866 AudioEngine::instance()->clear_pending_port_deletions ();
869 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
873 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
876 Controllable::dump_registry ();
879 BOOST_SHOW_POINTERS ();
883 Session::setup_ltc ()
887 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
889 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
890 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
893 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
894 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
895 // TODO use auto-connect thread
896 reconnect_ltc_output ();
900 /* fix up names of LTC ports because we don't want the normal
901 * IO style of NAME/TYPE-{in,out}N
904 _ltc_output->nth (0)->set_name (X_("LTC-out"));
908 Session::setup_click ()
912 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
913 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
915 _click_io.reset (new ClickIO (*this, X_("Click")));
916 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
917 _click_gain->activate ();
919 setup_click_state (state_tree->root());
921 setup_click_state (0);
926 Session::setup_click_state (const XMLNode* node)
928 const XMLNode* child = 0;
930 if (node && (child = find_named_node (*node, "Click")) != 0) {
932 /* existing state for Click */
935 if (Stateful::loading_state_version < 3000) {
936 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
938 const XMLNodeList& children (child->children());
939 XMLNodeList::const_iterator i = children.begin();
940 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
942 if (i != children.end()) {
943 c = _click_gain->set_state (**i, Stateful::loading_state_version);
949 _clicking = Config->get_clicking ();
953 error << _("could not setup Click I/O") << endmsg;
960 /* default state for Click: dual-mono to first 2 physical outputs */
963 _engine.get_physical_outputs (DataType::AUDIO, outs);
965 for (uint32_t physport = 0; physport < 2; ++physport) {
966 if (outs.size() > physport) {
967 if (_click_io->add_port (outs[physport], this)) {
968 // relax, even though its an error
973 if (_click_io->n_ports () > ChanCount::ZERO) {
974 _clicking = Config->get_clicking ();
980 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
981 MidiPortFlags include, MidiPortFlags exclude)
983 _engine.get_physical_inputs (type, inputs, include, exclude);
984 _engine.get_physical_outputs (type, outputs, include, exclude);
988 Session::setup_bundles ()
992 RCUWriter<BundleList> writer (_bundles);
993 boost::shared_ptr<BundleList> b = writer.get_copy ();
994 for (BundleList::iterator i = b->begin(); i != b->end();) {
995 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
1003 vector<string> inputs[DataType::num_types];
1004 vector<string> outputs[DataType::num_types];
1006 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1007 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
1008 MidiPortFlags (0), /* no specific inclusions */
1009 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1013 /* Create a set of Bundle objects that map
1014 to the physical I/O currently available. We create both
1015 mono and stereo bundles, so that the common cases of mono
1016 and stereo tracks get bundles to put in their mixer strip
1017 in / out menus. There may be a nicer way of achieving that;
1018 it doesn't really scale that well to higher channel counts
1021 /* mono output bundles */
1023 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1025 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1027 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1029 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1032 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1033 c->add_channel (_("mono"), DataType::AUDIO);
1034 c->set_port (0, outputs[DataType::AUDIO][np]);
1036 add_bundle (c, false);
1039 /* stereo output bundles */
1041 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1042 if (np + 1 < outputs[DataType::AUDIO].size()) {
1044 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1045 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1046 c->add_channel (_("L"), DataType::AUDIO);
1047 c->set_port (0, outputs[DataType::AUDIO][np]);
1048 c->add_channel (_("R"), DataType::AUDIO);
1049 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1051 add_bundle (c, false);
1055 /* mono input bundles */
1057 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1059 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1061 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1063 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1066 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1067 c->add_channel (_("mono"), DataType::AUDIO);
1068 c->set_port (0, inputs[DataType::AUDIO][np]);
1070 add_bundle (c, false);
1073 /* stereo input bundles */
1075 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1076 if (np + 1 < inputs[DataType::AUDIO].size()) {
1078 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1080 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1081 c->add_channel (_("L"), DataType::AUDIO);
1082 c->set_port (0, inputs[DataType::AUDIO][np]);
1083 c->add_channel (_("R"), DataType::AUDIO);
1084 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1086 add_bundle (c, false);
1090 /* MIDI input bundles */
1092 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1093 string n = inputs[DataType::MIDI][np];
1095 std::string pn = _engine.get_pretty_name_by_name (n);
1099 boost::erase_first (n, X_("alsa_pcm:"));
1101 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1102 c->add_channel ("", DataType::MIDI);
1103 c->set_port (0, inputs[DataType::MIDI][np]);
1104 add_bundle (c, false);
1107 /* MIDI output bundles */
1109 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1110 string n = outputs[DataType::MIDI][np];
1111 std::string pn = _engine.get_pretty_name_by_name (n);
1115 boost::erase_first (n, X_("alsa_pcm:"));
1117 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1118 c->add_channel ("", DataType::MIDI);
1119 c->set_port (0, outputs[DataType::MIDI][np]);
1120 add_bundle (c, false);
1123 // we trust the backend to only calls us if there's a change
1124 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1128 Session::auto_connect_master_bus ()
1130 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1134 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1135 // In this case it means "Multi Out" output mode
1136 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1140 /* if requested auto-connect the outputs to the first N physical ports.
1143 uint32_t limit = _master_out->n_outputs().n_total();
1144 vector<string> outputs[DataType::num_types];
1146 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1147 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1150 for (uint32_t n = 0; n < limit; ++n) {
1151 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1153 if (outputs[p->type()].size() > n) {
1154 connect_to = outputs[p->type()][n];
1157 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1158 if (_master_out->output()->connect (p, connect_to, this)) {
1159 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1168 Session::remove_monitor_section ()
1170 if (!_monitor_out || Profile->get_trx()) {
1174 /* allow deletion when session is unloaded */
1175 if (!_engine.running() && !deletion_in_progress ()) {
1176 error << _("Cannot remove monitor section while the engine is offline.") << endmsg;
1180 /* force reversion to Solo-In-Place */
1181 Config->set_solo_control_is_listen_control (false);
1183 /* if we are auditioning, cancel it ... this is a workaround
1184 to a problem (auditioning does not execute the process graph,
1185 which is needed to remove routes when using >1 core for processing)
1189 if (!deletion_in_progress ()) {
1190 /* Hold process lock while doing this so that we don't hear bits and
1191 * pieces of audio as we work on each route.
1194 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1196 /* Connect tracks to monitor section. Note that in an
1197 existing session, the internal sends will already exist, but we want the
1198 routes to notice that they connect to the control out specifically.
1202 boost::shared_ptr<RouteList> r = routes.reader ();
1203 ProcessorChangeBlocker pcb (this, false);
1205 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1207 if ((*x)->is_monitor()) {
1209 } else if ((*x)->is_master()) {
1212 (*x)->remove_aux_or_listen (_monitor_out);
1217 remove_route (_monitor_out);
1218 if (deletion_in_progress ()) {
1222 auto_connect_master_bus ();
1225 auditioner->connect ();
1228 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1232 Session::add_monitor_section ()
1236 if (!_engine.running()) {
1237 error << _("Cannot create monitor section while the engine is offline.") << endmsg;
1241 if (_monitor_out || !_master_out || Profile->get_trx()) {
1245 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1251 BOOST_MARK_ROUTE(r);
1254 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1255 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1256 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1258 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1263 add_routes (rl, false, false, false, 0);
1265 assert (_monitor_out);
1267 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1268 are undefined, at best.
1271 uint32_t limit = _monitor_out->n_inputs().n_audio();
1275 /* connect the inputs to the master bus outputs. this
1276 * represents a separate data feed from the internal sends from
1277 * each route. as of jan 2011, it allows the monitor section to
1278 * conditionally ignore either the internal sends or the normal
1279 * input feed, but we should really find a better way to do
1283 _master_out->output()->disconnect (this);
1285 for (uint32_t n = 0; n < limit; ++n) {
1286 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1287 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1290 string connect_to = o->name();
1291 if (_monitor_out->input()->connect (p, connect_to, this)) {
1292 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1300 /* if monitor section is not connected, connect it to physical outs
1303 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1305 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1307 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1310 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1312 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1313 Config->get_monitor_bus_preferred_bundle())
1319 /* Monitor bus is audio only */
1321 vector<string> outputs[DataType::num_types];
1323 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1324 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1327 uint32_t mod = outputs[DataType::AUDIO].size();
1328 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1332 for (uint32_t n = 0; n < limit; ++n) {
1334 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1336 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1337 connect_to = outputs[DataType::AUDIO][n % mod];
1340 if (!connect_to.empty()) {
1341 if (_monitor_out->output()->connect (p, connect_to, this)) {
1342 error << string_compose (
1343 _("cannot connect control output %1 to %2"),
1354 /* Hold process lock while doing this so that we don't hear bits and
1355 * pieces of audio as we work on each route.
1358 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1360 /* Connect tracks to monitor section. Note that in an
1361 existing session, the internal sends will already exist, but we want the
1362 routes to notice that they connect to the control out specifically.
1366 boost::shared_ptr<RouteList> rls = routes.reader ();
1368 ProcessorChangeBlocker pcb (this, false /* XXX */);
1370 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1372 if ((*x)->is_monitor()) {
1374 } else if ((*x)->is_master()) {
1377 (*x)->enable_monitor_send ();
1382 auditioner->connect ();
1385 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1389 Session::reset_monitor_section ()
1391 /* Process lock should be held by the caller.*/
1393 if (!_monitor_out || Profile->get_trx()) {
1397 uint32_t limit = _master_out->n_outputs().n_audio();
1399 /* connect the inputs to the master bus outputs. this
1400 * represents a separate data feed from the internal sends from
1401 * each route. as of jan 2011, it allows the monitor section to
1402 * conditionally ignore either the internal sends or the normal
1403 * input feed, but we should really find a better way to do
1407 _master_out->output()->disconnect (this);
1408 _monitor_out->output()->disconnect (this);
1410 // monitor section follow master bus - except midi
1411 ChanCount mon_chn (_master_out->output()->n_ports());
1412 mon_chn.set_midi (0);
1414 _monitor_out->input()->ensure_io (mon_chn, false, this);
1415 _monitor_out->output()->ensure_io (mon_chn, false, this);
1417 for (uint32_t n = 0; n < limit; ++n) {
1418 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1419 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1422 string connect_to = o->name();
1423 if (_monitor_out->input()->connect (p, connect_to, this)) {
1424 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1431 /* connect monitor section to physical outs
1434 if (Config->get_auto_connect_standard_busses()) {
1436 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1438 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1441 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1443 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1444 Config->get_monitor_bus_preferred_bundle())
1450 /* Monitor bus is audio only */
1452 vector<string> outputs[DataType::num_types];
1454 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1455 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1458 uint32_t mod = outputs[DataType::AUDIO].size();
1459 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1463 for (uint32_t n = 0; n < limit; ++n) {
1465 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1467 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1468 connect_to = outputs[DataType::AUDIO][n % mod];
1471 if (!connect_to.empty()) {
1472 if (_monitor_out->output()->connect (p, connect_to, this)) {
1473 error << string_compose (
1474 _("cannot connect control output %1 to %2"),
1485 /* Connect tracks to monitor section. Note that in an
1486 existing session, the internal sends will already exist, but we want the
1487 routes to notice that they connect to the control out specifically.
1491 boost::shared_ptr<RouteList> rls = routes.reader ();
1493 ProcessorChangeBlocker pcb (this, false);
1495 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1497 if ((*x)->is_monitor()) {
1499 } else if ((*x)->is_master()) {
1502 (*x)->enable_monitor_send ();
1508 Session::add_master_bus (ChanCount const& count)
1510 if (master_out ()) {
1516 boost::shared_ptr<Route> r (new Route (*this, _("Master"), PresentationInfo::MasterOut, DataType::AUDIO));
1521 BOOST_MARK_ROUTE(r);
1524 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1525 r->input()->ensure_io (count, false, this);
1526 r->output()->ensure_io (count, false, this);
1530 add_routes (rl, false, false, false, PresentationInfo::max_order);
1535 Session::hookup_io ()
1537 /* stop graph reordering notifications from
1538 causing resorts, etc.
1541 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1545 /* we delay creating the auditioner till now because
1546 it makes its own connections to ports.
1550 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1552 throw failed_constructor ();
1557 catch (failed_constructor& err) {
1558 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1562 /* load bundles, which we may have postponed earlier on */
1563 if (_bundle_xml_node) {
1564 load_bundles (*_bundle_xml_node);
1565 delete _bundle_xml_node;
1568 /* Tell all IO objects to connect themselves together */
1570 IO::enable_connecting ();
1572 /* Now tell all "floating" ports to connect to whatever
1573 they should be connected to.
1576 AudioEngine::instance()->reconnect_ports ();
1578 /* Anyone who cares about input state, wake up and do something */
1580 IOConnectionsComplete (); /* EMIT SIGNAL */
1582 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1584 /* now handle the whole enchilada as if it was one
1585 graph reorder event.
1590 /* update the full solo state, which can't be
1591 correctly determined on a per-route basis, but
1592 needs the global overview that only the session
1596 update_route_solo_state ();
1600 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1602 boost::shared_ptr<Track> track = wp.lock ();
1607 boost::shared_ptr<Playlist> playlist;
1609 if ((playlist = track->playlist()) != 0) {
1610 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1611 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1612 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1617 Session::record_enabling_legal () const
1619 /* this used to be in here, but survey says.... we don't need to restrict it */
1620 // if (record_status() == Recording) {
1624 if (Config->get_all_safe()) {
1631 Session::set_track_monitor_input_status (bool yn)
1633 boost::shared_ptr<RouteList> rl = routes.reader ();
1634 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1635 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1636 if (tr && tr->rec_enable_control()->get_value()) {
1637 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1638 tr->request_input_monitoring (yn);
1644 Session::auto_punch_start_changed (Location* location)
1646 replace_event (SessionEvent::PunchIn, location->start());
1648 if (get_record_enabled() && config.get_punch_in() && !actively_recording ()) {
1649 /* capture start has been changed, so save new pending state */
1650 save_state ("", true);
1655 Session::auto_punch_end_changed (Location* location)
1657 replace_event (SessionEvent::PunchOut, location->end());
1661 Session::auto_punch_changed (Location* location)
1663 auto_punch_start_changed (location);
1664 auto_punch_end_changed (location);
1667 /** @param loc A loop location.
1668 * @param pos Filled in with the start time of the required fade-out (in session samples).
1669 * @param length Filled in with the length of the required fade-out.
1672 Session::auto_loop_declick_range (Location* loc, samplepos_t & pos, samplepos_t & length)
1674 pos = max (loc->start(), loc->end() - 64);
1675 length = loc->end() - pos;
1679 Session::auto_loop_changed (Location* location)
1681 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1684 auto_loop_declick_range (location, dcp, dcl);
1686 bool rolling = transport_rolling ();
1688 if (rolling && play_loop) {
1690 if (_transport_sample < location->start() || _transport_sample > location->end()) {
1691 // relocate to beginning of loop
1692 clear_events (SessionEvent::LocateRoll);
1693 request_locate (location->start(), true);
1697 clear_events (SessionEvent::AutoLoop);
1700 /* possibly move playhead if not rolling; if we are rolling we'll move
1701 to the loop start on stop if that is appropriate.
1706 if (!rolling && select_playhead_priority_target (pos)) {
1707 if (pos == location->start()) {
1708 request_locate (pos);
1712 last_loopend = location->end();
1717 Session::set_auto_punch_location (Location* location)
1721 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1722 punch_connections.drop_connections();
1723 existing->set_auto_punch (false, this);
1724 clear_events (SessionEvent::PunchIn);
1725 clear_events (SessionEvent::PunchOut);
1726 auto_punch_location_changed (0);
1731 if (location == 0) {
1735 if (location->end() <= location->start()) {
1736 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1740 punch_connections.drop_connections ();
1742 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1743 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1744 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1746 location->set_auto_punch (true, this);
1748 auto_punch_changed (location);
1750 auto_punch_location_changed (location);
1754 Session::set_session_extents (samplepos_t start, samplepos_t end)
1757 if ((existing = _locations->session_range_location()) == 0) {
1758 //if there is no existing session, we need to make a new session location (should never happen)
1759 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1763 error << _("Session: you can't use that location for session start/end)") << endmsg;
1767 existing->set( start, end );
1773 Session::set_auto_loop_location (Location* location)
1777 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1778 loop_connections.drop_connections ();
1779 existing->set_auto_loop (false, this);
1780 remove_event (existing->end(), SessionEvent::AutoLoop);
1783 auto_loop_declick_range (existing, dcp, dcl);
1784 auto_loop_location_changed (0);
1789 if (location == 0) {
1793 if (location->end() <= location->start()) {
1794 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1798 last_loopend = location->end();
1800 loop_connections.drop_connections ();
1802 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1803 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1804 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1805 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1807 location->set_auto_loop (true, this);
1809 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1810 // set all tracks to use internal looping
1811 boost::shared_ptr<RouteList> rl = routes.reader ();
1812 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1813 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1814 if (tr && !tr->is_private_route()) {
1815 tr->set_loop (location);
1820 /* take care of our stuff first */
1822 auto_loop_changed (location);
1824 /* now tell everyone else */
1826 auto_loop_location_changed (location);
1830 Session::update_marks (Location*)
1836 Session::update_skips (Location* loc, bool consolidate)
1838 if (_ignore_skips_updates) {
1842 Locations::LocationList skips;
1845 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1846 consolidate_skips (loc);
1849 sync_locations_to_skips ();
1855 Session::consolidate_skips (Location* loc)
1857 Locations::LocationList all_locations = _locations->list ();
1859 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1861 if (!(*l)->is_skip ()) {
1866 /* don't test against self */
1873 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1874 case Evoral::OverlapInternal:
1875 case Evoral::OverlapExternal:
1876 case Evoral::OverlapStart:
1877 case Evoral::OverlapEnd:
1878 /* adjust new location to cover existing one */
1879 loc->set_start (min (loc->start(), (*l)->start()));
1880 loc->set_end (max (loc->end(), (*l)->end()));
1881 /* we don't need this one any more */
1882 _locations->remove (*l);
1883 /* the location has been deleted, so remove reference to it in our local list */
1884 l = all_locations.erase (l);
1887 case Evoral::OverlapNone:
1895 Session::sync_locations_to_skips ()
1897 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1898 * Session::_sync_locations_to_skips() from the audioengine thread.
1900 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1904 Session::_sync_locations_to_skips ()
1906 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1908 Locations::LocationList const & locs (_locations->list());
1910 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1912 Location* location = *i;
1914 if (location->is_skip() && location->is_skipping()) {
1915 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1923 Session::location_added (Location *location)
1925 if (location->is_auto_punch()) {
1926 set_auto_punch_location (location);
1929 if (location->is_auto_loop()) {
1930 set_auto_loop_location (location);
1933 if (location->is_session_range()) {
1934 /* no need for any signal handling or event setting with the session range,
1935 because we keep a direct reference to it and use its start/end directly.
1937 _session_range_location = location;
1940 if (location->is_mark()) {
1941 /* listen for per-location signals that require us to do any * global updates for marks */
1943 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1944 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1945 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1946 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1947 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1950 if (location->is_range_marker()) {
1951 /* listen for per-location signals that require us to do any * global updates for marks */
1953 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1954 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1955 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1956 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1957 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1960 if (location->is_skip()) {
1961 /* listen for per-location signals that require us to update skip-locate events */
1963 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1964 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1965 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1966 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1967 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1969 update_skips (location, true);
1976 Session::location_removed (Location *location)
1978 if (location->is_auto_loop()) {
1979 set_auto_loop_location (0);
1981 set_track_loop (false);
1986 if (location->is_auto_punch()) {
1987 set_auto_punch_location (0);
1990 if (location->is_session_range()) {
1991 /* this is never supposed to happen */
1992 error << _("programming error: session range removed!") << endl;
1995 if (location->is_skip()) {
1997 update_skips (location, false);
2004 Session::locations_changed ()
2006 _locations->apply (*this, &Session::_locations_changed);
2010 Session::_locations_changed (const Locations::LocationList& locations)
2012 /* There was some mass-change in the Locations object.
2014 We might be re-adding a location here but it doesn't actually matter
2015 for all the locations that the Session takes an interest in.
2019 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
2020 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
2021 location_added (*i);
2025 update_skips (NULL, false);
2029 Session::enable_record ()
2031 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2032 /* no recording at anything except normal speed */
2037 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2039 if (rs == Recording) {
2043 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2045 _last_record_location = _transport_sample;
2046 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2048 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2049 set_track_monitor_input_status (true);
2052 RecordStateChanged ();
2059 Session::set_all_tracks_record_enabled (bool enable )
2061 boost::shared_ptr<RouteList> rl = routes.reader();
2062 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2066 Session::disable_record (bool rt_context, bool force)
2070 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2072 if (!Config->get_latched_record_enable () || force) {
2073 g_atomic_int_set (&_record_status, Disabled);
2074 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2076 if (rs == Recording) {
2077 g_atomic_int_set (&_record_status, Enabled);
2081 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2082 set_track_monitor_input_status (false);
2085 RecordStateChanged (); /* emit signal */
2088 remove_pending_capture_state ();
2094 Session::step_back_from_record ()
2096 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2098 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2099 set_track_monitor_input_status (false);
2102 RecordStateChanged (); /* emit signal */
2107 Session::maybe_enable_record (bool rt_context)
2109 if (_step_editors > 0) {
2113 g_atomic_int_set (&_record_status, Enabled);
2115 /* This function is currently called from somewhere other than an RT thread.
2116 * (except maybe lua scripts, which can use rt_context = true)
2117 * This save_state() call therefore doesn't impact anything. Doing it here
2118 * means that we save pending state of which sources the next record will use,
2119 * which gives us some chance of recovering from a crash during the record.
2123 save_state ("", true);
2126 if (_transport_speed) {
2127 if (!config.get_punch_in()) {
2131 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2132 RecordStateChanged (); /* EMIT SIGNAL */
2139 Session::audible_sample (bool* latent_locate) const
2141 if (latent_locate) {
2142 *latent_locate = false;
2147 if (synced_to_engine()) {
2148 /* Note: this is basically just sync-to-JACK */
2149 ret = _engine.transport_sample();
2151 ret = _transport_sample;
2156 if (!transport_rolling()) {
2160 #if 0 // TODO looping
2161 if (_transport_speed > 0.0f) {
2162 if (play_loop && have_looped) {
2163 /* the play-position wrapped at the loop-point
2164 * ardour is already playing the beginning of the loop,
2165 * but due to playback latency, the "audible frame"
2166 * is still at the end of the loop.
2168 Location *location = _locations->auto_loop_location();
2169 sampleoffset_t lo = location->start() - ret;
2171 ret = location->end () - lo;
2172 if (latent_locate) {
2173 *latent_locate = true;
2177 } else if (_transport_speed < 0.0f) {
2178 /* XXX wot? no backward looping? */
2182 return std::max ((samplepos_t)0, ret);
2186 Session::preroll_samples (samplepos_t pos) const
2188 const float pr = Config->get_preroll_seconds();
2189 if (pos >= 0 && pr < 0) {
2190 const Tempo& tempo = _tempo_map->tempo_at_sample (pos);
2191 const Meter& meter = _tempo_map->meter_at_sample (pos);
2192 return meter.samples_per_bar (tempo, sample_rate()) * -pr;
2197 return pr * sample_rate();
2201 Session::set_sample_rate (samplecnt_t frames_per_second)
2203 /** \fn void Session::set_sample_size(samplecnt_t)
2204 the AudioEngine object that calls this guarantees
2205 that it will not be called while we are also in
2206 ::process(). Its fine to do things that block
2210 if (_base_sample_rate == 0) {
2211 _base_sample_rate = frames_per_second;
2213 else if (_base_sample_rate != frames_per_second && frames_per_second != _nominal_sample_rate) {
2214 NotifyAboutSampleRateMismatch (_base_sample_rate, frames_per_second);
2216 _nominal_sample_rate = frames_per_second;
2221 reset_write_sources (false);
2223 // XXX we need some equivalent to this, somehow
2224 // SndFileSource::setup_standard_crossfades (frames_per_second);
2228 /* XXX need to reset/reinstantiate all LADSPA plugins */
2232 Session::set_block_size (pframes_t nframes)
2234 /* the AudioEngine guarantees
2235 that it will not be called while we are also in
2236 ::process(). It is therefore fine to do things that block
2241 current_block_size = nframes;
2245 boost::shared_ptr<RouteList> r = routes.reader ();
2247 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2248 (*i)->set_block_size (nframes);
2251 boost::shared_ptr<RouteList> rl = routes.reader ();
2252 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2253 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2255 tr->set_block_size (nframes);
2259 set_worst_io_latencies ();
2265 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2267 boost::shared_ptr<Route> r2;
2269 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2270 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2274 /* make a copy of the existing list of routes that feed r1 */
2276 Route::FedBy existing (r1->fed_by());
2278 /* for each route that feeds r1, recurse, marking it as feeding
2282 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2283 if (!(r2 = i->r.lock ())) {
2284 /* (*i) went away, ignore it */
2288 /* r2 is a route that feeds r1 which somehow feeds base. mark
2289 base as being fed by r2
2292 rbase->add_fed_by (r2, i->sends_only);
2296 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2300 if (r1->feeds (r2) && r2->feeds (r1)) {
2304 /* now recurse, so that we can mark base as being fed by
2305 all routes that feed r2
2308 trace_terminal (r2, rbase);
2315 Session::resort_routes ()
2317 /* don't do anything here with signals emitted
2318 by Routes during initial setup or while we
2319 are being destroyed.
2322 if (inital_connect_or_deletion_in_progress ()) {
2326 if (_route_deletion_in_progress) {
2331 RCUWriter<RouteList> writer (routes);
2332 boost::shared_ptr<RouteList> r = writer.get_copy ();
2333 resort_routes_using (r);
2334 /* writer goes out of scope and forces update */
2338 if (DEBUG_ENABLED(DEBUG::Graph)) {
2339 boost::shared_ptr<RouteList> rl = routes.reader ();
2340 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2341 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2343 const Route::FedBy& fb ((*i)->fed_by());
2345 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2346 boost::shared_ptr<Route> sf = f->r.lock();
2348 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2357 /** This is called whenever we need to rebuild the graph of how we will process
2359 * @param r List of routes, in any order.
2363 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2365 /* We are going to build a directed graph of our routes;
2366 this is where the edges of that graph are put.
2371 /* Go through all routes doing two things:
2373 * 1. Collect the edges of the route graph. Each of these edges
2374 * is a pair of routes, one of which directly feeds the other
2375 * either by a JACK connection or by an internal send.
2377 * 2. Begin the process of making routes aware of which other
2378 * routes directly or indirectly feed them. This information
2379 * is used by the solo code.
2382 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2384 /* Clear out the route's list of direct or indirect feeds */
2385 (*i)->clear_fed_by ();
2387 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2389 bool via_sends_only;
2391 /* See if this *j feeds *i according to the current state of the JACK
2392 connections and internal sends.
2394 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2395 /* add the edge to the graph (part #1) */
2396 edges.add (*j, *i, via_sends_only);
2397 /* tell the route (for part #2) */
2398 (*i)->add_fed_by (*j, via_sends_only);
2403 /* Attempt a topological sort of the route graph */
2404 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2406 if (sorted_routes) {
2407 /* We got a satisfactory topological sort, so there is no feedback;
2410 Note: the process graph rechain does not require a
2411 topologically-sorted list, but hey ho.
2413 if (_process_graph) {
2414 _process_graph->rechain (sorted_routes, edges);
2417 _current_route_graph = edges;
2419 /* Complete the building of the routes' lists of what directly
2420 or indirectly feeds them.
2422 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2423 trace_terminal (*i, *i);
2426 *r = *sorted_routes;
2429 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2430 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2431 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2435 SuccessfulGraphSort (); /* EMIT SIGNAL */
2438 /* The topological sort failed, so we have a problem. Tell everyone
2439 and stick to the old graph; this will continue to be processed, so
2440 until the feedback is fixed, what is played back will not quite
2441 reflect what is actually connected. Note also that we do not
2442 do trace_terminal here, as it would fail due to an endless recursion,
2443 so the solo code will think that everything is still connected
2447 FeedbackDetected (); /* EMIT SIGNAL */
2452 /** Find a route name starting with \a base, maybe followed by the
2453 * lowest \a id. \a id will always be added if \a definitely_add_number
2454 * is true on entry; otherwise it will only be added if required
2455 * to make the name unique.
2457 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2458 * The available route name with the lowest ID will be used, and \a id
2459 * will be set to the ID.
2461 * \return false if a route name could not be found, and \a track_name
2462 * and \a id do not reflect a free route name.
2465 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2467 /* the base may conflict with ports that do not belong to existing
2468 routes, but hidden objects like the click track. So check port names
2469 before anything else.
2472 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2473 if (base == reserved->first) {
2474 /* Check if this reserved name already exists, and if
2475 so, disallow it without a numeric suffix.
2477 if (!reserved->second || route_by_name (reserved->first)) {
2478 definitely_add_number = true;
2487 /* if we have "base 1" already, it doesn't make sense to add "base"
2488 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2490 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2491 /* just use the base */
2497 name = string_compose ("%1 %2", base, id);
2499 if (route_by_name (name) == 0) {
2505 } while (id < (UINT_MAX-1));
2510 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2512 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2514 in = ChanCount::ZERO;
2515 out = ChanCount::ZERO;
2517 boost::shared_ptr<RouteList> r = routes.reader ();
2519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2520 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2524 assert (!tr->is_auditioner()); // XXX remove me
2525 in += tr->n_inputs();
2526 out += tr->n_outputs();
2531 Session::default_track_name_pattern (DataType t)
2534 case DataType::AUDIO:
2535 if (Profile->get_trx()) {
2542 case DataType::MIDI:
2549 /** Caller must not hold process lock
2550 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2551 * @param instrument plugin info for the instrument to insert pre-fader, if any
2553 list<boost::shared_ptr<MidiTrack> >
2554 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2555 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2556 RouteGroup* route_group, uint32_t how_many,
2557 string name_template, PresentationInfo::order_t order,
2561 uint32_t track_id = 0;
2563 RouteList new_routes;
2564 list<boost::shared_ptr<MidiTrack> > ret;
2566 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2567 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2570 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2571 error << "cannot find name for new midi track" << endmsg;
2575 boost::shared_ptr<MidiTrack> track;
2578 track.reset (new MidiTrack (*this, track_name, mode));
2580 if (track->init ()) {
2585 track->set_strict_io (true);
2588 BOOST_MARK_TRACK (track);
2591 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2592 if (track->input()->ensure_io (input, false, this)) {
2593 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2597 if (track->output()->ensure_io (output, false, this)) {
2598 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2604 route_group->add (track);
2607 new_routes.push_back (track);
2608 ret.push_back (track);
2611 catch (failed_constructor &err) {
2612 error << _("Session: could not create new midi track.") << endmsg;
2616 catch (AudioEngine::PortRegistrationFailure& pfe) {
2618 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;
2626 if (!new_routes.empty()) {
2627 StateProtector sp (this);
2628 if (Profile->get_trx()) {
2629 add_routes (new_routes, false, false, false, order);
2631 add_routes (new_routes, true, true, false, order);
2635 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2636 PluginPtr plugin = instrument->load (*this);
2638 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2642 plugin->load_preset (*pset);
2644 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2646 pi->set_strict_io (true);
2649 (*r)->add_processor (pi, PreFader);
2651 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2652 (*r)->move_instrument_down (false);
2662 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2663 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2664 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2667 uint32_t bus_id = 0;
2671 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2674 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2675 error << "cannot find name for new midi bus" << endmsg;
2680 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2687 bus->set_strict_io (true);
2690 BOOST_MARK_ROUTE(bus);
2693 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2695 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2696 error << _("cannot configure new midi bus input") << endmsg;
2701 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2702 error << _("cannot configure new midi bus output") << endmsg;
2708 route_group->add (bus);
2711 bus->add_internal_return ();
2712 ret.push_back (bus);
2715 catch (failed_constructor &err) {
2716 error << _("Session: could not create new audio route.") << endmsg;
2720 catch (AudioEngine::PortRegistrationFailure& pfe) {
2721 error << pfe.what() << endmsg;
2731 StateProtector sp (this);
2732 add_routes (ret, false, false, false, order);
2735 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2736 PluginPtr plugin = instrument->load (*this);
2738 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2742 plugin->load_preset (*pset);
2744 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2746 pi->set_strict_io (true);
2749 (*r)->add_processor (pi, PreFader);
2751 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2752 (*r)->move_instrument_down (false);
2764 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2766 boost::shared_ptr<Route> midi_track (wmt.lock());
2772 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2774 if (change.after.n_audio() <= change.before.n_audio()) {
2778 /* new audio ports: make sure the audio goes somewhere useful,
2779 * unless the user has no-auto-connect selected.
2781 * The existing ChanCounts don't matter for this call as they are only
2782 * to do with matching input and output indices, and we are only changing
2785 auto_connect_route (midi_track, false, ChanCount(), change.before);
2789 #ifdef USE_TRACKS_CODE_FEATURES
2792 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2794 return route1->remote_control_id() < route2->remote_control_id();
2798 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2800 // it is not allowed to perform connection
2801 if (!IO::connecting_legal) {
2805 // if we are deleting routes we will call this once at the end
2806 if (_route_deletion_in_progress) {
2810 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2816 // We need to disconnect the route's inputs and outputs first
2817 // basing on autoconnect configuration
2818 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2819 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2821 ChanCount existing_inputs;
2822 ChanCount existing_outputs;
2823 count_existing_track_channels (existing_inputs, existing_outputs);
2825 //ChanCount inputs = ChanCount::ZERO;
2826 //ChanCount outputs = ChanCount::ZERO;
2828 RouteList existing_routes = *routes.reader ();
2829 existing_routes.sort (compare_routes_by_remote_id);
2832 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2834 vector<string> physinputs;
2835 vector<string> physoutputs;
2837 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2838 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2840 uint32_t input_n = 0;
2841 uint32_t output_n = 0;
2842 RouteList::iterator rIter = existing_routes.begin();
2843 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2844 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2845 for (; rIter != existing_routes.end(); ++rIter) {
2846 if (*rIter == _master_out || *rIter == _monitor_out ) {
2850 if (current_output_auto_connection == AutoConnectPhysical) {
2851 (*rIter)->amp()->deactivate();
2852 } else if (current_output_auto_connection == AutoConnectMaster) {
2853 (*rIter)->amp()->activate();
2856 if (reconnectIputs) {
2857 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2859 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2861 if (current_input_auto_connection & AutoConnectPhysical) {
2863 if ( input_n == physinputs.size() ) {
2867 string port = physinputs[input_n];
2869 if (port.empty() ) {
2870 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2873 //GZ: check this; could be heavy
2874 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2880 if (reconnectOutputs) {
2882 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2883 if (current_output_auto_connection & AutoConnectPhysical) {
2885 //GZ: check this; could be heavy
2886 (*rIter)->output()->disconnect (this);
2887 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2889 //GZ: check this; could be heavy
2890 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2892 } else if (current_output_auto_connection & AutoConnectMaster){
2894 if (!reconnect_master) {
2898 //GZ: check this; could be heavy
2899 (*rIter)->output()->disconnect (this);
2902 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2903 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2905 error << error << "Master bus is not available" << endmsg;
2910 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2911 if (current_output_auto_connection & AutoConnectPhysical) {
2913 if ( output_n == physoutputs.size() ) {
2917 string port = physoutputs[output_n];
2919 if (port.empty() ) {
2920 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2923 //GZ: check this; could be heavy
2924 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2927 } else if (current_output_auto_connection & AutoConnectMaster) {
2929 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2933 // connect to master bus
2934 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2936 if (port.empty() ) {
2937 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2941 //GZ: check this; could be heavy
2942 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2949 _master_out->output()->disconnect (this);
2950 auto_connect_master_bus ();
2955 session_routes_reconnected (); /* EMIT SIGNAL */
2959 Session::reconnect_midi_scene_ports(bool inputs)
2963 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2965 scene_in_ptr->disconnect_all ();
2967 std::vector<EngineStateController::MidiPortState> midi_port_states;
2968 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2970 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2972 for (; state_iter != midi_port_states.end(); ++state_iter) {
2973 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2974 scene_in_ptr->connect (state_iter->name);
2981 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2983 if (scene_out_ptr ) {
2984 scene_out_ptr->disconnect_all ();
2986 std::vector<EngineStateController::MidiPortState> midi_port_states;
2987 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2989 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2991 for (; state_iter != midi_port_states.end(); ++state_iter) {
2992 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2993 scene_out_ptr->connect (state_iter->name);
3001 Session::reconnect_mmc_ports(bool inputs)
3003 if (inputs ) { // get all enabled midi input ports
3005 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
3007 mmc_in_ptr->disconnect_all ();
3008 std::vector<std::string> enabled_midi_inputs;
3009 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3011 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3013 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3014 mmc_in_ptr->connect (*port_iter);
3018 } else { // get all enabled midi output ports
3020 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3022 mmc_out_ptr->disconnect_all ();
3023 std::vector<std::string> enabled_midi_outputs;
3024 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3026 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3028 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3029 mmc_out_ptr->connect (*port_iter);
3038 Session::ensure_stripable_sort_order ()
3041 get_stripables (sl);
3042 sl.sort (Stripable::Sorter ());
3044 bool change = false;
3045 PresentationInfo::order_t order = 0;
3047 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3048 boost::shared_ptr<Stripable> s (*si);
3049 assert (!s->is_auditioner ()); // XXX remove me
3050 if (s->is_monitor ()) {
3053 if (order != s->presentation_info().order()) {
3054 s->set_presentation_order (order);
3063 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3065 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3067 if (first_new_order == PresentationInfo::max_order) {
3068 /* adding at end, no worries */
3072 /* create a gap in the presentation info to accomodate @param how_many
3076 get_stripables (sl);
3078 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3079 boost::shared_ptr<Stripable> s (*si);
3081 if (s->presentation_info().special (false)) {
3085 if (!s->presentation_info().order_set()) {
3089 if (s->presentation_info().order () >= first_new_order) {
3090 s->set_presentation_order (s->presentation_info().order () + how_many);
3095 /** Caller must not hold process lock
3096 * @param name_template string to use for the start of the name, or "" to use "Audio".
3098 list< boost::shared_ptr<AudioTrack> >
3099 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3100 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3104 uint32_t track_id = 0;
3106 RouteList new_routes;
3107 list<boost::shared_ptr<AudioTrack> > ret;
3109 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3110 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3114 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3115 error << "cannot find name for new audio track" << endmsg;
3119 boost::shared_ptr<AudioTrack> track;
3122 track.reset (new AudioTrack (*this, track_name, mode));
3124 if (track->init ()) {
3128 if (Profile->get_mixbus ()) {
3129 track->set_strict_io (true);
3132 if (ARDOUR::Profile->get_trx ()) {
3133 // TRACKS considers it's not a USE CASE, it's
3134 // a piece of behavior of the session model:
3136 // Gain for a newly created route depends on
3137 // the current output_auto_connect mode:
3139 // 0 for Stereo Out mode
3141 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3142 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3146 BOOST_MARK_TRACK (track);
3149 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3151 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3152 error << string_compose (
3153 _("cannot configure %1 in/%2 out configuration for new audio track"),
3154 input_channels, output_channels)
3159 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3160 error << string_compose (
3161 _("cannot configure %1 in/%2 out configuration for new audio track"),
3162 input_channels, output_channels)
3169 route_group->add (track);
3172 new_routes.push_back (track);
3173 ret.push_back (track);
3176 catch (failed_constructor &err) {
3177 error << _("Session: could not create new audio track.") << endmsg;
3181 catch (AudioEngine::PortRegistrationFailure& pfe) {
3183 error << pfe.what() << endmsg;
3191 if (!new_routes.empty()) {
3192 StateProtector sp (this);
3193 if (Profile->get_trx()) {
3194 add_routes (new_routes, false, false, false, order);
3196 add_routes (new_routes, true, true, false, order);
3203 /** Caller must not hold process lock.
3204 * @param name_template string to use for the start of the name, or "" to use "Bus".
3207 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3208 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3211 uint32_t bus_id = 0;
3215 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3218 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3219 error << "cannot find name for new audio bus" << endmsg;
3224 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3230 if (Profile->get_mixbus ()) {
3231 bus->set_strict_io (true);
3234 BOOST_MARK_ROUTE(bus);
3237 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3239 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3240 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3241 input_channels, output_channels)
3247 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3248 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3249 input_channels, output_channels)
3256 route_group->add (bus);
3259 bus->add_internal_return ();
3260 ret.push_back (bus);
3263 catch (failed_constructor &err) {
3264 error << _("Session: could not create new audio route.") << endmsg;
3268 catch (AudioEngine::PortRegistrationFailure& pfe) {
3269 error << pfe.what() << endmsg;
3279 StateProtector sp (this);
3280 if (Profile->get_trx()) {
3281 add_routes (ret, false, false, false, order);
3282 } else if (flags == PresentationInfo::FoldbackBus) {
3283 add_routes (ret, false, false, true, order); // no autoconnect
3285 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3294 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3295 PlaylistDisposition pd)
3299 if (!tree.read (template_path.c_str())) {
3303 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3307 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3310 uint32_t number = 0;
3311 const uint32_t being_added = how_many;
3312 /* This will prevent the use of any existing XML-provided PBD::ID
3315 Stateful::ForceIDRegeneration force_ids;
3316 IO::disable_connecting ();
3320 /* We're going to modify the node contents a bit so take a
3321 * copy. The node may be re-used when duplicating more than once.
3324 XMLNode node_copy (node);
3325 std::vector<boost::shared_ptr<Playlist> > shared_playlists;
3330 if (!name_base.empty()) {
3332 /* if we're adding more than one routes, force
3333 * all the names of the new routes to be
3334 * numbered, via the final parameter.
3337 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3338 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3344 string const route_name = node_copy.property(X_("name"))->value ();
3346 /* generate a new name by adding a number to the end of the template name */
3347 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3348 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3349 abort(); /*NOTREACHED*/
3353 /* figure out the appropriate playlist setup. The track
3354 * (if the Route we're creating is a track) will find
3358 if (pd == CopyPlaylist) {
3360 PBD::ID playlist_id;
3362 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
3363 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3364 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3365 playlist->reset_shares ();
3366 node_copy.set_property (X_("audio-playlist"), playlist->id());
3369 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
3370 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3371 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3372 playlist->reset_shares ();
3373 node_copy.set_property (X_("midi-playlist"), playlist->id());
3376 } else if (pd == SharePlaylist) {
3377 PBD::ID playlist_id;
3379 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
3380 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3381 shared_playlists.push_back (playlist);
3384 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
3385 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3386 shared_playlists.push_back (playlist);
3389 } else { /* NewPlaylist */
3393 if (node_copy.get_property (X_("audio-playlist"), pid)) {
3394 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::AUDIO, *this, name, false);
3395 node_copy.set_property (X_("audio-playlist"), playlist->id());
3398 if (node_copy.get_property (X_("midi-playlist"), pid)) {
3399 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::MIDI, *this, name, false);
3400 node_copy.set_property (X_("midi-playlist"), playlist->id());
3404 /* Fix up new name in the XML node */
3406 Route::set_name_in_state (node_copy, name);
3408 /* trim bitslots from listen sends so that new ones are used */
3409 XMLNodeList children = node_copy.children ();
3410 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3411 if ((*i)->name() == X_("Processor")) {
3412 /* ForceIDRegeneration does not catch the following */
3413 XMLProperty const * role = (*i)->property (X_("role"));
3414 XMLProperty const * type = (*i)->property (X_("type"));
3415 if (role && role->value() == X_("Aux")) {
3416 /* check if the target bus exists.
3417 * we should not save aux-sends in templates.
3419 XMLProperty const * target = (*i)->property (X_("target"));
3421 (*i)->set_property ("type", "dangling-aux-send");
3424 boost::shared_ptr<Route> r = route_by_id (target->value());
3425 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3426 (*i)->set_property ("type", "dangling-aux-send");
3430 if (role && role->value() == X_("Listen")) {
3431 (*i)->remove_property (X_("bitslot"));
3433 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3434 Delivery::Role xrole;
3435 uint32_t bitslot = 0;
3436 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3437 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3438 (*i)->remove_property (X_("bitslot"));
3439 (*i)->remove_property (X_("name"));
3440 (*i)->set_property ("bitslot", bitslot);
3441 (*i)->set_property ("name", name);
3442 XMLNodeList io_kids = (*i)->children ();
3443 for (XMLNodeList::iterator j = io_kids.begin(); j != io_kids.end(); ++j) {
3444 if ((*j)->name() != X_("IO")) {
3447 (*j)->remove_property (X_("name"));
3448 (*j)->set_property ("name", name);
3451 else if (type && type->value() == X_("intreturn")) {
3452 (*i)->remove_property (X_("bitslot"));
3453 (*i)->set_property ("ignore-bitslot", "1");
3455 else if (type && type->value() == X_("return")) {
3456 // Return::set_state() generates a new one
3457 (*i)->remove_property (X_("bitslot"));
3459 else if (type && type->value() == X_("port")) {
3460 IOProcessor::prepare_for_reset (**i, name);
3465 /* new routes start off unsoloed to avoid issues related to
3466 upstream / downstream buses.
3468 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3470 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3473 error << _("Session: cannot create track/bus from template description") << endmsg;
3477 /* Fix up sharing of playlists with the new Route/Track */
3479 for (vector<boost::shared_ptr<Playlist> >::iterator sp = shared_playlists.begin(); sp != shared_playlists.end(); ++sp) {
3480 (*sp)->share_with (route->id());
3483 if (boost::dynamic_pointer_cast<Track>(route)) {
3484 /* force input/output change signals so that the new diskstream
3485 picks up the configuration of the route. During session
3486 loading this normally happens in a different way.
3489 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3491 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3492 change.after = route->input()->n_ports();
3493 route->input()->changed (change, this);
3494 change.after = route->output()->n_ports();
3495 route->output()->changed (change, this);
3498 ret.push_back (route);
3501 catch (failed_constructor &err) {
3502 error << _("Session: could not create new route from template") << endmsg;
3506 catch (AudioEngine::PortRegistrationFailure& pfe) {
3507 error << pfe.what() << endmsg;
3512 IO::enable_connecting ();
3521 StateProtector sp (this);
3522 if (Profile->get_trx()) {
3523 add_routes (ret, false, false, false, insert_at);
3525 add_routes (ret, true, true, false, insert_at);
3529 IO::enable_connecting ();
3535 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3538 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3539 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3542 error << _("Adding new tracks/busses failed") << endmsg;
3547 update_latency (false);
3548 update_latency (true);
3553 save_state (_current_snapshot_name);
3556 update_route_record_state ();
3558 RouteAdded (new_routes); /* EMIT SIGNAL */
3562 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3564 ChanCount existing_inputs;
3565 ChanCount existing_outputs;
3569 count_existing_track_channels (existing_inputs, existing_outputs);
3572 RCUWriter<RouteList> writer (routes);
3573 boost::shared_ptr<RouteList> r = writer.get_copy ();
3574 n_routes = r->size();
3575 r->insert (r->end(), new_routes.begin(), new_routes.end());
3577 /* if there is no control out and we're not in the middle of loading,
3578 * resort the graph here. if there is a control out, we will resort
3579 * toward the end of this method. if we are in the middle of loading,
3580 * we will resort when done.
3583 if (!_monitor_out && IO::connecting_legal) {
3584 resort_routes_using (r);
3588 /* monitor is not part of the order */
3590 assert (n_routes > 0);
3595 PresentationInfo::ChangeSuspender cs;
3596 ensure_route_presentation_info_gap (order, new_routes.size());
3598 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3600 boost::weak_ptr<Route> wpr (*x);
3601 boost::shared_ptr<Route> r (*x);
3603 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3604 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3605 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3607 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3608 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3609 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3611 if (r->is_master()) {
3615 if (r->is_monitor()) {
3619 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3621 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3622 track_playlist_changed (boost::weak_ptr<Track> (tr));
3623 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3625 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3627 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3628 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3629 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3633 if (!r->presentation_info().special (false)) {
3635 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3637 /* presentation info order may already have been set from XML */
3639 if (!r->presentation_info().order_set()) {
3640 if (order == PresentationInfo::max_order) {
3641 /* just add to the end */
3642 r->set_presentation_order (n_routes + added);
3643 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3645 r->set_presentation_order (order + added);
3646 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3649 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3653 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3654 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3655 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3657 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3659 r->presentation_info().order(),
3660 enum_2_string (r->presentation_info().flags()),
3661 r->presentation_info()));
3665 if (input_auto_connect || output_auto_connect) {
3666 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3667 existing_inputs += r->n_inputs();
3668 existing_outputs += r->n_outputs();
3673 ensure_stripable_sort_order ();
3676 if (_monitor_out && IO::connecting_legal) {
3677 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3679 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3680 if ((*x)->is_monitor()) {
3682 } else if ((*x)->is_master()) {
3685 (*x)->enable_monitor_send ();
3690 reassign_track_numbers ();
3694 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3696 boost::shared_ptr<RouteList> r = routes.reader ();
3697 boost::shared_ptr<Send> s;
3699 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3700 if ((s = (*i)->internal_send_for (dest)) != 0) {
3701 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3707 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3709 boost::shared_ptr<RouteList> r = routes.reader ();
3710 boost::shared_ptr<Send> s;
3712 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3713 if ((s = (*i)->internal_send_for (dest)) != 0) {
3714 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3720 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3722 boost::shared_ptr<RouteList> r = routes.reader ();
3723 boost::shared_ptr<Send> s;
3725 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3726 if ((s = (*i)->internal_send_for (dest)) != 0) {
3727 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3732 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3734 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3736 boost::shared_ptr<RouteList> r = routes.reader ();
3737 boost::shared_ptr<RouteList> t (new RouteList);
3739 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3740 /* no MIDI sends because there are no MIDI busses yet */
3741 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3746 add_internal_sends (dest, p, t);
3750 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3752 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3753 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3758 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3760 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3764 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3766 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3770 if (!dest->internal_return()) {
3771 dest->add_internal_return ();
3774 sender->add_aux_send (dest, before);
3780 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3782 bool mute_changed = false;
3783 bool send_selected = false;
3785 { // RCU Writer scope
3786 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3787 RCUWriter<RouteList> writer (routes);
3788 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3790 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3792 if (_selection->selected (*iter)) {
3793 send_selected = true;
3796 if (*iter == _master_out) {
3800 /* speed up session deletion, don't do the solo dance */
3801 if (!deletion_in_progress ()) {
3802 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3805 if ((*iter)->mute_control()->muted ()) {
3806 mute_changed = true;
3811 /* deleting the master out seems like a dumb
3812 idea, but its more of a UI policy issue
3816 if (*iter == _master_out) {
3817 _master_out = boost::shared_ptr<Route> ();
3820 if (*iter == _monitor_out) {
3821 _monitor_out.reset ();
3824 // We need to disconnect the route's inputs and outputs
3826 (*iter)->input()->disconnect (0);
3827 (*iter)->output()->disconnect (0);
3829 /* if the route had internal sends sending to it, remove them */
3831 if (!deletion_in_progress () && (*iter)->internal_return()) {
3833 boost::shared_ptr<RouteList> r = routes.reader ();
3834 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3835 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3837 (*i)->remove_processor (s);
3842 /* if the monitoring section had a pointer to this route, remove it */
3843 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3844 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3845 ProcessorChangeBlocker pcb (this, false);
3846 (*iter)->remove_aux_or_listen (_monitor_out);
3849 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3850 if (mt && mt->step_editing()) {
3851 if (_step_editors > 0) {
3857 /* writer goes out of scope, forces route list update */
3859 } // end of RCU Writer scope
3862 MuteChanged (); /* EMIT SIGNAL */
3865 update_route_solo_state ();
3866 update_latency_compensation ();
3869 /* Re-sort routes to remove the graph's current references to the one that is
3870 * going away, then flush old references out of the graph.
3871 * Wave Tracks: reconnect routes
3874 #ifdef USE_TRACKS_CODE_FEATURES
3875 reconnect_existing_routes(true, false);
3877 routes.flush (); // maybe unsafe, see below.
3881 if (_process_graph && !deletion_in_progress() && _engine.running()) {
3882 _process_graph->clear_other_chain ();
3885 /* get rid of it from the dead wood collection in the route list manager */
3886 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3890 /* remove these routes from the selection if appropriate, and signal
3891 * the change *before* we call DropReferences for them.
3894 if (send_selected && !deletion_in_progress()) {
3895 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3896 _selection->remove_stripable_by_id ((*iter)->id());
3899 pc.add (Properties::selected);
3900 PresentationInfo::Change (pc);
3903 /* try to cause everyone to drop their references
3904 * and unregister ports from the backend
3907 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3908 (*iter)->drop_references ();
3911 if (deletion_in_progress()) {
3916 pc.add (Properties::order);
3917 PresentationInfo::Change (pc);
3919 /* save the new state of the world */
3921 if (save_state (_current_snapshot_name)) {
3922 save_history (_current_snapshot_name);
3925 update_route_record_state ();
3929 Session::remove_route (boost::shared_ptr<Route> route)
3931 boost::shared_ptr<RouteList> rl (new RouteList);
3932 rl->push_back (route);
3937 Session::route_mute_changed ()
3939 MuteChanged (); /* EMIT SIGNAL */
3944 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3946 boost::shared_ptr<Route> route (wpr.lock());
3952 assert (Config->get_solo_control_is_listen_control());
3954 if (route->solo_control()->soloed_by_self_or_masters()) {
3956 if (Config->get_exclusive_solo()) {
3958 RouteGroup* rg = route->route_group ();
3959 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3961 boost::shared_ptr<RouteList> r = routes.reader ();
3963 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3964 if ((*i) == route) {
3965 /* already changed */
3969 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3970 /* route does not get solo propagated to it */
3974 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3975 /* this route is a part of the same solo group as the route
3976 * that was changed. Changing that route did change or will
3977 * change all group members appropriately, so we can ignore it
3982 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3988 } else if (_listen_cnt > 0) {
3995 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3997 boost::shared_ptr<Route> route (wpr.lock());
4003 bool send_changed = false;
4005 if (route->solo_isolate_control()->solo_isolated()) {
4006 if (_solo_isolated_cnt == 0) {
4007 send_changed = true;
4009 _solo_isolated_cnt++;
4010 } else if (_solo_isolated_cnt > 0) {
4011 _solo_isolated_cnt--;
4012 if (_solo_isolated_cnt == 0) {
4013 send_changed = true;
4018 IsolatedChanged (); /* EMIT SIGNAL */
4023 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
4025 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
4027 boost::shared_ptr<Route> route (wpr.lock());
4033 if (Config->get_solo_control_is_listen_control()) {
4034 route_listen_changed (group_override, wpr);
4038 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()));
4040 if (route->solo_control()->transitioned_into_solo() == 0) {
4041 /* route solo changed by upstream/downstream or clear all solo state; not interesting
4044 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()));
4048 boost::shared_ptr<RouteList> r = routes.reader ();
4049 int32_t delta = route->solo_control()->transitioned_into_solo ();
4051 /* the route may be a member of a group that has shared-solo
4052 * semantics. If so, then all members of that group should follow the
4053 * solo of the changed route. But ... this is optional, controlled by a
4054 * Controllable::GroupControlDisposition.
4056 * The first argument to the signal that this method is connected to is the
4057 * GroupControlDisposition value that was used to change solo.
4059 * If the solo change was done with group semantics (either InverseGroup
4060 * (force the entire group to change even if the group shared solo is
4061 * disabled) or UseGroup (use the group, which may or may not have the
4062 * shared solo property enabled)) then as we propagate the change to
4063 * the entire session we should IGNORE THE GROUP that the changed route
4067 RouteGroup* rg = route->route_group ();
4068 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4070 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4072 if (delta == 1 && Config->get_exclusive_solo()) {
4074 /* new solo: disable all other solos, but not the group if its solo-enabled */
4076 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4078 if ((*i) == route) {
4079 /* already changed */
4083 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4084 /* route does not get solo propagated to it */
4088 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4089 /* this route is a part of the same solo group as the route
4090 * that was changed. Changing that route did change or will
4091 * change all group members appropriately, so we can ignore it
4097 (*i)->solo_control()->set_value (0.0, group_override);
4101 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4103 RouteList uninvolved;
4105 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4107 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4108 bool via_sends_only;
4109 bool in_signal_flow;
4111 if ((*i) == route) {
4112 /* already changed */
4116 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4117 /* route does not get solo propagated to it */
4118 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 excluded from solo because iso = %2 can_solo = %3\n", (*i)->name(), (*i)->solo_isolate_control()->solo_isolated(),
4123 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4124 /* this route is a part of the same solo group as the route
4125 * that was changed. Changing that route did change or will
4126 * change all group members appropriately, so we can ignore it
4132 in_signal_flow = false;
4134 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4136 if ((*i)->feeds (route, &via_sends_only)) {
4137 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4138 if (!via_sends_only) {
4139 if (!route->soloed_by_others_upstream()) {
4140 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4142 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4145 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4147 in_signal_flow = true;
4149 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4152 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4154 if (route->feeds (*i, &via_sends_only)) {
4155 /* propagate solo upstream only if routing other than
4156 sends is involved, but do consider the other route
4157 (*i) to be part of the signal flow even if only
4160 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4164 route->soloed_by_others_downstream(),
4165 route->soloed_by_others_upstream()));
4166 if (!via_sends_only) {
4167 //NB. Triggers Invert Push, which handles soloed by downstream
4168 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4169 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4171 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4173 in_signal_flow = true;
4175 DEBUG_TRACE (DEBUG::Solo, string_compose("\tno feed to %1\n", (*i)->name()) );
4178 if (!in_signal_flow) {
4179 uninvolved.push_back (*i);
4183 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4185 /* now notify that the mute state of the routes not involved in the signal
4186 pathway of the just-solo-changed route may have altered.
4189 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4190 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4191 (*i)->act_on_mute ();
4192 /* Session will emit SoloChanged() after all solo changes are
4193 * complete, which should be used by UIs to update mute status
4199 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4201 /* now figure out if anything that matters is soloed (or is "listening")*/
4203 bool something_soloed = false;
4204 bool something_listening = false;
4205 uint32_t listeners = 0;
4206 uint32_t isolated = 0;
4209 r = routes.reader();
4212 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4213 if ((*i)->can_solo()) {
4214 if (Config->get_solo_control_is_listen_control()) {
4215 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4217 something_listening = true;
4220 (*i)->set_listen (false);
4221 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4222 something_soloed = true;
4227 if ((*i)->solo_isolate_control()->solo_isolated()) {
4232 if (something_soloed != _non_soloed_outs_muted) {
4233 _non_soloed_outs_muted = something_soloed;
4234 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4237 if (something_listening != _listening) {
4238 _listening = something_listening;
4239 SoloActive (_listening);
4242 _listen_cnt = listeners;
4244 if (isolated != _solo_isolated_cnt) {
4245 _solo_isolated_cnt = isolated;
4246 IsolatedChanged (); /* EMIT SIGNAL */
4249 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4250 something_soloed, listeners, isolated));
4253 SoloChanged (); /* EMIT SIGNAL */
4258 Session::muted () const
4260 // TODO consider caching the value on every MuteChanged signal,
4261 // Note that API users may also subscribe to MuteChanged and hence
4262 // this method needs to be called first.
4265 get_stripables (all);
4266 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4267 assert (!(*i)->is_auditioner()); // XXX remove me
4268 if ((*i)->is_monitor()) {
4271 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4272 if (r && !r->active()) {
4275 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4276 if (mc && mc->muted ()) {
4284 std::vector<boost::weak_ptr<AutomationControl> >
4285 Session::cancel_all_mute ()
4288 get_stripables (all);
4289 std::vector<boost::weak_ptr<AutomationControl> > muted;
4290 boost::shared_ptr<ControlList> cl (new ControlList);
4291 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4292 assert (!(*i)->is_auditioner());
4293 if ((*i)->is_monitor()) {
4296 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4297 if (r && !r->active()) {
4300 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4301 if (ac && ac->get_value () > 0) {
4303 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4306 if (!cl->empty ()) {
4307 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4313 Session::get_stripables (StripableList& sl, PresentationInfo::Flag fl) const
4315 boost::shared_ptr<RouteList> r = routes.reader ();
4316 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4317 if ((*it)->presentation_info ().flags () & fl) {
4322 if (fl & PresentationInfo::VCA) {
4323 VCAList v = _vca_manager->vcas ();
4324 sl.insert (sl.end(), v.begin(), v.end());
4329 Session::get_stripables () const
4331 PresentationInfo::Flag fl = PresentationInfo::AllStripables;
4333 Session::get_stripables (rv, fl);
4334 rv.sort (Stripable::Sorter ());
4339 Session::get_routelist (bool mixer_order, PresentationInfo::Flag fl) const
4341 boost::shared_ptr<RouteList> r = routes.reader ();
4343 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4344 if ((*it)->presentation_info ().flags () & fl) {
4348 rv.sort (Stripable::Sorter (mixer_order));
4352 boost::shared_ptr<RouteList>
4353 Session::get_routes_with_internal_returns() const
4355 boost::shared_ptr<RouteList> r = routes.reader ();
4356 boost::shared_ptr<RouteList> rl (new RouteList);
4358 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4359 if ((*i)->internal_return ()) {
4367 Session::io_name_is_legal (const std::string& name) const
4369 boost::shared_ptr<RouteList> r = routes.reader ();
4371 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4372 if (name == reserved->first) {
4373 if (!route_by_name (reserved->first)) {
4374 /* first instance of a reserved name is allowed for some */
4375 return reserved->second;
4377 /* all other instances of a reserved name are not allowed */
4382 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4383 if ((*i)->name() == name) {
4387 if ((*i)->has_io_processor_named (name)) {
4396 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4399 vector<string> connections;
4401 /* if we are passed only a single route and we're not told to turn
4402 * others off, then just do the simple thing.
4405 if (flip_others == false && rl->size() == 1) {
4406 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4408 mt->set_input_active (onoff);
4413 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4415 PortSet& ps ((*rt)->input()->ports());
4417 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4418 p->get_connections (connections);
4421 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4422 routes_using_input_from (*s, rl2);
4425 /* scan all relevant routes to see if others are on or off */
4427 bool others_are_already_on = false;
4429 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4431 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4437 if ((*r) != (*rt)) {
4438 if (mt->input_active()) {
4439 others_are_already_on = true;
4442 /* this one needs changing */
4443 mt->set_input_active (onoff);
4449 /* globally reverse other routes */
4451 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4452 if ((*r) != (*rt)) {
4453 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4455 mt->set_input_active (!others_are_already_on);
4464 Session::routes_using_input_from (const string& str, RouteList& rl)
4466 boost::shared_ptr<RouteList> r = routes.reader();
4468 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4469 if ((*i)->input()->connected_to (str)) {
4475 boost::shared_ptr<Route>
4476 Session::route_by_name (string name) const
4478 boost::shared_ptr<RouteList> r = routes.reader ();
4480 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4481 if ((*i)->name() == name) {
4486 return boost::shared_ptr<Route> ((Route*) 0);
4489 boost::shared_ptr<Route>
4490 Session::route_by_id (PBD::ID id) const
4492 boost::shared_ptr<RouteList> r = routes.reader ();
4494 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4495 if ((*i)->id() == id) {
4500 return boost::shared_ptr<Route> ((Route*) 0);
4504 boost::shared_ptr<Stripable>
4505 Session::stripable_by_id (PBD::ID id) const
4508 get_stripables (sl);
4510 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4511 if ((*s)->id() == id) {
4516 return boost::shared_ptr<Stripable>();
4519 boost::shared_ptr<Processor>
4520 Session::processor_by_id (PBD::ID id) const
4522 boost::shared_ptr<RouteList> r = routes.reader ();
4524 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4525 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4531 return boost::shared_ptr<Processor> ();
4534 boost::shared_ptr<Route>
4535 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4537 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4540 boost::shared_ptr<Stripable>
4541 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4544 PresentationInfo::order_t match_cnt = 0;
4546 get_stripables (sl);
4547 sl.sort (Stripable::Sorter());
4549 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4551 if ((*s)->presentation_info().hidden()) {
4552 /* if the caller didn't explicitly ask for hidden
4553 stripables, ignore hidden ones. This matches
4554 the semantics of the pre-PresentationOrder
4555 "get by RID" logic of Ardour 4.x and earlier.
4557 XXX at some point we should likely reverse
4558 the logic of the flags, because asking for "the
4559 hidden stripables" is not going to be common,
4560 whereas asking for visible ones is normal.
4563 if (! (flags & PresentationInfo::Hidden)) {
4568 if ((*s)->presentation_info().flag_match (flags)) {
4569 if (match_cnt++ == n) {
4575 /* there is no nth stripable that matches the given flags */
4576 return boost::shared_ptr<Stripable>();
4579 boost::shared_ptr<Route>
4580 Session::route_by_selected_count (uint32_t id) const
4582 RouteList r (*(routes.reader ()));
4583 r.sort (Stripable::Sorter());
4585 RouteList::iterator i;
4587 for (i = r.begin(); i != r.end(); ++i) {
4588 if ((*i)->is_selected()) {
4596 return boost::shared_ptr<Route> ();
4600 Session::reassign_track_numbers ()
4604 RouteList r (*(routes.reader ()));
4605 r.sort (Stripable::Sorter());
4607 StateProtector sp (this);
4609 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4610 assert (!(*i)->is_auditioner());
4611 if (boost::dynamic_pointer_cast<Track> (*i)) {
4612 (*i)->set_track_number(++tn);
4614 else if (!(*i)->is_master() && !(*i)->is_monitor()) {
4615 (*i)->set_track_number(--bn);
4618 const uint32_t decimals = ceilf (log10f (tn + 1));
4619 const bool decimals_changed = _track_number_decimals != decimals;
4620 _track_number_decimals = decimals;
4622 if (decimals_changed && config.get_track_name_number ()) {
4623 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4624 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4626 t->resync_track_name();
4629 // trigger GUI re-layout
4630 config.ParameterChanged("track-name-number");
4634 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4635 boost::shared_ptr<RouteList> rl = routes.reader ();
4636 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4637 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4645 Session::playlist_region_added (boost::weak_ptr<Region> w)
4647 boost::shared_ptr<Region> r = w.lock ();
4652 /* These are the operations that are currently in progress... */
4653 list<GQuark> curr = _current_trans_quarks;
4656 /* ...and these are the operations during which we want to update
4657 the session range location markers.
4660 ops.push_back (Operations::capture);
4661 ops.push_back (Operations::paste);
4662 ops.push_back (Operations::duplicate_region);
4663 ops.push_back (Operations::insert_file);
4664 ops.push_back (Operations::insert_region);
4665 ops.push_back (Operations::drag_region_brush);
4666 ops.push_back (Operations::region_drag);
4667 ops.push_back (Operations::selection_grab);
4668 ops.push_back (Operations::region_fill);
4669 ops.push_back (Operations::fill_selection);
4670 ops.push_back (Operations::create_region);
4671 ops.push_back (Operations::region_copy);
4672 ops.push_back (Operations::fixed_time_region_copy);
4675 /* See if any of the current operations match the ones that we want */
4677 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4679 /* If so, update the session range markers */
4681 maybe_update_session_range (r->position (), r->last_sample ());
4685 /** Update the session range markers if a is before the current start or
4686 * b is after the current end.
4689 Session::maybe_update_session_range (samplepos_t a, samplepos_t b)
4695 samplepos_t session_end_marker_shift_samples = session_end_shift * _nominal_sample_rate;
4697 if (_session_range_location == 0) {
4699 set_session_range_location (a, b + session_end_marker_shift_samples);
4703 if (_session_range_is_free && (a < _session_range_location->start())) {
4704 _session_range_location->set_start (a);
4707 if (_session_range_is_free && (b > _session_range_location->end())) {
4708 _session_range_location->set_end (b);
4714 Session::set_session_range_is_free (bool yn)
4716 _session_range_is_free = yn;
4720 Session::playlist_ranges_moved (list<Evoral::RangeMove<samplepos_t> > const & ranges)
4722 for (list<Evoral::RangeMove<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4723 maybe_update_session_range (i->to, i->to + i->length);
4728 Session::playlist_regions_extended (list<Evoral::Range<samplepos_t> > const & ranges)
4730 for (list<Evoral::Range<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4731 maybe_update_session_range (i->from, i->to);
4735 /* Region management */
4737 boost::shared_ptr<Region>
4738 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4740 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4741 RegionFactory::RegionMap::const_iterator i;
4742 boost::shared_ptr<Region> region;
4744 Glib::Threads::Mutex::Lock lm (region_lock);
4746 for (i = regions.begin(); i != regions.end(); ++i) {
4750 if (region->whole_file()) {
4752 if (child->source_equivalent (region)) {
4758 return boost::shared_ptr<Region> ();
4762 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4764 set<boost::shared_ptr<Region> > relevant_regions;
4766 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4767 RegionFactory::get_regions_using_source (*s, relevant_regions);
4770 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4771 set<boost::shared_ptr<Region> >::iterator tmp;
4776 _playlists->destroy_region (*r);
4777 RegionFactory::map_remove (*r);
4779 (*r)->drop_sources ();
4780 (*r)->drop_references ();
4782 relevant_regions.erase (r);
4787 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4790 Glib::Threads::Mutex::Lock ls (source_lock);
4791 /* remove from the main source list */
4792 sources.erase ((*s)->id());
4795 (*s)->mark_for_remove ();
4796 (*s)->drop_references ();
4805 Session::remove_last_capture ()
4807 list<boost::shared_ptr<Source> > srcs;
4809 boost::shared_ptr<RouteList> rl = routes.reader ();
4810 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4811 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4816 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4819 srcs.insert (srcs.end(), l.begin(), l.end());
4824 destroy_sources (srcs);
4826 save_state (_current_snapshot_name);
4831 /* Source Management */
4834 Session::add_source (boost::shared_ptr<Source> source)
4836 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4837 pair<SourceMap::iterator,bool> result;
4839 entry.first = source->id();
4840 entry.second = source;
4843 Glib::Threads::Mutex::Lock lm (source_lock);
4844 result = sources.insert (entry);
4847 if (result.second) {
4849 /* yay, new source */
4851 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4854 if (!fs->within_session()) {
4855 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4861 boost::shared_ptr<AudioFileSource> afs;
4863 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4864 if (Config->get_auto_analyse_audio()) {
4865 Analyser::queue_source_for_analysis (source, false);
4869 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4874 Session::remove_source (boost::weak_ptr<Source> src)
4876 if (deletion_in_progress ()) {
4880 SourceMap::iterator i;
4881 boost::shared_ptr<Source> source = src.lock();
4888 Glib::Threads::Mutex::Lock lm (source_lock);
4890 if ((i = sources.find (source->id())) != sources.end()) {
4895 if (!in_cleanup () && !loading ()) {
4897 /* save state so we don't end up with a session file
4898 * referring to non-existent sources.
4901 save_state (_current_snapshot_name);
4905 boost::shared_ptr<Source>
4906 Session::source_by_id (const PBD::ID& id)
4908 Glib::Threads::Mutex::Lock lm (source_lock);
4909 SourceMap::iterator i;
4910 boost::shared_ptr<Source> source;
4912 if ((i = sources.find (id)) != sources.end()) {
4919 boost::shared_ptr<AudioFileSource>
4920 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4922 /* Restricted to audio files because only audio sources have channel
4926 Glib::Threads::Mutex::Lock lm (source_lock);
4928 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4929 boost::shared_ptr<AudioFileSource> afs
4930 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4932 if (afs && afs->path() == path && chn == afs->channel()) {
4937 return boost::shared_ptr<AudioFileSource>();
4940 boost::shared_ptr<MidiSource>
4941 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4943 /* Restricted to MIDI files because audio sources require a channel
4944 for unique identification, in addition to a path.
4947 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4948 if (need_source_lock) {
4952 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4953 boost::shared_ptr<MidiSource> ms
4954 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4955 boost::shared_ptr<FileSource> fs
4956 = boost::dynamic_pointer_cast<FileSource>(s->second);
4958 if (ms && fs && fs->path() == path) {
4963 return boost::shared_ptr<MidiSource>();
4967 Session::count_sources_by_origin (const string& path)
4970 Glib::Threads::Mutex::Lock lm (source_lock);
4972 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4973 boost::shared_ptr<FileSource> fs
4974 = boost::dynamic_pointer_cast<FileSource>(i->second);
4976 if (fs && fs->origin() == path) {
4985 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4987 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4988 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4990 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4995 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4997 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4999 if (Glib::path_is_absolute (filepath)) {
5001 /* rip the session dir from the audiofile source */
5003 string session_path;
5004 bool in_another_session = true;
5006 if (filepath.find (interchange_dir_string) != string::npos) {
5008 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
5009 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
5010 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
5011 session_path = Glib::path_get_dirname (session_path); /* now has session path */
5013 /* see if it is within our session */
5015 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5016 if (i->path == session_path) {
5017 in_another_session = false;
5022 in_another_session = false;
5026 if (in_another_session) {
5027 SessionDirectory sd (session_path);
5028 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
5032 /* 1) if file belongs to this session
5033 * it may be a relative path (interchange/...)
5034 * or just basename (session_state, remove source)
5035 * -> just use the basename
5037 std::string filename = Glib::path_get_basename (filepath);
5040 /* 2) if the file is outside our session dir:
5041 * (imported but not copied) add the path for check-summming */
5043 path = Glib::path_get_dirname (filepath);
5046 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
5050 Session::new_audio_source_path_for_embedded (const std::string& path)
5054 * we know that the filename is already unique because it exists
5055 * out in the filesystem.
5057 * However, when we bring it into the session, we could get a
5060 * Eg. two embedded files:
5065 * When merged into session, these collide.
5067 * There will not be a conflict with in-memory sources
5068 * because when the source was created we already picked
5069 * a unique name for it.
5071 * This collision is not likely to be common, but we have to guard
5072 * against it. So, if there is a collision, take the md5 hash of the
5073 * the path, and use that as the filename instead.
5076 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5077 string base = Glib::path_get_basename (path);
5078 string newpath = Glib::build_filename (sdir.sound_path(), base);
5080 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5084 md5.digestString (path.c_str());
5085 md5.writeToString ();
5086 base = md5.digestChars;
5088 string ext = get_suffix (path);
5095 newpath = Glib::build_filename (sdir.sound_path(), base);
5097 /* if this collides, we're screwed */
5099 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5100 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5109 /** Return true if there are no audio file sources that use @param name as
5110 * the filename component of their path.
5112 * Return false otherwise.
5114 * This method MUST ONLY be used to check in-session, mono files since it
5115 * hard-codes the channel of the audio file source we are looking for as zero.
5117 * If/when Ardour supports native files in non-mono formats, the logic here
5118 * will need to be revisited.
5121 Session::audio_source_name_is_unique (const string& name)
5123 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5124 vector<space_and_path>::iterator i;
5125 uint32_t existing = 0;
5127 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5129 /* note that we search *without* the extension so that
5130 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5131 in the event that this new name is required for
5132 a file format change.
5135 const string spath = *i;
5137 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5142 /* it is possible that we have the path already
5143 * assigned to a source that has not yet been written
5144 * (ie. the write source for a diskstream). we have to
5145 * check this in order to make sure that our candidate
5146 * path isn't used again, because that can lead to
5147 * two Sources point to the same file with different
5148 * notions of their removability.
5152 string possible_path = Glib::build_filename (spath, name);
5154 if (audio_source_by_path_and_channel (possible_path, 0)) {
5160 return (existing == 0);
5164 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)
5167 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5169 if (Profile->get_trx() && destructive) {
5171 sstr << setfill ('0') << setw (4) << cnt;
5172 sstr << legalized_base;
5174 sstr << legalized_base;
5176 if (take_required || related_exists) {
5188 } else if (nchan > 2) {
5193 /* XXX what? more than 26 channels! */
5204 /** Return a unique name based on \a base for a new internal audio source */
5206 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5209 string possible_name;
5210 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5212 bool some_related_source_name_exists = false;
5214 legalized = legalize_for_path (base);
5216 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5218 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5220 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5222 if (audio_source_name_is_unique (possible_name)) {
5226 some_related_source_name_exists = true;
5229 error << string_compose(
5230 _("There are already %1 recordings for %2, which I consider too many."),
5231 limit, base) << endmsg;
5233 throw failed_constructor();
5237 /* We've established that the new name does not exist in any session
5238 * directory, so now find out which one we should use for this new
5242 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5244 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5249 /** Return a unique name based on `base` for a new internal MIDI source */
5251 Session::new_midi_source_path (const string& base, bool need_lock)
5253 string possible_path;
5254 string possible_name;
5256 possible_name = legalize_for_path (base);
5258 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5259 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5261 /* - the main session folder is the first in the vector.
5262 * - after checking all locations for file-name uniqueness,
5263 * we keep the one from the last iteration as new file name
5264 * - midi files are small and should just be kept in the main session-folder
5266 * -> reverse the array, check main session folder last and use that as location
5269 std::reverse(sdirs.begin(), sdirs.end());
5272 possible_name = bump_name_once (possible_name, '-');
5274 vector<space_and_path>::iterator i;
5275 uint32_t existing = 0;
5277 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5279 possible_path = Glib::build_filename (*i, possible_name + ".mid");
5281 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5285 if (midi_source_by_path (possible_path, need_lock)) {
5290 if (possible_path.size () >= PATH_MAX) {
5291 error << string_compose(
5292 _("There are already many recordings for %1, resulting in a too long file-path %2."),
5293 base, possible_path) << endmsg;
5298 if (existing == 0) {
5303 /* No need to "find best location" for software/app-based RAID, because
5304 MIDI is so small that we always put it in the same place.
5307 return possible_path;
5311 /** Create a new within-session audio source */
5312 boost::shared_ptr<AudioFileSource>
5313 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5315 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5317 if (!path.empty()) {
5318 return boost::dynamic_pointer_cast<AudioFileSource> (
5319 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, sample_rate(), true, true));
5321 throw failed_constructor ();
5325 /** Create a new within-session MIDI source */
5326 boost::shared_ptr<MidiSource>
5327 Session::create_midi_source_for_session (string const & basic_name)
5329 const string path = new_midi_source_path (basic_name);
5331 if (!path.empty()) {
5332 return boost::dynamic_pointer_cast<SMFSource> (
5333 SourceFactory::createWritable (
5334 DataType::MIDI, *this, path, false, sample_rate()));
5336 throw failed_constructor ();
5340 /** Create a new within-session MIDI source */
5341 boost::shared_ptr<MidiSource>
5342 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5344 /* the caller passes in the track the source will be used in,
5345 so that we can keep the numbering sane.
5347 Rationale: a track with the name "Foo" that has had N
5348 captures carried out so far will ALREADY have a write source
5349 named "Foo-N+1.mid" waiting to be used for the next capture.
5351 If we call new_midi_source_name() we will get "Foo-N+2". But
5352 there is no region corresponding to "Foo-N+1", so when
5353 "Foo-N+2" appears in the track, the gap presents the user
5354 with odd behaviour - why did it skip past Foo-N+1?
5356 We could explain this to the user in some odd way, but
5357 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5360 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5363 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5365 std::string name = track->steal_write_source_name ();
5368 return boost::shared_ptr<MidiSource>();
5371 /* MIDI files are small, just put them in the first location of the
5372 session source search path.
5375 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5377 return boost::dynamic_pointer_cast<SMFSource> (
5378 SourceFactory::createWritable (
5379 DataType::MIDI, *this, path, false, sample_rate()));
5384 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5386 if (playlist->hidden()) {
5390 _playlists->add (playlist);
5393 playlist->release();
5400 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5402 if (deletion_in_progress ()) {
5406 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5412 _playlists->remove (playlist);
5418 Session::set_audition (boost::shared_ptr<Region> r)
5420 pending_audition_region = r;
5421 add_post_transport_work (PostTransportAudition);
5422 _butler->schedule_transport_work ();
5426 Session::audition_playlist ()
5428 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5429 ev->region.reset ();
5435 Session::register_lua_function (
5436 const std::string& name,
5437 const std::string& script,
5438 const LuaScriptParamList& args
5441 Glib::Threads::Mutex::Lock lm (lua_lock);
5443 lua_State* L = lua.getState();
5445 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5446 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5447 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5448 if ((*i)->optional && !(*i)->is_set) { continue; }
5449 tbl_arg[(*i)->name] = (*i)->value;
5451 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5454 LuaScriptsChanged (); /* EMIT SIGNAL */
5459 Session::unregister_lua_function (const std::string& name)
5461 Glib::Threads::Mutex::Lock lm (lua_lock);
5462 (*_lua_del)(name); // throws luabridge::LuaException
5463 lua.collect_garbage ();
5466 LuaScriptsChanged (); /* EMIT SIGNAL */
5470 std::vector<std::string>
5471 Session::registered_lua_functions ()
5473 Glib::Threads::Mutex::Lock lm (lua_lock);
5474 std::vector<std::string> rv;
5477 luabridge::LuaRef list ((*_lua_list)());
5478 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5479 if (!i.key ().isString ()) { assert(0); continue; }
5480 rv.push_back (i.key ().cast<std::string> ());
5487 static void _lua_print (std::string s) {
5488 std::cout << "SessionLua: " << s << "\n";
5493 Session::try_run_lua (pframes_t nframes)
5495 if (_n_lua_scripts == 0) return;
5496 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5498 try { (*_lua_run)(nframes); } catch (...) { }
5499 lua.collect_garbage_step ();
5504 Session::setup_lua ()
5507 lua.Print.connect (&_lua_print);
5511 "function ArdourSession ()"
5512 " local self = { scripts = {}, instances = {} }"
5514 " local remove = function (n)"
5515 " self.scripts[n] = nil"
5516 " self.instances[n] = nil"
5517 " Session:scripts_changed()" // call back
5520 " local addinternal = function (n, f, a)"
5521 " assert(type(n) == 'string', 'function-name must be string')"
5522 " assert(type(f) == 'function', 'Given script is a not a function')"
5523 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5524 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5525 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5526 " local env = { print = print, tostring = tostring, assert = assert, ipairs = ipairs, error = error, select = select, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall, bit32=bit32, Session = Session, PBD = PBD, Timecode = Timecode, Evoral = Evoral, C = C, ARDOUR = ARDOUR }"
5527 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5528 " Session:scripts_changed()" // call back
5531 " local add = function (n, b, a)"
5532 " assert(type(b) == 'string', 'ByteCode must be string')"
5533 " load (b)()" // assigns f
5534 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5535 " addinternal (n, load(f), a)"
5538 " local run = function (...)"
5539 " for n, s in pairs (self.instances) do"
5540 " local status, err = pcall (s, ...)"
5541 " if not status then"
5542 " print ('fn \"'.. n .. '\": ', err)"
5549 " local cleanup = function ()"
5550 " self.scripts = nil"
5551 " self.instances = nil"
5554 " local list = function ()"
5556 " for n, _ in pairs (self.scripts) do"
5562 " local function basic_serialize (o)"
5563 " if type(o) == \"number\" then"
5564 " return tostring(o)"
5566 " return string.format(\"%q\", o)"
5570 " local function serialize (name, value)"
5571 " local rv = name .. ' = '"
5573 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5574 " return rv .. basic_serialize(value) .. ' '"
5575 " elseif type(value) == \"table\" then"
5577 " for k,v in pairs(value) do"
5578 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5579 " rv = rv .. serialize(fieldname, v) .. ' '"
5580 " collectgarbage()" // string concatenation allocates a new string :(
5583 " elseif type(value) == \"function\" then"
5584 " return rv .. string.format(\"%q\", string.dump(value, true))"
5586 " error('cannot save a ' .. type(value))"
5591 " local save = function ()"
5592 " return (serialize('scripts', self.scripts))"
5595 " local restore = function (state)"
5596 " self.scripts = {}"
5598 " for n, s in pairs (scripts) do"
5599 " addinternal (n, load(s['f']), s['a'])"
5603 " return { run = run, add = add, remove = remove,"
5604 " list = list, restore = restore, save = save, cleanup = cleanup}"
5607 " sess = ArdourSession ()"
5608 " ArdourSession = nil"
5610 "function ardour () end"
5613 lua_State* L = lua.getState();
5616 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5617 lua.do_command ("sess = nil"); // hide it.
5618 lua.do_command ("collectgarbage()");
5620 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5621 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5622 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5623 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5624 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5625 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5626 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5627 } catch (luabridge::LuaException const& e) {
5628 fatal << string_compose (_("programming error: %1"),
5629 std::string ("Failed to setup session Lua interpreter") + e.what ())
5631 abort(); /*NOTREACHED*/
5633 fatal << string_compose (_("programming error: %1"),
5634 X_("Failed to setup session Lua interpreter"))
5636 abort(); /*NOTREACHED*/
5640 LuaBindings::stddef (L);
5641 LuaBindings::common (L);
5642 LuaBindings::dsp (L);
5644 luabridge::push <Session *> (L, this);
5645 lua_setglobal (L, "Session");
5649 Session::scripts_changed ()
5651 assert (!lua_lock.trylock()); // must hold lua_lock
5654 luabridge::LuaRef list ((*_lua_list)());
5656 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5657 if (!i.key ().isString ()) { assert(0); continue; }
5660 _n_lua_scripts = cnt;
5661 } catch (luabridge::LuaException const& e) {
5662 fatal << string_compose (_("programming error: %1"),
5663 std::string ("Indexing Lua Session Scripts failed.") + e.what ())
5665 abort(); /*NOTREACHED*/
5667 fatal << string_compose (_("programming error: %1"),
5668 X_("Indexing Lua Session Scripts failed."))
5670 abort(); /*NOTREACHED*/
5675 Session::non_realtime_set_audition ()
5677 assert (pending_audition_region);
5678 auditioner->audition_region (pending_audition_region);
5679 pending_audition_region.reset ();
5680 AuditionActive (true); /* EMIT SIGNAL */
5684 Session::audition_region (boost::shared_ptr<Region> r)
5686 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5692 Session::cancel_audition ()
5697 if (auditioner->auditioning()) {
5698 auditioner->cancel_audition ();
5699 AuditionActive (false); /* EMIT SIGNAL */
5704 Session::is_auditioning () const
5706 /* can be called before we have an auditioner object */
5708 return auditioner->auditioning();
5715 Session::graph_reordered ()
5717 /* don't do this stuff if we are setting up connections
5718 from a set_state() call or creating new tracks. Ditto for deletion.
5721 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5727 /* force all diskstreams to update their capture offset values to
5728 * reflect any changes in latencies within the graph.
5730 update_route_latency (false, true);
5733 /** @return Number of samples that there is disk space available to write,
5736 boost::optional<samplecnt_t>
5737 Session::available_capture_duration ()
5739 Glib::Threads::Mutex::Lock lm (space_lock);
5741 if (_total_free_4k_blocks_uncertain) {
5742 return boost::optional<samplecnt_t> ();
5745 float sample_bytes_on_disk = 4.0; // keep gcc happy
5747 switch (config.get_native_file_data_format()) {
5749 sample_bytes_on_disk = 4.0;
5753 sample_bytes_on_disk = 3.0;
5757 sample_bytes_on_disk = 2.0;
5761 /* impossible, but keep some gcc versions happy */
5762 fatal << string_compose (_("programming error: %1"),
5763 X_("illegal native file data format"))
5765 abort(); /*NOTREACHED*/
5768 double scale = 4096.0 / sample_bytes_on_disk;
5770 if (_total_free_4k_blocks * scale > (double) max_samplecnt) {
5771 return max_samplecnt;
5774 return (samplecnt_t) floor (_total_free_4k_blocks * scale);
5778 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5781 RCUWriter<BundleList> writer (_bundles);
5782 boost::shared_ptr<BundleList> b = writer.get_copy ();
5783 b->push_back (bundle);
5787 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5794 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5796 bool removed = false;
5799 RCUWriter<BundleList> writer (_bundles);
5800 boost::shared_ptr<BundleList> b = writer.get_copy ();
5801 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5803 if (i != b->end()) {
5810 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5816 boost::shared_ptr<Bundle>
5817 Session::bundle_by_name (string name) const
5819 boost::shared_ptr<BundleList> b = _bundles.reader ();
5821 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5822 if ((*i)->name() == name) {
5827 return boost::shared_ptr<Bundle> ();
5831 Session::tempo_map_changed (const PropertyChange&)
5835 _playlists->update_after_tempo_map_change ();
5837 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5843 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5845 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5846 (*i)->recompute_samples_from_beat ();
5850 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5851 * the given count with the current block size.
5854 Session::ensure_buffers (ChanCount howmany)
5856 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5860 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5862 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5863 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5868 Session::next_insert_id ()
5870 /* this doesn't really loop forever. just think about it */
5873 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5874 if (!insert_bitset[n]) {
5875 insert_bitset[n] = true;
5881 /* none available, so resize and try again */
5883 insert_bitset.resize (insert_bitset.size() + 16, false);
5888 Session::next_send_id ()
5890 /* this doesn't really loop forever. just think about it */
5893 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5894 if (!send_bitset[n]) {
5895 send_bitset[n] = true;
5901 /* none available, so resize and try again */
5903 send_bitset.resize (send_bitset.size() + 16, false);
5908 Session::next_aux_send_id ()
5910 /* this doesn't really loop forever. just think about it */
5913 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5914 if (!aux_send_bitset[n]) {
5915 aux_send_bitset[n] = true;
5921 /* none available, so resize and try again */
5923 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5928 Session::next_return_id ()
5930 /* this doesn't really loop forever. just think about it */
5933 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5934 if (!return_bitset[n]) {
5935 return_bitset[n] = true;
5941 /* none available, so resize and try again */
5943 return_bitset.resize (return_bitset.size() + 16, false);
5948 Session::mark_send_id (uint32_t id)
5950 if (id >= send_bitset.size()) {
5951 send_bitset.resize (id+16, false);
5953 if (send_bitset[id]) {
5954 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5956 send_bitset[id] = true;
5960 Session::mark_aux_send_id (uint32_t id)
5962 if (id >= aux_send_bitset.size()) {
5963 aux_send_bitset.resize (id+16, false);
5965 if (aux_send_bitset[id]) {
5966 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5968 aux_send_bitset[id] = true;
5972 Session::mark_return_id (uint32_t id)
5974 if (id >= return_bitset.size()) {
5975 return_bitset.resize (id+16, false);
5977 if (return_bitset[id]) {
5978 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5980 return_bitset[id] = true;
5984 Session::mark_insert_id (uint32_t id)
5986 if (id >= insert_bitset.size()) {
5987 insert_bitset.resize (id+16, false);
5989 if (insert_bitset[id]) {
5990 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5992 insert_bitset[id] = true;
5996 Session::unmark_send_id (uint32_t id)
5998 if (id < send_bitset.size()) {
5999 send_bitset[id] = false;
6004 Session::unmark_aux_send_id (uint32_t id)
6006 if (id < aux_send_bitset.size()) {
6007 aux_send_bitset[id] = false;
6012 Session::unmark_return_id (uint32_t id)
6014 if (deletion_in_progress ()) {
6017 if (id < return_bitset.size()) {
6018 return_bitset[id] = false;
6023 Session::unmark_insert_id (uint32_t id)
6025 if (id < insert_bitset.size()) {
6026 insert_bitset[id] = false;
6031 Session::reset_native_file_format ()
6033 boost::shared_ptr<RouteList> rl = routes.reader ();
6035 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6036 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6038 /* don't save state as we do this, there's no point */
6039 _state_of_the_state = StateOfTheState (_state_of_the_state | InCleanup);
6040 tr->reset_write_sources (false);
6041 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
6047 Session::route_name_unique (string n) const
6049 boost::shared_ptr<RouteList> r = routes.reader ();
6051 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6052 if ((*i)->name() == n) {
6061 Session::route_name_internal (string n) const
6063 if (auditioner && auditioner->name() == n) {
6067 if (_click_io && _click_io->name() == n) {
6075 Session::freeze_all (InterThreadInfo& itt)
6077 boost::shared_ptr<RouteList> r = routes.reader ();
6079 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6081 boost::shared_ptr<Track> t;
6083 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6084 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6094 boost::shared_ptr<Region>
6095 Session::write_one_track (Track& track, samplepos_t start, samplepos_t end,
6096 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6097 InterThreadInfo& itt,
6098 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6099 bool for_export, bool for_freeze)
6101 boost::shared_ptr<Region> result;
6102 boost::shared_ptr<Playlist> playlist;
6103 boost::shared_ptr<Source> source;
6104 ChanCount diskstream_channels (track.n_channels());
6105 samplepos_t position;
6106 samplecnt_t this_chunk;
6108 samplepos_t latency_skip;
6110 samplepos_t len = end - start;
6111 bool need_block_size_reset = false;
6112 ChanCount const max_proc = track.max_processor_streams ();
6113 string legal_playlist_name;
6114 string possible_path;
6116 DataType data_type = track.data_type();
6119 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
6120 end, start) << endmsg;
6124 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
6125 include_endpoint, for_export, for_freeze);
6127 if (data_type == DataType::MIDI && endpoint && !for_export && !for_freeze && diskstream_channels.n(DataType::AUDIO) > 0) {
6128 data_type = DataType::AUDIO;
6131 if (diskstream_channels.n(data_type) < 1) {
6132 error << _("Cannot write a range with no data.") << endmsg;
6136 // block all process callback handling
6138 block_processing ();
6141 // synchronize with AudioEngine::process_callback()
6142 // make sure processing is not currently running
6143 // and processing_blocked() is honored before
6144 // acquiring thread buffers
6145 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6148 _bounce_processing_active = true;
6150 /* call tree *MUST* hold route_lock */
6152 if ((playlist = track.playlist()) == 0) {
6156 legal_playlist_name = legalize_for_path (playlist->name());
6158 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(data_type); ++chan_n) {
6160 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6161 string path = ((data_type == DataType::AUDIO)
6162 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6163 : new_midi_source_path (legal_playlist_name));
6170 source = SourceFactory::createWritable (data_type, *this, path, false, sample_rate());
6173 catch (failed_constructor& err) {
6174 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6178 srcs.push_back (source);
6181 /* tell redirects that care that we are about to use a much larger
6182 * blocksize. this will flush all plugins too, so that they are ready
6183 * to be used for this process.
6186 need_block_size_reset = true;
6187 track.set_block_size (bounce_chunk_size);
6188 _engine.main_thread()->get_buffers ();
6192 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6194 /* create a set of reasonably-sized buffers */
6195 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6196 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6198 buffers.set_count (max_proc);
6200 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6201 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6202 boost::shared_ptr<MidiSource> ms;
6204 afs->prepare_for_peakfile_writes ();
6205 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6206 Source::Lock lock(ms->mutex());
6207 ms->mark_streaming_write_started(lock);
6211 while (to_do && !itt.cancel) {
6213 this_chunk = min (to_do, bounce_chunk_size);
6215 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6219 start += this_chunk;
6220 to_do -= this_chunk;
6221 itt.progress = (float) (1.0 - ((double) to_do / len));
6223 if (latency_skip >= bounce_chunk_size) {
6224 latency_skip -= bounce_chunk_size;
6228 const samplecnt_t current_chunk = this_chunk - latency_skip;
6231 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6232 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6233 boost::shared_ptr<MidiSource> ms;
6236 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6239 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6240 Source::Lock lock(ms->mutex());
6242 const MidiBuffer& buf = buffers.get_midi(0);
6243 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6244 Evoral::Event<samplepos_t> ev = *i;
6245 if (!endpoint || for_export) {
6246 ev.set_time(ev.time() - position);
6248 ms->append_event_samples(lock, ev, ms->timeline_position());
6255 /* post-roll, pick up delayed processor output */
6256 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6258 while (latency_skip && !itt.cancel) {
6259 this_chunk = min (latency_skip, bounce_chunk_size);
6260 latency_skip -= this_chunk;
6262 buffers.silence (this_chunk, 0);
6263 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6266 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6267 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6270 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6282 xnow = localtime (&now);
6284 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6285 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6286 boost::shared_ptr<MidiSource> ms;
6289 afs->update_header (position, *xnow, now);
6290 afs->flush_header ();
6291 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6292 Source::Lock lock(ms->mutex());
6293 ms->mark_streaming_write_completed(lock);
6297 /* construct a region to represent the bounced material */
6301 plist.add (Properties::start, 0);
6302 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6303 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6305 result = RegionFactory::create (srcs, plist);
6311 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6312 (*src)->mark_for_remove ();
6313 (*src)->drop_references ();
6317 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6318 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6321 afs->done_with_peakfile_writes ();
6325 _bounce_processing_active = false;
6327 if (need_block_size_reset) {
6328 _engine.main_thread()->drop_buffers ();
6329 track.set_block_size (get_block_size());
6332 unblock_processing ();
6338 Session::gain_automation_buffer() const
6340 return ProcessThread::gain_automation_buffer ();
6344 Session::trim_automation_buffer() const
6346 return ProcessThread::trim_automation_buffer ();
6350 Session::send_gain_automation_buffer() const
6352 return ProcessThread::send_gain_automation_buffer ();
6356 Session::scratch_automation_buffer() const
6358 return ProcessThread::scratch_automation_buffer ();
6362 Session::pan_automation_buffer() const
6364 return ProcessThread::pan_automation_buffer ();
6368 Session::get_silent_buffers (ChanCount count)
6370 return ProcessThread::get_silent_buffers (count);
6374 Session::get_scratch_buffers (ChanCount count, bool silence)
6376 return ProcessThread::get_scratch_buffers (count, silence);
6380 Session::get_noinplace_buffers (ChanCount count)
6382 return ProcessThread::get_noinplace_buffers (count);
6386 Session::get_route_buffers (ChanCount count, bool silence)
6388 return ProcessThread::get_route_buffers (count, silence);
6393 Session::get_mix_buffers (ChanCount count)
6395 return ProcessThread::get_mix_buffers (count);
6399 Session::ntracks () const
6402 boost::shared_ptr<RouteList> r = routes.reader ();
6404 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6405 if (boost::dynamic_pointer_cast<Track> (*i)) {
6414 Session::nbusses () const
6417 boost::shared_ptr<RouteList> r = routes.reader ();
6419 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6420 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6429 Session::nstripables (bool with_monitor) const
6431 uint32_t rv = routes.reader()->size ();
6432 rv += _vca_manager->vcas ().size ();
6446 Session::add_automation_list(AutomationList *al)
6448 automation_lists[al->id()] = al;
6451 /** @return true if there is at least one record-enabled track, otherwise false */
6453 Session::have_rec_enabled_track () const
6455 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6459 Session::have_rec_disabled_track () const
6461 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6464 /** Update the state of our rec-enabled tracks flag */
6466 Session::update_route_record_state ()
6468 boost::shared_ptr<RouteList> rl = routes.reader ();
6469 RouteList::iterator i = rl->begin();
6470 while (i != rl->end ()) {
6472 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6473 if (tr && tr->rec_enable_control()->get_value()) {
6480 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6482 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6484 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6485 RecordStateChanged (); /* EMIT SIGNAL */
6488 for (i = rl->begin(); i != rl->end (); ++i) {
6489 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6490 if (tr && !tr->rec_enable_control()->get_value()) {
6495 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6497 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6499 if (record_status() == Recording && record_arm_state_changed ) {
6500 RecordArmStateChanged ();
6506 Session::listen_position_changed ()
6509 /* skip duing session restore (already taken care of) */
6512 ProcessorChangeBlocker pcb (this);
6513 boost::shared_ptr<RouteList> r = routes.reader ();
6514 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6515 (*i)->listen_position_changed ();
6520 Session::solo_control_mode_changed ()
6522 if (soloing() || listening()) {
6524 /* We can't use ::clear_all_solo_state() here because during
6525 session loading at program startup, that will queue a call
6526 to rt_clear_all_solo_state() that will not execute until
6527 AFTER solo states have been established (thus throwing away
6528 the session's saved solo state). So just explicitly turn
6531 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6533 clear_all_solo_state (get_routes());
6538 /** Called when a property of one of our route groups changes */
6540 Session::route_group_property_changed (RouteGroup* rg)
6542 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6545 /** Called when a route is added to one of our route groups */
6547 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6549 RouteAddedToRouteGroup (rg, r);
6552 /** Called when a route is removed from one of our route groups */
6554 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6556 update_route_record_state ();
6557 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6559 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6560 remove_route_group (*rg);
6564 boost::shared_ptr<AudioTrack>
6565 Session::get_nth_audio_track (int nth) const
6567 boost::shared_ptr<RouteList> rl = routes.reader ();
6568 rl->sort (Stripable::Sorter ());
6570 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6571 if (!boost::dynamic_pointer_cast<AudioTrack> (*r)) {
6578 return boost::dynamic_pointer_cast<AudioTrack> (*r);
6580 return boost::shared_ptr<AudioTrack> ();
6583 boost::shared_ptr<RouteList>
6584 Session::get_tracks () const
6586 boost::shared_ptr<RouteList> rl = routes.reader ();
6587 boost::shared_ptr<RouteList> tl (new RouteList);
6589 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6590 if (boost::dynamic_pointer_cast<Track> (*r)) {
6591 assert (!(*r)->is_auditioner()); // XXX remove me
6598 boost::shared_ptr<RouteList>
6599 Session::get_routes_with_regions_at (samplepos_t const p) const
6601 boost::shared_ptr<RouteList> r = routes.reader ();
6602 boost::shared_ptr<RouteList> rl (new RouteList);
6604 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6605 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6610 boost::shared_ptr<Playlist> pl = tr->playlist ();
6615 if (pl->has_region_at (p)) {
6624 Session::goto_end ()
6626 if (_session_range_location) {
6627 request_locate (_session_range_location->end(), false);
6629 request_locate (0, false);
6634 Session::goto_start (bool and_roll)
6636 if (_session_range_location) {
6637 request_locate (_session_range_location->start(), and_roll);
6639 request_locate (0, and_roll);
6644 Session::current_start_sample () const
6646 return _session_range_location ? _session_range_location->start() : 0;
6650 Session::current_end_sample () const
6652 return _session_range_location ? _session_range_location->end() : 0;
6656 Session::set_session_range_location (samplepos_t start, samplepos_t end)
6658 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6659 _locations->add (_session_range_location);
6663 Session::step_edit_status_change (bool yn)
6669 send = (_step_editors == 0);
6674 send = (_step_editors == 1);
6677 if (_step_editors > 0) {
6683 StepEditStatusChange (val);
6689 Session::start_time_changed (samplepos_t old)
6691 /* Update the auto loop range to match the session range
6692 (unless the auto loop range has been changed by the user)
6695 Location* s = _locations->session_range_location ();
6700 Location* l = _locations->auto_loop_location ();
6702 if (l && l->start() == old) {
6703 l->set_start (s->start(), true);
6709 Session::end_time_changed (samplepos_t old)
6711 /* Update the auto loop range to match the session range
6712 (unless the auto loop range has been changed by the user)
6715 Location* s = _locations->session_range_location ();
6720 Location* l = _locations->auto_loop_location ();
6722 if (l && l->end() == old) {
6723 l->set_end (s->end(), true);
6728 std::vector<std::string>
6729 Session::source_search_path (DataType type) const
6733 if (session_dirs.size() == 1) {
6735 case DataType::AUDIO:
6736 sp.push_back (_session_dir->sound_path());
6738 case DataType::MIDI:
6739 sp.push_back (_session_dir->midi_path());
6743 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6744 SessionDirectory sdir (i->path);
6746 case DataType::AUDIO:
6747 sp.push_back (sdir.sound_path());
6749 case DataType::MIDI:
6750 sp.push_back (sdir.midi_path());
6756 if (type == DataType::AUDIO) {
6757 const string sound_path_2X = _session_dir->sound_path_2X();
6758 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6759 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6760 sp.push_back (sound_path_2X);
6765 // now check the explicit (possibly user-specified) search path
6768 case DataType::AUDIO:
6769 sp += Searchpath(config.get_audio_search_path ());
6771 case DataType::MIDI:
6772 sp += Searchpath(config.get_midi_search_path ());
6780 Session::ensure_search_path_includes (const string& path, DataType type)
6789 case DataType::AUDIO:
6790 sp += Searchpath(config.get_audio_search_path ());
6792 case DataType::MIDI:
6793 sp += Searchpath (config.get_midi_search_path ());
6797 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6798 /* No need to add this new directory if it has the same inode as
6799 an existing one; checking inode rather than name prevents duplicated
6800 directories when we are using symlinks.
6802 On Windows, I think we could just do if (*i == path) here.
6804 if (PBD::equivalent_paths (*i, path)) {
6812 case DataType::AUDIO:
6813 config.set_audio_search_path (sp.to_string());
6815 case DataType::MIDI:
6816 config.set_midi_search_path (sp.to_string());
6822 Session::remove_dir_from_search_path (const string& dir, DataType type)
6827 case DataType::AUDIO:
6828 sp = Searchpath(config.get_audio_search_path ());
6830 case DataType::MIDI:
6831 sp = Searchpath (config.get_midi_search_path ());
6838 case DataType::AUDIO:
6839 config.set_audio_search_path (sp.to_string());
6841 case DataType::MIDI:
6842 config.set_midi_search_path (sp.to_string());
6848 boost::shared_ptr<Speakers>
6849 Session::get_speakers()
6855 Session::unknown_processors () const
6859 boost::shared_ptr<RouteList> r = routes.reader ();
6860 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6861 list<string> t = (*i)->unknown_processors ();
6862 copy (t.begin(), t.end(), back_inserter (p));
6872 Session::set_worst_io_latencies_x (IOChange, void *)
6874 set_worst_io_latencies ();
6878 Session::send_latency_compensation_change ()
6880 /* As a result of Send::set_output_latency()
6881 * or InternalReturn::set_playback_offset ()
6882 * the send's own latency can change (source track
6883 * is aligned with target bus).
6885 * This can only happen be triggered by
6886 * Route::update_signal_latency ()
6887 * when updating the processor latency.
6889 * We need to walk the graph again to take those changes into account
6890 * (we should probably recurse or process the graph in a 2 step process).
6892 ++_send_latency_changes;
6896 Session::update_route_latency (bool playback, bool apply_to_delayline)
6898 /* Note: RouteList is process-graph sorted */
6899 boost::shared_ptr<RouteList> r = routes.reader ();
6902 /* reverse the list so that we work backwards from the last route to run to the first,
6903 * this is not needed, but can help to reduce the iterations for aux-sends.
6905 RouteList* rl = routes.reader().get();
6906 r.reset (new RouteList (*rl));
6907 reverse (r->begin(), r->end());
6910 bool changed = false;
6913 _send_latency_changes = 0;
6914 _worst_route_latency = 0;
6916 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6917 // if (!(*i)->active()) { continue ; } // TODO
6919 if ((*i)->signal_latency () != (l = (*i)->update_signal_latency (apply_to_delayline))) {
6922 _worst_route_latency = std::max (l, _worst_route_latency);
6925 if (_send_latency_changes > 0) {
6926 // only 1 extra iteration is needed (we allow only 1 level of aux-sends)
6927 // BUT.. jack'n'sends'n'bugs
6928 if (++bailout < 5) {
6929 cerr << "restarting Session::update_latency. # of send changes: " << _send_latency_changes << " iteration: " << bailout << endl;
6934 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_route_latency, (changed ? "yes" : "no")));
6940 Session::update_latency (bool playback)
6942 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6944 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _route_deletion_in_progress) {
6947 if (!_engine.running()) {
6951 /* Note; RouteList is sorted as process-graph */
6952 boost::shared_ptr<RouteList> r = routes.reader ();
6955 /* reverse the list so that we work backwards from the last route to run to the first */
6956 RouteList* rl = routes.reader().get();
6957 r.reset (new RouteList (*rl));
6958 reverse (r->begin(), r->end());
6961 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6962 samplecnt_t latency = (*i)->set_private_port_latencies (playback);
6963 (*i)->set_public_port_latencies (latency, playback);
6967 set_worst_output_latency ();
6968 update_route_latency (true, true);
6970 set_worst_input_latency ();
6971 update_route_latency (false, false);
6974 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6978 Session::initialize_latencies ()
6981 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6982 update_latency (false);
6983 update_latency (true);
6986 set_worst_io_latencies ();
6990 Session::set_worst_io_latencies ()
6992 set_worst_output_latency ();
6993 set_worst_input_latency ();
6997 Session::set_worst_output_latency ()
6999 if (inital_connect_or_deletion_in_progress ()) {
7003 _worst_output_latency = 0;
7005 if (!_engine.running()) {
7009 boost::shared_ptr<RouteList> r = routes.reader ();
7011 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7012 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
7015 _worst_output_latency = max (_worst_output_latency, _click_io->latency());
7017 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
7021 Session::set_worst_input_latency ()
7023 if (inital_connect_or_deletion_in_progress ()) {
7027 _worst_input_latency = 0;
7029 if (!_engine.running()) {
7033 boost::shared_ptr<RouteList> r = routes.reader ();
7035 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7036 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
7039 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
7043 Session::update_latency_compensation (bool force_whole_graph)
7045 if (inital_connect_or_deletion_in_progress ()) {
7048 /* this lock is not usually contended, but under certain conditions,
7049 * update_latency_compensation may be called concurrently.
7050 * e.g. drag/drop copy a latent plugin while rolling.
7051 * GUI thread (via route_processors_changed) and
7052 * auto_connect_thread_run may race.
7054 Glib::Threads::Mutex::Lock lx (_update_latency_lock, Glib::Threads::TRY_LOCK);
7056 /* no need to do this twice */
7060 bool some_track_latency_changed = update_route_latency (false, false);
7062 if (some_track_latency_changed || force_whole_graph) {
7063 _engine.update_latencies ();
7064 /* above call will ask the backend up update its latencies, which
7065 * eventually will trigger AudioEngine::latency_callback () and
7066 * call Session::update_latency ()
7069 boost::shared_ptr<RouteList> r = routes.reader ();
7070 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7071 (*i)->apply_latency_compensation ();
7077 Session::session_name_is_legal (const string& path)
7079 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7081 for (int i = 0; illegal_chars[i]; ++i) {
7082 if (path.find (illegal_chars[i]) != string::npos) {
7083 return illegal_chars[i];
7091 Session::notify_presentation_info_change ()
7093 if (deletion_in_progress()) {
7097 reassign_track_numbers();
7099 #ifdef USE_TRACKS_CODE_FEATURES
7100 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7101 * if track order has been changed by user
7103 reconnect_existing_routes(true, true);
7109 Session::operation_in_progress (GQuark op) const
7111 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7114 boost::shared_ptr<Port>
7115 Session::ltc_output_port () const
7117 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
7121 Session::reconnect_ltc_output ()
7125 string src = Config->get_ltc_output_port();
7127 _ltc_output->disconnect (this);
7129 if (src != _("None") && !src.empty()) {
7130 _ltc_output->nth (0)->connect (src);
7136 Session::set_range_selection (samplepos_t start, samplepos_t end)
7138 _range_selection = Evoral::Range<samplepos_t> (start, end);
7139 #ifdef USE_TRACKS_CODE_FEATURES
7140 follow_playhead_priority ();
7145 Session::set_object_selection (samplepos_t start, samplepos_t end)
7147 _object_selection = Evoral::Range<samplepos_t> (start, end);
7148 #ifdef USE_TRACKS_CODE_FEATURES
7149 follow_playhead_priority ();
7154 Session::clear_range_selection ()
7156 _range_selection = Evoral::Range<samplepos_t> (-1,-1);
7157 #ifdef USE_TRACKS_CODE_FEATURES
7158 follow_playhead_priority ();
7163 Session::clear_object_selection ()
7165 _object_selection = Evoral::Range<samplepos_t> (-1,-1);
7166 #ifdef USE_TRACKS_CODE_FEATURES
7167 follow_playhead_priority ();
7172 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7173 const ChanCount& input_start,
7174 const ChanCount& output_start,
7175 const ChanCount& input_offset,
7176 const ChanCount& output_offset)
7178 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7179 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7180 input_start, output_start,
7181 input_offset, output_offset));
7183 auto_connect_thread_wakeup ();
7187 Session::auto_connect_thread_wakeup ()
7189 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7190 pthread_cond_signal (&_auto_connect_cond);
7191 pthread_mutex_unlock (&_auto_connect_mutex);
7196 Session::queue_latency_recompute ()
7198 g_atomic_int_inc (&_latency_recompute_pending);
7199 auto_connect_thread_wakeup ();
7203 Session::auto_connect (const AutoConnectRequest& ar)
7205 boost::shared_ptr<Route> route = ar.route.lock();
7207 if (!route) { return; }
7209 if (!IO::connecting_legal) {
7213 /* If both inputs and outputs are auto-connected to physical ports,
7214 * use the max of input and output offsets to ensure auto-connected
7215 * port numbers always match up (e.g. the first audio input and the
7216 * first audio output of the route will have the same physical
7217 * port number). Otherwise just use the lowest input or output
7221 const bool in_out_physical =
7222 (Config->get_input_auto_connect() & AutoConnectPhysical)
7223 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7224 && ar.connect_inputs;
7226 const ChanCount in_offset = in_out_physical
7227 ? ChanCount::max(ar.input_offset, ar.output_offset)
7230 const ChanCount out_offset = in_out_physical
7231 ? ChanCount::max(ar.input_offset, ar.output_offset)
7234 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7235 vector<string> physinputs;
7236 vector<string> physoutputs;
7239 /* for connecting track inputs we only want MIDI ports marked
7243 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7245 if (!physinputs.empty() && ar.connect_inputs) {
7246 uint32_t nphysical_in = physinputs.size();
7248 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7251 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7252 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7255 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7261 if (!physoutputs.empty()) {
7262 uint32_t nphysical_out = physoutputs.size();
7263 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7267 * do not create new connections if we reached the limit of physical outputs
7270 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7271 ARDOUR::Profile->get_trx () &&
7272 ar.output_offset.get(*t) == nphysical_out ) {
7276 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7277 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7278 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7279 /* master bus is audio only */
7280 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7281 port = _master_out->input()->ports().port(*t,
7282 i % _master_out->input()->n_ports().get(*t))->name();
7286 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7295 Session::auto_connect_thread_start ()
7297 if (g_atomic_int_get (&_ac_thread_active)) {
7301 while (!_auto_connect_queue.empty ()) {
7302 _auto_connect_queue.pop ();
7305 g_atomic_int_set (&_ac_thread_active, 1);
7306 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7307 g_atomic_int_set (&_ac_thread_active, 0);
7312 Session::auto_connect_thread_terminate ()
7314 if (!g_atomic_int_get (&_ac_thread_active)) {
7319 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7320 while (!_auto_connect_queue.empty ()) {
7321 _auto_connect_queue.pop ();
7325 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7326 * fail to wakeup the thread.
7329 pthread_mutex_lock (&_auto_connect_mutex);
7330 g_atomic_int_set (&_ac_thread_active, 0);
7331 pthread_cond_signal (&_auto_connect_cond);
7332 pthread_mutex_unlock (&_auto_connect_mutex);
7335 pthread_join (_auto_connect_thread, &status);
7339 Session::auto_connect_thread (void *arg)
7341 Session *s = static_cast<Session *>(arg);
7342 s->auto_connect_thread_run ();
7348 Session::auto_connect_thread_run ()
7350 pthread_set_name (X_("autoconnect"));
7351 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7352 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7353 pthread_mutex_lock (&_auto_connect_mutex);
7354 while (g_atomic_int_get (&_ac_thread_active)) {
7356 if (!_auto_connect_queue.empty ()) {
7357 // Why would we need the process lock ??
7358 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7359 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7360 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7361 // We have control over those, but what does jack do?
7362 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7364 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7365 while (!_auto_connect_queue.empty ()) {
7366 const AutoConnectRequest ar (_auto_connect_queue.front());
7367 _auto_connect_queue.pop ();
7374 if (!actively_recording ()) { // might not be needed,
7375 /* this is only used for updating plugin latencies, the
7376 * graph does not change. so it's safe in general.
7378 * update_latency_compensation ()
7379 * calls DiskWriter::set_capture_offset () which
7380 * modifies the capture-offset, which can be a problem.
7382 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7383 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7384 update_latency_compensation ();
7389 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7390 // jack1 cannot cope with removing ports while processing
7391 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7392 AudioEngine::instance()->clear_pending_port_deletions ();
7395 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7397 pthread_mutex_unlock (&_auto_connect_mutex);
7401 Session::cancel_all_solo ()
7405 get_stripables (sl);
7407 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7408 clear_all_solo_state (routes.reader());
7412 Session::maybe_update_tempo_from_midiclock_tempo (float bpm)
7414 if (_tempo_map->n_tempos() == 1) {
7415 TempoSection& ts (_tempo_map->tempo_section_at_sample (0));
7416 if (fabs (ts.note_types_per_minute() - bpm) > (0.01 * ts.note_types_per_minute())) {
7417 const Tempo tempo (bpm, 4.0, bpm);
7418 std::cerr << "new tempo " << bpm << " old " << ts.note_types_per_minute() << std::endl;
7419 _tempo_map->replace_tempo (ts, tempo, 0.0, 0.0, AudioTime);