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/unwind.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.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/directory_names.h"
70 #ifdef USE_TRACKS_CODE_FEATURES
71 #include "ardour/engine_state_controller.h"
73 #include "ardour/filename_extensions.h"
74 #include "ardour/gain_control.h"
75 #include "ardour/graph.h"
76 #include "ardour/luabindings.h"
77 #include "ardour/midiport_manager.h"
78 #include "ardour/scene_changer.h"
79 #include "ardour/midi_patch_manager.h"
80 #include "ardour/midi_track.h"
81 #include "ardour/midi_ui.h"
82 #include "ardour/operations.h"
83 #include "ardour/playlist.h"
84 #include "ardour/playlist_factory.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/revision.h"
94 #include "ardour/route_graph.h"
95 #include "ardour/route_group.h"
96 #include "ardour/send.h"
97 #include "ardour/selection.h"
98 #include "ardour/session.h"
99 #include "ardour/session_directory.h"
100 #include "ardour/session_playlists.h"
101 #include "ardour/slave.h"
102 #include "ardour/smf_source.h"
103 #include "ardour/solo_isolate_control.h"
104 #include "ardour/source_factory.h"
105 #include "ardour/speakers.h"
106 #include "ardour/tempo.h"
107 #include "ardour/ticker.h"
108 #include "ardour/track.h"
109 #include "ardour/types_convert.h"
110 #include "ardour/user_bundle.h"
111 #include "ardour/utils.h"
112 #include "ardour/vca_manager.h"
113 #include "ardour/vca.h"
115 #include "midi++/port.h"
116 #include "midi++/mmc.h"
118 #include "LuaBridge/LuaBridge.h"
120 #include "pbd/i18n.h"
122 #include <glibmm/checksum.h>
131 using namespace ARDOUR;
134 bool Session::_disable_all_loaded_plugins = false;
135 bool Session::_bypass_all_loaded_plugins = false;
136 guint Session::_name_id_counter = 0;
138 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
139 PBD::Signal1<void,std::string> Session::Dialog;
140 PBD::Signal0<int> Session::AskAboutPendingState;
141 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
142 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
143 PBD::Signal0<void> Session::SendFeedback;
144 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
146 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
147 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
148 PBD::Signal2<void,std::string, std::string> Session::Exported;
149 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
150 PBD::Signal0<void> Session::Quit;
151 PBD::Signal0<void> Session::FeedbackDetected;
152 PBD::Signal0<void> Session::SuccessfulGraphSort;
153 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
155 const framecnt_t Session::bounce_chunk_size = 8192;
156 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
157 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
159 // seconds should be added after the region exceeds end marker
160 #ifdef USE_TRACKS_CODE_FEATURES
161 const uint32_t Session::session_end_shift = 5;
163 const uint32_t Session::session_end_shift = 0;
166 /** @param snapshot_name Snapshot name, without .ardour suffix */
167 Session::Session (AudioEngine &eng,
168 const string& fullpath,
169 const string& snapshot_name,
170 BusProfile* bus_profile,
172 : playlists (new SessionPlaylists)
174 , process_function (&Session::process_with_events)
175 , _bounce_processing_active (false)
176 , waiting_for_sync_offset (false)
177 , _base_frame_rate (0)
178 , _nominal_frame_rate (0)
179 , _current_frame_rate (0)
180 , transport_sub_state (0)
181 , _record_status (Disabled)
182 , _transport_frame (0)
183 , _session_range_location (0)
184 , _session_range_end_is_free (true)
187 , _transport_speed (0)
188 , _default_transport_speed (1.0)
189 , _last_transport_speed (0)
190 , _signalled_varispeed (0)
191 , _target_transport_speed (0.0)
192 , auto_play_legal (false)
193 , _last_slave_transport_frame (0)
194 , maximum_output_latency (0)
195 , _requested_return_frame (-1)
196 , current_block_size (0)
197 , _worst_output_latency (0)
198 , _worst_input_latency (0)
199 , _worst_track_latency (0)
200 , _have_captured (false)
201 , _non_soloed_outs_muted (false)
204 , _solo_isolated_cnt (0)
206 , _was_seamless (Config->get_seamless_loop ())
207 , _under_nsm_control (false)
209 , delta_accumulator_cnt (0)
210 , average_slave_delta (1800) // !!! why 1800 ???
212 , have_first_delta_accumulator (false)
213 , _slave_state (Stopped)
214 , _mtc_active (false)
215 , _ltc_active (false)
216 , post_export_sync (false)
217 , post_export_position (0)
219 , _export_rolling (false)
220 , _realtime_export (false)
221 , _region_export (false)
222 , _export_preroll (0)
223 , _export_latency (0)
224 , _pre_export_mmc_enabled (false)
225 , _name (snapshot_name)
227 , _send_qf_mtc (false)
228 , _pframes_since_last_mtc (0)
230 , loop_changing (false)
232 , _session_dir (new SessionDirectory (fullpath))
233 , _current_snapshot_name (snapshot_name)
235 , state_was_pending (false)
236 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
238 , _save_queued (false)
239 , _last_roll_location (0)
240 , _last_roll_or_reversal_location (0)
241 , _last_record_location (0)
242 , pending_locate_roll (false)
243 , pending_locate_frame (0)
244 , pending_locate_flush (false)
245 , pending_abort (false)
246 , pending_auto_loop (false)
247 , _mempool ("Session", 3145728)
248 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
250 , _butler (new Butler (*this))
251 , _post_transport_work (0)
252 , cumulative_rf_motion (0)
254 , _locations (new Locations (*this))
255 , _ignore_skips_updates (false)
256 , _rt_thread_active (false)
257 , _rt_emit_pending (false)
258 , _ac_thread_active (0)
259 , _latency_recompute_pending (0)
261 , outbound_mtc_timecode_frame (0)
262 , next_quarter_frame_to_send (-1)
263 , _samples_per_timecode_frame (0)
264 , _frames_per_hour (0)
265 , _timecode_frames_per_hour (0)
266 , last_timecode_valid (false)
267 , last_timecode_when (0)
268 , _send_timecode_update (false)
280 , ltc_timecode_offset (0)
281 , ltc_timecode_negative_offset (false)
282 , midi_control_ui (0)
284 , _all_route_group (new RouteGroup (*this, "all"))
285 , routes (new RouteList)
286 , _adding_routes_in_progress (false)
287 , _reconnecting_routes_in_progress (false)
288 , _route_deletion_in_progress (false)
289 , destructive_index (0)
290 , _track_number_decimals(1)
291 , default_fade_steepness (0)
292 , default_fade_msecs (0)
293 , _total_free_4k_blocks (0)
294 , _total_free_4k_blocks_uncertain (false)
295 , no_questions_about_missing_files (false)
298 , _bundles (new BundleList)
299 , _bundle_xml_node (0)
302 , _click_rec_only (false)
304 , click_emphasis_data (0)
306 , click_emphasis_length (0)
307 , _clicks_cleared (0)
308 , _count_in_samples (0)
309 , _play_range (false)
310 , _range_selection (-1,-1)
311 , _object_selection (-1,-1)
312 , _preroll_record_punch_pos (-1)
313 , _preroll_record_trim_len (0)
314 , _count_in_once (false)
316 , first_file_data_format_reset (true)
317 , first_file_header_format_reset (true)
318 , have_looped (false)
319 , _have_rec_enabled_track (false)
320 , _have_rec_disabled_track (true)
322 , _suspend_timecode_transmission (0)
323 , _speakers (new Speakers)
324 , _ignore_route_processor_changes (0)
329 , _vca_manager (new VCAManager (*this))
330 , _selection (new CoreSelection (*this))
334 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
336 pthread_mutex_init (&_rt_emit_mutex, 0);
337 pthread_cond_init (&_rt_emit_cond, 0);
339 pthread_mutex_init (&_auto_connect_mutex, 0);
340 pthread_cond_init (&_auto_connect_cond, 0);
342 init_name_id_counter (1); // reset for new sessions, start at 1
343 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
345 pre_engine_init (fullpath); // sets _is_new
351 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
353 #ifdef USE_TRACKS_CODE_FEATURES
354 sr = EngineStateController::instance()->get_current_sample_rate();
356 if (ensure_engine (sr, true)) {
358 throw SessionException (_("Cannot connect to audio/midi engine"));
361 // set samplerate for plugins added early
362 // e.g from templates or MB channelstrip
363 set_block_size (_engine.samples_per_cycle());
364 set_frame_rate (_engine.sample_rate());
366 if (create (mix_template, bus_profile)) {
368 throw SessionException (_("Session initialization failed"));
371 /* if a mix template was provided, then ::create() will
372 * have copied it into the session and we need to load it
373 * so that we have the state ready for ::set_state()
374 * after the engine is started.
376 * Note that we do NOT try to get the sample rate from
377 * the template at this time, though doing so would
378 * be easy if we decided this was an appropriate part
382 if (!mix_template.empty()) {
383 if (load_state (_current_snapshot_name)) {
384 throw SessionException (_("Failed to load template/snapshot state"));
386 store_recent_templates (mix_template);
389 /* load default session properties - if any */
394 if (load_state (_current_snapshot_name)) {
395 throw SessionException (_("Failed to load state"));
398 /* try to get sample rate from XML state so that we
399 * can influence the SR if we set up the audio
404 XMLProperty const * prop;
405 XMLNode const * root (state_tree->root());
406 if ((prop = root->property (X_("sample-rate"))) != 0) {
407 sr = atoi (prop->value());
411 if (ensure_engine (sr, false)) {
413 throw SessionException (_("Cannot connect to audio/midi engine"));
417 int err = post_engine_init ();
422 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
426 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
429 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
432 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
435 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")));
440 store_recent_sessions (_name, _path);
442 bool was_dirty = dirty();
444 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
446 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
448 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
449 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
452 DirtyChanged (); /* EMIT SIGNAL */
455 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
456 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
458 emit_thread_start ();
459 auto_connect_thread_start ();
461 /* hook us up to the engine since we are now completely constructed */
463 BootMessage (_("Connect to engine"));
465 _engine.set_session (this);
466 _engine.reset_timebase ();
468 #ifdef USE_TRACKS_CODE_FEATURES
470 EngineStateController::instance()->set_session(this);
473 if ( ARDOUR::Profile->get_trx () ) {
475 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
476 * each available input must have corresponding track when session starts.
479 uint32_t how_many (0);
481 std::vector<std::string> inputs;
482 EngineStateController::instance()->get_physical_audio_inputs(inputs);
484 how_many = inputs.size();
486 list<boost::shared_ptr<AudioTrack> > tracks;
488 // Track names after driver
489 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
490 string track_name = "";
491 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
493 track_name = inputs[i];
494 replace_all (track_name, "system:capture", "");
496 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
497 tracks.insert(tracks.begin(), single_track.front());
499 } else { // Default track names
500 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
503 if (tracks.size() != how_many) {
505 throw failed_constructor ();
511 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
513 if (!mix_template.empty ()) {
514 /* ::create() unsets _is_new after creating the session.
515 * But for templated sessions, the sample-rate is initially unset
516 * (not read from template), so we need to save it (again).
524 BootMessage (_("Session loading complete"));
536 Session::next_name_id ()
538 return g_atomic_int_add (&_name_id_counter, 1);
542 Session::name_id_counter ()
544 return g_atomic_int_get (&_name_id_counter);
548 Session::init_name_id_counter (guint n)
550 g_atomic_int_set (&_name_id_counter, n);
554 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
556 if (_engine.current_backend() == 0) {
557 /* backend is unknown ... */
558 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
559 if (r.get_value_or (-1) != 0) {
562 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
564 } else if (_engine.setup_required()) {
565 /* backend is known, but setup is needed */
566 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
567 if (r.get_value_or (-1) != 0) {
570 } else if (!_engine.running()) {
571 if (_engine.start()) {
576 /* at this point the engine should be running */
578 if (!_engine.running()) {
582 return immediately_post_engine ();
587 Session::immediately_post_engine ()
589 /* Do various initializations that should take place directly after we
590 * know that the engine is running, but before we either create a
591 * session or set state for an existing one.
594 if (how_many_dsp_threads () > 1) {
595 /* For now, only create the graph if we are using >1 DSP threads, as
596 it is a bit slower than the old code with 1 thread.
598 _process_graph.reset (new Graph (*this));
601 /* every time we reconnect, recompute worst case output latencies */
603 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
605 if (synced_to_engine()) {
606 _engine.transport_stop ();
609 if (config.get_jack_time_master()) {
610 _engine.transport_locate (_transport_frame);
614 BootMessage (_("Set up LTC"));
616 BootMessage (_("Set up Click"));
618 BootMessage (_("Set up standard connections"));
622 catch (failed_constructor& err) {
626 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
628 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
636 vector<void*> debug_pointers;
638 /* if we got to here, leaving pending capture state around
642 remove_pending_capture_state ();
646 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
649 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
655 /* disconnect from any and all signals that we are connected to */
657 Port::PortSignalDrop (); /* EMIT SIGNAL */
660 /* shutdown control surface protocols while we still have ports
661 * and the engine to move data to any devices.
664 /* remove I/O objects before unsetting the engine session */
667 _ltc_output.reset ();
669 ControlProtocolManager::instance().drop_protocols ();
671 /* stop auto dis/connecting */
672 auto_connect_thread_terminate ();
674 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
676 _engine.remove_session ();
678 #ifdef USE_TRACKS_CODE_FEATURES
679 EngineStateController::instance()->remove_session();
682 /* deregister all ports - there will be no process or any other
683 * callbacks from the engine any more.
686 Port::PortDrop (); /* EMIT SIGNAL */
688 /* clear history so that no references to objects are held any more */
692 /* clear state tree so that no references to objects are held any more */
698 /* unregister all lua functions, drop held references (if any) */
699 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
701 lua.do_command ("Session = nil");
709 lua.collect_garbage ();
712 /* reset dynamic state version back to default */
713 Stateful::loading_state_version = 0;
715 _butler->drop_references ();
719 delete _all_route_group;
721 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
722 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
726 if (click_data != default_click) {
727 delete [] click_data;
730 if (click_emphasis_data != default_click_emphasis) {
731 delete [] click_emphasis_data;
736 /* need to remove auditioner before monitoring section
737 * otherwise it is re-connected */
740 /* drop references to routes held by the monitoring section
741 * specifically _monitor_out aux/listen references */
742 remove_monitor_section();
744 /* clear out any pending dead wood from RCU managed objects */
749 AudioDiskstream::free_working_buffers();
751 /* tell everyone who is still standing that we're about to die */
754 /* tell everyone to drop references and delete objects as we go */
756 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
757 RegionFactory::delete_all_regions ();
759 /* Do this early so that VCAs no longer hold references to routes */
761 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
764 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
766 /* reset these three references to special routes before we do the usual route delete thing */
768 _master_out.reset ();
769 _monitor_out.reset ();
772 RCUWriter<RouteList> writer (routes);
773 boost::shared_ptr<RouteList> r = writer.get_copy ();
775 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
776 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
777 (*i)->drop_references ();
781 /* writer goes out of scope and updates master */
786 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
787 Glib::Threads::Mutex::Lock lm (source_lock);
788 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
789 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
790 i->second->drop_references ();
796 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
799 emit_thread_terminate ();
801 pthread_cond_destroy (&_rt_emit_cond);
802 pthread_mutex_destroy (&_rt_emit_mutex);
804 pthread_cond_destroy (&_auto_connect_cond);
805 pthread_mutex_destroy (&_auto_connect_mutex);
807 delete _scene_changer; _scene_changer = 0;
808 delete midi_control_ui; midi_control_ui = 0;
810 delete _mmc; _mmc = 0;
811 delete _midi_ports; _midi_ports = 0;
812 delete _locations; _locations = 0;
817 /* clear event queue, the session is gone, nobody is interested in
818 * those anymore, but they do leak memory if not removed
820 while (!immediate_events.empty ()) {
821 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
822 SessionEvent *ev = immediate_events.front ();
823 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
824 immediate_events.pop_front ();
828 case SessionEvent::AutoLoop:
829 case SessionEvent::AutoLoopDeclick:
830 case SessionEvent::Skip:
831 case SessionEvent::PunchIn:
832 case SessionEvent::PunchOut:
833 case SessionEvent::RecordStart:
834 case SessionEvent::StopOnce:
835 case SessionEvent::RangeStop:
836 case SessionEvent::RangeLocate:
840 case SessionEvent::RealTimeOperation:
847 del = del && !_remove_event (ev);
855 /* unregister all dropped ports, process pending port deletion. */
856 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
857 // jack1 cannot cope with removing ports while processing
858 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
859 AudioEngine::instance()->clear_pending_port_deletions ();
862 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
866 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
868 BOOST_SHOW_POINTERS ();
872 Session::setup_ltc ()
876 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
877 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
879 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
880 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
883 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
884 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
885 // TODO use auto-connect thread somehow (needs a route currently)
886 // see note in Session::auto_connect_thread_run() why process lock is needed.
887 reconnect_ltc_input ();
891 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
892 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
895 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
896 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
897 // TODO use auto-connect thread
898 reconnect_ltc_output ();
902 /* fix up names of LTC ports because we don't want the normal
903 * IO style of NAME/TYPE-{in,out}N
906 _ltc_input->nth (0)->set_name (X_("LTC-in"));
907 _ltc_output->nth (0)->set_name (X_("LTC-out"));
911 Session::setup_click ()
915 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
916 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
918 _click_io.reset (new ClickIO (*this, X_("Click")));
919 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
920 _click_gain->activate ();
922 setup_click_state (state_tree->root());
924 setup_click_state (0);
929 Session::setup_click_state (const XMLNode* node)
931 const XMLNode* child = 0;
933 if (node && (child = find_named_node (*node, "Click")) != 0) {
935 /* existing state for Click */
938 if (Stateful::loading_state_version < 3000) {
939 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
941 const XMLNodeList& children (child->children());
942 XMLNodeList::const_iterator i = children.begin();
943 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
945 if (i != children.end()) {
946 c = _click_gain->set_state (**i, Stateful::loading_state_version);
952 _clicking = Config->get_clicking ();
956 error << _("could not setup Click I/O") << endmsg;
963 /* default state for Click: dual-mono to first 2 physical outputs */
966 _engine.get_physical_outputs (DataType::AUDIO, outs);
968 for (uint32_t physport = 0; physport < 2; ++physport) {
969 if (outs.size() > physport) {
970 if (_click_io->add_port (outs[physport], this)) {
971 // relax, even though its an error
976 if (_click_io->n_ports () > ChanCount::ZERO) {
977 _clicking = Config->get_clicking ();
983 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
984 MidiPortFlags include, MidiPortFlags exclude)
986 _engine.get_physical_inputs (type, inputs, include, exclude);
987 _engine.get_physical_outputs (type, outputs, include, exclude);
991 Session::setup_bundles ()
995 RCUWriter<BundleList> writer (_bundles);
996 boost::shared_ptr<BundleList> b = writer.get_copy ();
997 for (BundleList::iterator i = b->begin(); i != b->end();) {
998 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
1006 vector<string> inputs[DataType::num_types];
1007 vector<string> outputs[DataType::num_types];
1009 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1010 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
1011 MidiPortFlags (0), /* no specific inclusions */
1012 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1016 /* Create a set of Bundle objects that map
1017 to the physical I/O currently available. We create both
1018 mono and stereo bundles, so that the common cases of mono
1019 and stereo tracks get bundles to put in their mixer strip
1020 in / out menus. There may be a nicer way of achieving that;
1021 it doesn't really scale that well to higher channel counts
1024 /* mono output bundles */
1026 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1028 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1030 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1032 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1035 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1036 c->add_channel (_("mono"), DataType::AUDIO);
1037 c->set_port (0, outputs[DataType::AUDIO][np]);
1039 add_bundle (c, false);
1042 /* stereo output bundles */
1044 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1045 if (np + 1 < outputs[DataType::AUDIO].size()) {
1047 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1048 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1049 c->add_channel (_("L"), DataType::AUDIO);
1050 c->set_port (0, outputs[DataType::AUDIO][np]);
1051 c->add_channel (_("R"), DataType::AUDIO);
1052 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1054 add_bundle (c, false);
1058 /* mono input bundles */
1060 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1062 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1064 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1066 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1069 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1070 c->add_channel (_("mono"), DataType::AUDIO);
1071 c->set_port (0, inputs[DataType::AUDIO][np]);
1073 add_bundle (c, false);
1076 /* stereo input bundles */
1078 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1079 if (np + 1 < inputs[DataType::AUDIO].size()) {
1081 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1083 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1084 c->add_channel (_("L"), DataType::AUDIO);
1085 c->set_port (0, inputs[DataType::AUDIO][np]);
1086 c->add_channel (_("R"), DataType::AUDIO);
1087 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1089 add_bundle (c, false);
1093 /* MIDI input bundles */
1095 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1096 string n = inputs[DataType::MIDI][np];
1098 std::string pn = _engine.get_pretty_name_by_name (n);
1102 boost::erase_first (n, X_("alsa_pcm:"));
1104 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1105 c->add_channel ("", DataType::MIDI);
1106 c->set_port (0, inputs[DataType::MIDI][np]);
1107 add_bundle (c, false);
1110 /* MIDI output bundles */
1112 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1113 string n = outputs[DataType::MIDI][np];
1114 std::string pn = _engine.get_pretty_name_by_name (n);
1118 boost::erase_first (n, X_("alsa_pcm:"));
1120 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1121 c->add_channel ("", DataType::MIDI);
1122 c->set_port (0, outputs[DataType::MIDI][np]);
1123 add_bundle (c, false);
1126 // we trust the backend to only calls us if there's a change
1127 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1131 Session::auto_connect_master_bus ()
1133 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1137 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1138 // In this case it means "Multi Out" output mode
1139 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1143 /* if requested auto-connect the outputs to the first N physical ports.
1146 uint32_t limit = _master_out->n_outputs().n_total();
1147 vector<string> outputs[DataType::num_types];
1149 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1150 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1153 for (uint32_t n = 0; n < limit; ++n) {
1154 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1156 if (outputs[p->type()].size() > n) {
1157 connect_to = outputs[p->type()][n];
1160 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1161 if (_master_out->output()->connect (p, connect_to, this)) {
1162 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1171 Session::remove_monitor_section ()
1173 if (!_monitor_out || Profile->get_trx()) {
1177 /* force reversion to Solo-In-Place */
1178 Config->set_solo_control_is_listen_control (false);
1180 /* if we are auditioning, cancel it ... this is a workaround
1181 to a problem (auditioning does not execute the process graph,
1182 which is needed to remove routes when using >1 core for processing)
1187 /* Hold process lock while doing this so that we don't hear bits and
1188 * pieces of audio as we work on each route.
1191 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1193 /* Connect tracks to monitor section. Note that in an
1194 existing session, the internal sends will already exist, but we want the
1195 routes to notice that they connect to the control out specifically.
1199 boost::shared_ptr<RouteList> r = routes.reader ();
1200 ProcessorChangeBlocker pcb (this, false);
1202 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1204 if ((*x)->is_monitor()) {
1206 } else if ((*x)->is_master()) {
1209 (*x)->remove_aux_or_listen (_monitor_out);
1214 remove_route (_monitor_out);
1215 if (_state_of_the_state & Deletion) {
1219 auto_connect_master_bus ();
1222 auditioner->connect ();
1225 Config->ParameterChanged ("use-monitor-bus");
1229 Session::add_monitor_section ()
1233 if (_monitor_out || !_master_out || Profile->get_trx()) {
1237 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1243 BOOST_MARK_ROUTE(r);
1246 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1247 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1248 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1250 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1255 add_routes (rl, false, false, false, 0);
1257 assert (_monitor_out);
1259 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1260 are undefined, at best.
1263 uint32_t limit = _monitor_out->n_inputs().n_audio();
1267 /* connect the inputs to the master bus outputs. this
1268 * represents a separate data feed from the internal sends from
1269 * each route. as of jan 2011, it allows the monitor section to
1270 * conditionally ignore either the internal sends or the normal
1271 * input feed, but we should really find a better way to do
1275 _master_out->output()->disconnect (this);
1277 for (uint32_t n = 0; n < limit; ++n) {
1278 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1279 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1282 string connect_to = o->name();
1283 if (_monitor_out->input()->connect (p, connect_to, this)) {
1284 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1292 /* if monitor section is not connected, connect it to physical outs
1295 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1297 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1299 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1302 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1304 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1305 Config->get_monitor_bus_preferred_bundle())
1311 /* Monitor bus is audio only */
1313 vector<string> outputs[DataType::num_types];
1315 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1316 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1319 uint32_t mod = outputs[DataType::AUDIO].size();
1320 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1324 for (uint32_t n = 0; n < limit; ++n) {
1326 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1328 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1329 connect_to = outputs[DataType::AUDIO][n % mod];
1332 if (!connect_to.empty()) {
1333 if (_monitor_out->output()->connect (p, connect_to, this)) {
1334 error << string_compose (
1335 _("cannot connect control output %1 to %2"),
1346 /* Hold process lock while doing this so that we don't hear bits and
1347 * pieces of audio as we work on each route.
1350 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1352 /* Connect tracks to monitor section. Note that in an
1353 existing session, the internal sends will already exist, but we want the
1354 routes to notice that they connect to the control out specifically.
1358 boost::shared_ptr<RouteList> rls = routes.reader ();
1360 ProcessorChangeBlocker pcb (this, false /* XXX */);
1362 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1364 if ((*x)->is_monitor()) {
1366 } else if ((*x)->is_master()) {
1369 (*x)->enable_monitor_send ();
1374 auditioner->connect ();
1376 Config->ParameterChanged ("use-monitor-bus");
1380 Session::reset_monitor_section ()
1382 /* Process lock should be held by the caller.*/
1384 if (!_monitor_out || Profile->get_trx()) {
1388 uint32_t limit = _master_out->n_outputs().n_audio();
1390 /* connect the inputs to the master bus outputs. this
1391 * represents a separate data feed from the internal sends from
1392 * each route. as of jan 2011, it allows the monitor section to
1393 * conditionally ignore either the internal sends or the normal
1394 * input feed, but we should really find a better way to do
1398 _master_out->output()->disconnect (this);
1399 _monitor_out->output()->disconnect (this);
1401 // monitor section follow master bus - except midi
1402 ChanCount mon_chn (_master_out->output()->n_ports());
1403 mon_chn.set_midi (0);
1405 _monitor_out->input()->ensure_io (mon_chn, false, this);
1406 _monitor_out->output()->ensure_io (mon_chn, false, this);
1408 for (uint32_t n = 0; n < limit; ++n) {
1409 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1410 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1413 string connect_to = o->name();
1414 if (_monitor_out->input()->connect (p, connect_to, this)) {
1415 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1422 /* connect monitor section to physical outs
1425 if (Config->get_auto_connect_standard_busses()) {
1427 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1429 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1432 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1434 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1435 Config->get_monitor_bus_preferred_bundle())
1441 /* Monitor bus is audio only */
1443 vector<string> outputs[DataType::num_types];
1445 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1446 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1449 uint32_t mod = outputs[DataType::AUDIO].size();
1450 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1454 for (uint32_t n = 0; n < limit; ++n) {
1456 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1458 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1459 connect_to = outputs[DataType::AUDIO][n % mod];
1462 if (!connect_to.empty()) {
1463 if (_monitor_out->output()->connect (p, connect_to, this)) {
1464 error << string_compose (
1465 _("cannot connect control output %1 to %2"),
1476 /* Connect tracks to monitor section. Note that in an
1477 existing session, the internal sends will already exist, but we want the
1478 routes to notice that they connect to the control out specifically.
1482 boost::shared_ptr<RouteList> rls = routes.reader ();
1484 ProcessorChangeBlocker pcb (this, false);
1486 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1488 if ((*x)->is_monitor()) {
1490 } else if ((*x)->is_master()) {
1493 (*x)->enable_monitor_send ();
1499 Session::hookup_io ()
1501 /* stop graph reordering notifications from
1502 causing resorts, etc.
1505 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1509 /* we delay creating the auditioner till now because
1510 it makes its own connections to ports.
1514 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1516 throw failed_constructor ();
1518 a->use_new_diskstream ();
1522 catch (failed_constructor& err) {
1523 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1527 /* load bundles, which we may have postponed earlier on */
1528 if (_bundle_xml_node) {
1529 load_bundles (*_bundle_xml_node);
1530 delete _bundle_xml_node;
1533 /* Tell all IO objects to connect themselves together */
1535 IO::enable_connecting ();
1537 /* Now tell all "floating" ports to connect to whatever
1538 they should be connected to.
1541 AudioEngine::instance()->reconnect_ports ();
1543 /* Anyone who cares about input state, wake up and do something */
1545 IOConnectionsComplete (); /* EMIT SIGNAL */
1547 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1549 /* now handle the whole enchilada as if it was one
1550 graph reorder event.
1555 /* update the full solo state, which can't be
1556 correctly determined on a per-route basis, but
1557 needs the global overview that only the session
1561 update_route_solo_state ();
1565 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1567 boost::shared_ptr<Track> track = wp.lock ();
1572 boost::shared_ptr<Playlist> playlist;
1574 if ((playlist = track->playlist()) != 0) {
1575 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1576 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1577 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1582 Session::record_enabling_legal () const
1584 /* this used to be in here, but survey says.... we don't need to restrict it */
1585 // if (record_status() == Recording) {
1589 if (Config->get_all_safe()) {
1596 Session::set_track_monitor_input_status (bool yn)
1598 boost::shared_ptr<RouteList> rl = routes.reader ();
1599 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1600 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1601 if (tr && tr->rec_enable_control()->get_value()) {
1602 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1603 tr->request_input_monitoring (yn);
1609 Session::auto_punch_start_changed (Location* location)
1611 replace_event (SessionEvent::PunchIn, location->start());
1613 if (get_record_enabled() && config.get_punch_in()) {
1614 /* capture start has been changed, so save new pending state */
1615 save_state ("", true);
1620 Session::auto_punch_end_changed (Location* location)
1622 framepos_t when_to_stop = location->end();
1623 // when_to_stop += _worst_output_latency + _worst_input_latency;
1624 replace_event (SessionEvent::PunchOut, when_to_stop);
1628 Session::auto_punch_changed (Location* location)
1630 framepos_t when_to_stop = location->end();
1632 replace_event (SessionEvent::PunchIn, location->start());
1633 //when_to_stop += _worst_output_latency + _worst_input_latency;
1634 replace_event (SessionEvent::PunchOut, when_to_stop);
1637 /** @param loc A loop location.
1638 * @param pos Filled in with the start time of the required fade-out (in session frames).
1639 * @param length Filled in with the length of the required fade-out.
1642 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1644 pos = max (loc->start(), loc->end() - 64);
1645 length = loc->end() - pos;
1649 Session::auto_loop_changed (Location* location)
1651 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1654 auto_loop_declick_range (location, dcp, dcl);
1656 if (transport_rolling() && play_loop) {
1658 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1660 // if (_transport_frame > location->end()) {
1662 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1663 // relocate to beginning of loop
1664 clear_events (SessionEvent::LocateRoll);
1666 request_locate (location->start(), true);
1669 else if (Config->get_seamless_loop() && !loop_changing) {
1671 // schedule a locate-roll to refill the diskstreams at the
1672 // previous loop end
1673 loop_changing = true;
1675 if (location->end() > last_loopend) {
1676 clear_events (SessionEvent::LocateRoll);
1677 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1683 clear_events (SessionEvent::AutoLoopDeclick);
1684 clear_events (SessionEvent::AutoLoop);
1687 /* possibly move playhead if not rolling; if we are rolling we'll move
1688 to the loop start on stop if that is appropriate.
1693 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1694 if (pos == location->start()) {
1695 request_locate (pos);
1700 last_loopend = location->end();
1705 Session::set_auto_punch_location (Location* location)
1709 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1710 punch_connections.drop_connections();
1711 existing->set_auto_punch (false, this);
1712 remove_event (existing->start(), SessionEvent::PunchIn);
1713 clear_events (SessionEvent::PunchOut);
1714 auto_punch_location_changed (0);
1719 if (location == 0) {
1723 if (location->end() <= location->start()) {
1724 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1728 punch_connections.drop_connections ();
1730 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1731 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1732 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1734 location->set_auto_punch (true, this);
1736 auto_punch_changed (location);
1738 auto_punch_location_changed (location);
1742 Session::set_session_extents (framepos_t start, framepos_t end)
1745 if ((existing = _locations->session_range_location()) == 0) {
1746 //if there is no existing session, we need to make a new session location (should never happen)
1747 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1751 error << _("Session: you can't use that location for session start/end)") << endmsg;
1755 existing->set( start, end );
1761 Session::set_auto_loop_location (Location* location)
1765 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1766 loop_connections.drop_connections ();
1767 existing->set_auto_loop (false, this);
1768 remove_event (existing->end(), SessionEvent::AutoLoop);
1771 auto_loop_declick_range (existing, dcp, dcl);
1772 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1773 auto_loop_location_changed (0);
1778 if (location == 0) {
1782 if (location->end() <= location->start()) {
1783 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1787 last_loopend = location->end();
1789 loop_connections.drop_connections ();
1791 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1792 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1793 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1794 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1796 location->set_auto_loop (true, this);
1798 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1799 // set all tracks to use internal looping
1800 boost::shared_ptr<RouteList> rl = routes.reader ();
1801 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1802 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1803 if (tr && !tr->hidden()) {
1804 tr->set_loop (location);
1809 /* take care of our stuff first */
1811 auto_loop_changed (location);
1813 /* now tell everyone else */
1815 auto_loop_location_changed (location);
1819 Session::update_marks (Location*)
1825 Session::update_skips (Location* loc, bool consolidate)
1827 if (_ignore_skips_updates) {
1831 Locations::LocationList skips;
1834 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1835 consolidate_skips (loc);
1838 sync_locations_to_skips ();
1844 Session::consolidate_skips (Location* loc)
1846 Locations::LocationList all_locations = _locations->list ();
1848 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1850 if (!(*l)->is_skip ()) {
1855 /* don't test against self */
1862 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1863 case Evoral::OverlapInternal:
1864 case Evoral::OverlapExternal:
1865 case Evoral::OverlapStart:
1866 case Evoral::OverlapEnd:
1867 /* adjust new location to cover existing one */
1868 loc->set_start (min (loc->start(), (*l)->start()));
1869 loc->set_end (max (loc->end(), (*l)->end()));
1870 /* we don't need this one any more */
1871 _locations->remove (*l);
1872 /* the location has been deleted, so remove reference to it in our local list */
1873 l = all_locations.erase (l);
1876 case Evoral::OverlapNone:
1884 Session::sync_locations_to_skips ()
1886 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1887 * Session::_sync_locations_to_skips() from the audioengine thread.
1889 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1893 Session::_sync_locations_to_skips ()
1895 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1897 Locations::LocationList const & locs (_locations->list());
1899 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1901 Location* location = *i;
1903 if (location->is_skip() && location->is_skipping()) {
1904 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1912 Session::location_added (Location *location)
1914 if (location->is_auto_punch()) {
1915 set_auto_punch_location (location);
1918 if (location->is_auto_loop()) {
1919 set_auto_loop_location (location);
1922 if (location->is_session_range()) {
1923 /* no need for any signal handling or event setting with the session range,
1924 because we keep a direct reference to it and use its start/end directly.
1926 _session_range_location = location;
1929 if (location->is_mark()) {
1930 /* listen for per-location signals that require us to do any * global updates for marks */
1932 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1933 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1934 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1935 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1936 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1939 if (location->is_range_marker()) {
1940 /* listen for per-location signals that require us to do any * global updates for marks */
1942 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1943 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1944 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1945 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1946 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1949 if (location->is_skip()) {
1950 /* listen for per-location signals that require us to update skip-locate events */
1952 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1953 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1954 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1955 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1956 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1958 update_skips (location, true);
1965 Session::location_removed (Location *location)
1967 if (location->is_auto_loop()) {
1968 set_auto_loop_location (0);
1969 set_track_loop (false);
1972 if (location->is_auto_punch()) {
1973 set_auto_punch_location (0);
1976 if (location->is_session_range()) {
1977 /* this is never supposed to happen */
1978 error << _("programming error: session range removed!") << endl;
1981 if (location->is_skip()) {
1983 update_skips (location, false);
1990 Session::locations_changed ()
1992 _locations->apply (*this, &Session::_locations_changed);
1996 Session::_locations_changed (const Locations::LocationList& locations)
1998 /* There was some mass-change in the Locations object.
2000 We might be re-adding a location here but it doesn't actually matter
2001 for all the locations that the Session takes an interest in.
2005 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
2006 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
2007 location_added (*i);
2011 update_skips (NULL, false);
2015 Session::enable_record ()
2017 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2018 /* no recording at anything except normal speed */
2023 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2025 if (rs == Recording) {
2029 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2031 _last_record_location = _transport_frame;
2032 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2034 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2035 set_track_monitor_input_status (true);
2038 RecordStateChanged ();
2045 Session::set_all_tracks_record_enabled (bool enable )
2047 boost::shared_ptr<RouteList> rl = routes.reader();
2048 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2052 Session::disable_record (bool rt_context, bool force)
2056 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2058 if (!Config->get_latched_record_enable () || force) {
2059 g_atomic_int_set (&_record_status, Disabled);
2060 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2062 if (rs == Recording) {
2063 g_atomic_int_set (&_record_status, Enabled);
2067 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2068 set_track_monitor_input_status (false);
2071 RecordStateChanged (); /* emit signal */
2074 remove_pending_capture_state ();
2076 unset_preroll_record_punch ();
2081 Session::step_back_from_record ()
2083 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2085 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2086 set_track_monitor_input_status (false);
2089 RecordStateChanged (); /* emit signal */
2094 Session::maybe_enable_record (bool rt_context)
2096 if (_step_editors > 0) {
2100 g_atomic_int_set (&_record_status, Enabled);
2102 /* This function is currently called from somewhere other than an RT thread.
2103 * (except maybe lua scripts, which can use rt_context = true)
2104 * This save_state() call therefore doesn't impact anything. Doing it here
2105 * means that we save pending state of which sources the next record will use,
2106 * which gives us some chance of recovering from a crash during the record.
2110 save_state ("", true);
2113 if (_transport_speed) {
2114 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2118 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2119 RecordStateChanged (); /* EMIT SIGNAL */
2126 Session::audible_frame (bool* latent_locate) const
2130 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2131 offset *= transport_speed ();
2132 if (latent_locate) {
2133 *latent_locate = false;
2136 if (synced_to_engine()) {
2137 /* Note: this is basically just sync-to-JACK */
2138 ret = _engine.transport_frame();
2140 ret = _transport_frame;
2143 if (transport_rolling()) {
2146 /* Check to see if we have passed the first guaranteed
2147 * audible frame past our last start position. if not,
2148 * return that last start point because in terms
2149 * of audible frames, we have not moved yet.
2151 * `Start position' in this context means the time we last
2152 * either started, located, or changed transport direction.
2155 if (_transport_speed > 0.0f) {
2157 if (!play_loop || !have_looped) {
2158 if (ret < _last_roll_or_reversal_location) {
2159 if (latent_locate) {
2160 *latent_locate = true;
2162 return _last_roll_or_reversal_location;
2165 /* the play-position wrapped at the loop-point
2166 * ardour is already playing the beginning of the loop,
2167 * but due to playback latency, the "audible frame"
2168 * is still at the end of the loop.
2170 Location *location = _locations->auto_loop_location();
2171 frameoffset_t lo = location->start() - ret;
2173 ret = location->end () - lo;
2174 if (latent_locate) {
2175 *latent_locate = true;
2180 } else if (_transport_speed < 0.0f) {
2182 /* XXX wot? no backward looping? */
2184 if (ret > _last_roll_or_reversal_location) {
2185 return _last_roll_or_reversal_location;
2190 return std::max ((framepos_t)0, ret);
2195 Session::preroll_samples (framepos_t pos) const
2197 const float pr = Config->get_preroll_seconds();
2198 if (pos >= 0 && pr < 0) {
2199 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2200 const Meter& meter = _tempo_map->meter_at_frame (pos);
2201 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2206 return pr * frame_rate();
2210 Session::set_frame_rate (framecnt_t frames_per_second)
2212 /** \fn void Session::set_frame_size(framecnt_t)
2213 the AudioEngine object that calls this guarantees
2214 that it will not be called while we are also in
2215 ::process(). Its fine to do things that block
2219 if (_base_frame_rate == 0) {
2220 _base_frame_rate = frames_per_second;
2222 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2223 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2225 _nominal_frame_rate = frames_per_second;
2230 reset_write_sources (false);
2232 // XXX we need some equivalent to this, somehow
2233 // SndFileSource::setup_standard_crossfades (frames_per_second);
2237 /* XXX need to reset/reinstantiate all LADSPA plugins */
2241 Session::set_block_size (pframes_t nframes)
2243 /* the AudioEngine guarantees
2244 that it will not be called while we are also in
2245 ::process(). It is therefore fine to do things that block
2250 current_block_size = nframes;
2254 boost::shared_ptr<RouteList> r = routes.reader ();
2256 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2257 (*i)->set_block_size (nframes);
2260 boost::shared_ptr<RouteList> rl = routes.reader ();
2261 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2262 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2264 tr->set_block_size (nframes);
2268 set_worst_io_latencies ();
2274 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2276 boost::shared_ptr<Route> r2;
2278 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2279 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2283 /* make a copy of the existing list of routes that feed r1 */
2285 Route::FedBy existing (r1->fed_by());
2287 /* for each route that feeds r1, recurse, marking it as feeding
2291 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2292 if (!(r2 = i->r.lock ())) {
2293 /* (*i) went away, ignore it */
2297 /* r2 is a route that feeds r1 which somehow feeds base. mark
2298 base as being fed by r2
2301 rbase->add_fed_by (r2, i->sends_only);
2305 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2309 if (r1->feeds (r2) && r2->feeds (r1)) {
2313 /* now recurse, so that we can mark base as being fed by
2314 all routes that feed r2
2317 trace_terminal (r2, rbase);
2324 Session::resort_routes ()
2326 /* don't do anything here with signals emitted
2327 by Routes during initial setup or while we
2328 are being destroyed.
2331 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2335 if (_route_deletion_in_progress) {
2340 RCUWriter<RouteList> writer (routes);
2341 boost::shared_ptr<RouteList> r = writer.get_copy ();
2342 resort_routes_using (r);
2343 /* writer goes out of scope and forces update */
2347 if (DEBUG_ENABLED(DEBUG::Graph)) {
2348 boost::shared_ptr<RouteList> rl = routes.reader ();
2349 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2350 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2352 const Route::FedBy& fb ((*i)->fed_by());
2354 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2355 boost::shared_ptr<Route> sf = f->r.lock();
2357 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2366 /** This is called whenever we need to rebuild the graph of how we will process
2368 * @param r List of routes, in any order.
2372 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2374 /* We are going to build a directed graph of our routes;
2375 this is where the edges of that graph are put.
2380 /* Go through all routes doing two things:
2382 * 1. Collect the edges of the route graph. Each of these edges
2383 * is a pair of routes, one of which directly feeds the other
2384 * either by a JACK connection or by an internal send.
2386 * 2. Begin the process of making routes aware of which other
2387 * routes directly or indirectly feed them. This information
2388 * is used by the solo code.
2391 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2393 /* Clear out the route's list of direct or indirect feeds */
2394 (*i)->clear_fed_by ();
2396 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2398 bool via_sends_only;
2400 /* See if this *j feeds *i according to the current state of the JACK
2401 connections and internal sends.
2403 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2404 /* add the edge to the graph (part #1) */
2405 edges.add (*j, *i, via_sends_only);
2406 /* tell the route (for part #2) */
2407 (*i)->add_fed_by (*j, via_sends_only);
2412 /* Attempt a topological sort of the route graph */
2413 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2415 if (sorted_routes) {
2416 /* We got a satisfactory topological sort, so there is no feedback;
2419 Note: the process graph rechain does not require a
2420 topologically-sorted list, but hey ho.
2422 if (_process_graph) {
2423 _process_graph->rechain (sorted_routes, edges);
2426 _current_route_graph = edges;
2428 /* Complete the building of the routes' lists of what directly
2429 or indirectly feeds them.
2431 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2432 trace_terminal (*i, *i);
2435 *r = *sorted_routes;
2438 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2439 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2440 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2444 SuccessfulGraphSort (); /* EMIT SIGNAL */
2447 /* The topological sort failed, so we have a problem. Tell everyone
2448 and stick to the old graph; this will continue to be processed, so
2449 until the feedback is fixed, what is played back will not quite
2450 reflect what is actually connected. Note also that we do not
2451 do trace_terminal here, as it would fail due to an endless recursion,
2452 so the solo code will think that everything is still connected
2456 FeedbackDetected (); /* EMIT SIGNAL */
2461 /** Find a route name starting with \a base, maybe followed by the
2462 * lowest \a id. \a id will always be added if \a definitely_add_number
2463 * is true on entry; otherwise it will only be added if required
2464 * to make the name unique.
2466 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2467 * The available route name with the lowest ID will be used, and \a id
2468 * will be set to the ID.
2470 * \return false if a route name could not be found, and \a track_name
2471 * and \a id do not reflect a free route name.
2474 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2476 /* the base may conflict with ports that do not belong to existing
2477 routes, but hidden objects like the click track. So check port names
2478 before anything else.
2481 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2482 if (base == reserved->first) {
2483 /* Check if this reserved name already exists, and if
2484 so, disallow it without a numeric suffix.
2486 if (!reserved->second || route_by_name (reserved->first)) {
2487 definitely_add_number = true;
2496 /* if we have "base 1" already, it doesn't make sense to add "base"
2497 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2499 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2500 /* just use the base */
2506 name = string_compose ("%1 %2", base, id);
2508 if (route_by_name (name) == 0) {
2514 } while (id < (UINT_MAX-1));
2519 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2521 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2523 in = ChanCount::ZERO;
2524 out = ChanCount::ZERO;
2526 boost::shared_ptr<RouteList> r = routes.reader ();
2528 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2529 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2530 if (tr && !tr->is_auditioner()) {
2531 in += tr->n_inputs();
2532 out += tr->n_outputs();
2538 Session::default_track_name_pattern (DataType t)
2541 case DataType::AUDIO:
2542 if (Profile->get_trx()) {
2549 case DataType::MIDI:
2556 /** Caller must not hold process lock
2557 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2558 * @param instrument plugin info for the instrument to insert pre-fader, if any
2560 list<boost::shared_ptr<MidiTrack> >
2561 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2562 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2563 RouteGroup* route_group, uint32_t how_many,
2564 string name_template, PresentationInfo::order_t order,
2568 uint32_t track_id = 0;
2570 RouteList new_routes;
2571 list<boost::shared_ptr<MidiTrack> > ret;
2573 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2574 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2577 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2578 error << "cannot find name for new midi track" << endmsg;
2582 boost::shared_ptr<MidiTrack> track;
2585 track.reset (new MidiTrack (*this, track_name, mode));
2587 if (track->init ()) {
2592 track->set_strict_io (true);
2595 track->use_new_diskstream();
2597 BOOST_MARK_TRACK (track);
2600 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2601 if (track->input()->ensure_io (input, false, this)) {
2602 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2606 if (track->output()->ensure_io (output, false, this)) {
2607 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2612 track->non_realtime_input_change();
2615 route_group->add (track);
2618 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2620 new_routes.push_back (track);
2621 ret.push_back (track);
2624 catch (failed_constructor &err) {
2625 error << _("Session: could not create new midi track.") << endmsg;
2629 catch (AudioEngine::PortRegistrationFailure& pfe) {
2631 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;
2639 if (!new_routes.empty()) {
2640 StateProtector sp (this);
2641 if (Profile->get_trx()) {
2642 add_routes (new_routes, false, false, false, order);
2644 add_routes (new_routes, true, true, false, order);
2648 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2649 PluginPtr plugin = instrument->load (*this);
2651 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2655 plugin->load_preset (*pset);
2657 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2659 pi->set_strict_io (true);
2662 (*r)->add_processor (pi, PreFader);
2664 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2665 (*r)->move_instrument_down (false);
2675 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2676 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2677 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2680 uint32_t bus_id = 0;
2684 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2687 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2688 error << "cannot find name for new midi bus" << endmsg;
2693 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2700 bus->set_strict_io (true);
2703 BOOST_MARK_ROUTE(bus);
2706 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2708 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2709 error << _("cannot configure new midi bus input") << endmsg;
2714 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2715 error << _("cannot configure new midi bus output") << endmsg;
2721 route_group->add (bus);
2724 bus->add_internal_return ();
2725 ret.push_back (bus);
2728 catch (failed_constructor &err) {
2729 error << _("Session: could not create new audio route.") << endmsg;
2733 catch (AudioEngine::PortRegistrationFailure& pfe) {
2734 error << pfe.what() << endmsg;
2744 StateProtector sp (this);
2745 add_routes (ret, false, false, false, order);
2748 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2749 PluginPtr plugin = instrument->load (*this);
2751 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2755 plugin->load_preset (*pset);
2757 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2759 pi->set_strict_io (true);
2762 (*r)->add_processor (pi, PreFader);
2764 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2765 (*r)->move_instrument_down (false);
2777 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2779 boost::shared_ptr<Route> midi_track (wmt.lock());
2785 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2787 if (change.after.n_audio() <= change.before.n_audio()) {
2791 /* new audio ports: make sure the audio goes somewhere useful,
2792 * unless the user has no-auto-connect selected.
2794 * The existing ChanCounts don't matter for this call as they are only
2795 * to do with matching input and output indices, and we are only changing
2798 auto_connect_route (midi_track, false, ChanCount(), change.before);
2802 #ifdef USE_TRACKS_CODE_FEATURES
2805 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2807 return route1->remote_control_id() < route2->remote_control_id();
2811 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2813 // it is not allowed to perform connection
2814 if (!IO::connecting_legal) {
2818 // if we are deleting routes we will call this once at the end
2819 if (_route_deletion_in_progress) {
2823 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2829 // We need to disconnect the route's inputs and outputs first
2830 // basing on autoconnect configuration
2831 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2832 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2834 ChanCount existing_inputs;
2835 ChanCount existing_outputs;
2836 count_existing_track_channels (existing_inputs, existing_outputs);
2838 //ChanCount inputs = ChanCount::ZERO;
2839 //ChanCount outputs = ChanCount::ZERO;
2841 RouteList existing_routes = *routes.reader ();
2842 existing_routes.sort (compare_routes_by_remote_id);
2845 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2847 vector<string> physinputs;
2848 vector<string> physoutputs;
2850 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2851 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2853 uint32_t input_n = 0;
2854 uint32_t output_n = 0;
2855 RouteList::iterator rIter = existing_routes.begin();
2856 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2857 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2858 for (; rIter != existing_routes.end(); ++rIter) {
2859 if (*rIter == _master_out || *rIter == _monitor_out ) {
2863 if (current_output_auto_connection == AutoConnectPhysical) {
2864 (*rIter)->amp()->deactivate();
2865 } else if (current_output_auto_connection == AutoConnectMaster) {
2866 (*rIter)->amp()->activate();
2869 if (reconnectIputs) {
2870 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2872 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2874 if (current_input_auto_connection & AutoConnectPhysical) {
2876 if ( input_n == physinputs.size() ) {
2880 string port = physinputs[input_n];
2882 if (port.empty() ) {
2883 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2886 //GZ: check this; could be heavy
2887 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2893 if (reconnectOutputs) {
2895 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2896 if (current_output_auto_connection & AutoConnectPhysical) {
2898 //GZ: check this; could be heavy
2899 (*rIter)->output()->disconnect (this);
2900 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2902 //GZ: check this; could be heavy
2903 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2905 } else if (current_output_auto_connection & AutoConnectMaster){
2907 if (!reconnect_master) {
2911 //GZ: check this; could be heavy
2912 (*rIter)->output()->disconnect (this);
2915 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2916 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2918 error << error << "Master bus is not available" << endmsg;
2923 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2924 if (current_output_auto_connection & AutoConnectPhysical) {
2926 if ( output_n == physoutputs.size() ) {
2930 string port = physoutputs[output_n];
2932 if (port.empty() ) {
2933 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2936 //GZ: check this; could be heavy
2937 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2940 } else if (current_output_auto_connection & AutoConnectMaster) {
2942 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2946 // connect to master bus
2947 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2949 if (port.empty() ) {
2950 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2954 //GZ: check this; could be heavy
2955 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2962 _master_out->output()->disconnect (this);
2963 auto_connect_master_bus ();
2968 session_routes_reconnected (); /* EMIT SIGNAL */
2972 Session::reconnect_midi_scene_ports(bool inputs)
2976 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2978 scene_in_ptr->disconnect_all ();
2980 std::vector<EngineStateController::MidiPortState> midi_port_states;
2981 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2983 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2985 for (; state_iter != midi_port_states.end(); ++state_iter) {
2986 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2987 scene_in_ptr->connect (state_iter->name);
2994 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2996 if (scene_out_ptr ) {
2997 scene_out_ptr->disconnect_all ();
2999 std::vector<EngineStateController::MidiPortState> midi_port_states;
3000 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
3002 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
3004 for (; state_iter != midi_port_states.end(); ++state_iter) {
3005 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
3006 scene_out_ptr->connect (state_iter->name);
3014 Session::reconnect_mtc_ports ()
3016 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
3022 mtc_in_ptr->disconnect_all ();
3024 std::vector<EngineStateController::MidiPortState> midi_port_states;
3025 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
3027 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
3029 for (; state_iter != midi_port_states.end(); ++state_iter) {
3030 if (state_iter->available && state_iter->mtc_in) {
3031 mtc_in_ptr->connect (state_iter->name);
3035 if (!_midi_ports->mtc_input_port ()->connected () &&
3036 config.get_external_sync () &&
3037 (Config->get_sync_source () == MTC) ) {
3038 config.set_external_sync (false);
3041 if ( ARDOUR::Profile->get_trx () ) {
3042 // Tracks need this signal to update timecode_source_dropdown
3043 MtcOrLtcInputPortChanged (); //emit signal
3048 Session::reconnect_mmc_ports(bool inputs)
3050 if (inputs ) { // get all enabled midi input ports
3052 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
3054 mmc_in_ptr->disconnect_all ();
3055 std::vector<std::string> enabled_midi_inputs;
3056 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3058 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3060 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3061 mmc_in_ptr->connect (*port_iter);
3065 } else { // get all enabled midi output ports
3067 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3069 mmc_out_ptr->disconnect_all ();
3070 std::vector<std::string> enabled_midi_outputs;
3071 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3073 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3075 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3076 mmc_out_ptr->connect (*port_iter);
3085 Session::ensure_stripable_sort_order ()
3088 get_stripables (sl);
3089 sl.sort (Stripable::Sorter ());
3091 bool change = false;
3092 PresentationInfo::order_t order = 0;
3094 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3095 boost::shared_ptr<Stripable> s (*si);
3096 if (s->is_monitor () || s->is_auditioner ()) {
3099 if (order != s->presentation_info().order()) {
3100 s->set_presentation_order (order);
3109 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3111 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3113 if (first_new_order == PresentationInfo::max_order) {
3114 /* adding at end, no worries */
3118 /* create a gap in the presentation info to accomodate @param how_many
3122 get_stripables (sl);
3124 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3125 boost::shared_ptr<Stripable> s (*si);
3127 if (s->presentation_info().special (false)) {
3131 if (!s->presentation_info().order_set()) {
3135 if (s->presentation_info().order () >= first_new_order) {
3136 s->set_presentation_order (s->presentation_info().order () + how_many);
3141 /** Caller must not hold process lock
3142 * @param name_template string to use for the start of the name, or "" to use "Audio".
3144 list< boost::shared_ptr<AudioTrack> >
3145 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3146 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3150 uint32_t track_id = 0;
3152 RouteList new_routes;
3153 list<boost::shared_ptr<AudioTrack> > ret;
3155 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3156 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3160 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3161 error << "cannot find name for new audio track" << endmsg;
3165 boost::shared_ptr<AudioTrack> track;
3168 track.reset (new AudioTrack (*this, track_name, mode));
3170 if (track->init ()) {
3174 if (Profile->get_mixbus ()) {
3175 track->set_strict_io (true);
3178 if (ARDOUR::Profile->get_trx ()) {
3179 // TRACKS considers it's not a USE CASE, it's
3180 // a piece of behavior of the session model:
3182 // Gain for a newly created route depends on
3183 // the current output_auto_connect mode:
3185 // 0 for Stereo Out mode
3187 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3188 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3192 track->use_new_diskstream();
3194 BOOST_MARK_TRACK (track);
3197 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3199 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3200 error << string_compose (
3201 _("cannot configure %1 in/%2 out configuration for new audio track"),
3202 input_channels, output_channels)
3207 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3208 error << string_compose (
3209 _("cannot configure %1 in/%2 out configuration for new audio track"),
3210 input_channels, output_channels)
3217 route_group->add (track);
3220 track->non_realtime_input_change();
3222 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3224 new_routes.push_back (track);
3225 ret.push_back (track);
3228 catch (failed_constructor &err) {
3229 error << _("Session: could not create new audio track.") << endmsg;
3233 catch (AudioEngine::PortRegistrationFailure& pfe) {
3235 error << pfe.what() << endmsg;
3243 if (!new_routes.empty()) {
3244 StateProtector sp (this);
3245 if (Profile->get_trx()) {
3246 add_routes (new_routes, false, false, false, order);
3248 add_routes (new_routes, true, true, false, order);
3255 /** Caller must not hold process lock.
3256 * @param name_template string to use for the start of the name, or "" to use "Bus".
3259 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3260 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3263 uint32_t bus_id = 0;
3267 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3270 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3271 error << "cannot find name for new audio bus" << endmsg;
3276 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3282 if (Profile->get_mixbus ()) {
3283 bus->set_strict_io (true);
3286 BOOST_MARK_ROUTE(bus);
3289 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3291 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3292 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3293 input_channels, output_channels)
3299 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3300 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3301 input_channels, output_channels)
3308 route_group->add (bus);
3311 bus->add_internal_return ();
3312 ret.push_back (bus);
3315 catch (failed_constructor &err) {
3316 error << _("Session: could not create new audio route.") << endmsg;
3320 catch (AudioEngine::PortRegistrationFailure& pfe) {
3321 error << pfe.what() << endmsg;
3331 StateProtector sp (this);
3332 if (Profile->get_trx()) {
3333 add_routes (ret, false, false, false, order);
3335 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3344 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3345 PlaylistDisposition pd)
3349 if (!tree.read (template_path.c_str())) {
3353 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3357 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3360 uint32_t number = 0;
3361 const uint32_t being_added = how_many;
3362 /* This will prevent the use of any existing XML-provided PBD::ID
3365 Stateful::ForceIDRegeneration force_ids;
3366 IO::disable_connecting ();
3370 /* We're going to modify the node contents a bit so take a
3371 * copy. The node may be re-used when duplicating more than once.
3374 XMLNode node_copy (node);
3379 if (!name_base.empty()) {
3381 /* if we're adding more than one routes, force
3382 * all the names of the new routes to be
3383 * numbered, via the final parameter.
3386 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3387 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3393 string const route_name = node_copy.property(X_("name"))->value ();
3395 /* generate a new name by adding a number to the end of the template name */
3396 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3397 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3398 abort(); /*NOTREACHED*/
3402 /* set this name in the XML description that we are about to use */
3404 if (pd == CopyPlaylist) {
3405 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3407 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3408 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3409 // Use same name as Route::set_name_in_state so playlist copy
3410 // is picked up when creating the Route in XMLRouteFactory below
3411 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3412 playlist->reset_shares ();
3414 } else if (pd == SharePlaylist) {
3415 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3417 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3418 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3419 playlist->share_with ((node_copy.property (X_("id")))->value());
3423 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3425 Route::set_name_in_state (node_copy, name, rename_playlist);
3427 /* trim bitslots from listen sends so that new ones are used */
3428 XMLNodeList children = node_copy.children ();
3429 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3430 if ((*i)->name() == X_("Processor")) {
3431 /* ForceIDRegeneration does not catch the following */
3432 XMLProperty const * role = (*i)->property (X_("role"));
3433 XMLProperty const * type = (*i)->property (X_("type"));
3434 if (role && role->value() == X_("Aux")) {
3435 /* check if the target bus exists.
3436 * we should not save aux-sends in templates.
3438 XMLProperty const * target = (*i)->property (X_("target"));
3440 (*i)->set_property ("type", "dangling-aux-send");
3443 boost::shared_ptr<Route> r = route_by_id (target->value());
3444 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3445 (*i)->set_property ("type", "dangling-aux-send");
3449 if (role && role->value() == X_("Listen")) {
3450 (*i)->remove_property (X_("bitslot"));
3452 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3453 Delivery::Role xrole;
3454 uint32_t bitslot = 0;
3455 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3456 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3457 (*i)->remove_property (X_("bitslot"));
3458 (*i)->remove_property (X_("name"));
3459 (*i)->set_property ("bitslot", bitslot);
3460 (*i)->set_property ("name", name);
3462 else if (type && type->value() == X_("intreturn")) {
3463 (*i)->remove_property (X_("bitslot"));
3464 (*i)->set_property ("ignore-bitslot", "1");
3466 else if (type && type->value() == X_("return")) {
3467 // Return::set_state() generates a new one
3468 (*i)->remove_property (X_("bitslot"));
3470 else if (type && type->value() == X_("port")) {
3471 // PortInsert::set_state() handles the bitslot
3472 (*i)->remove_property (X_("bitslot"));
3473 (*i)->set_property ("ignore-name", "1");
3478 /* new routes start off unsoloed to avoid issues related to
3479 upstream / downstream buses. */
3480 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3482 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3485 error << _("Session: cannot create track/bus from template description") << endmsg;
3489 if (boost::dynamic_pointer_cast<Track>(route)) {
3490 /* force input/output change signals so that the new diskstream
3491 picks up the configuration of the route. During session
3492 loading this normally happens in a different way.
3495 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3497 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3498 change.after = route->input()->n_ports();
3499 route->input()->changed (change, this);
3500 change.after = route->output()->n_ports();
3501 route->output()->changed (change, this);
3504 ret.push_back (route);
3507 catch (failed_constructor &err) {
3508 error << _("Session: could not create new route from template") << endmsg;
3512 catch (AudioEngine::PortRegistrationFailure& pfe) {
3513 error << pfe.what() << endmsg;
3522 StateProtector sp (this);
3523 if (Profile->get_trx()) {
3524 add_routes (ret, false, false, false, insert_at);
3526 add_routes (ret, true, true, false, insert_at);
3528 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 (true);
3548 update_latency (false);
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 /* auditioner and monitor routes are not part of the order */
3590 assert (n_routes > 0);
3594 assert (n_routes > 0);
3599 PresentationInfo::ChangeSuspender cs;
3600 ensure_route_presentation_info_gap (order, new_routes.size());
3602 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3604 boost::weak_ptr<Route> wpr (*x);
3605 boost::shared_ptr<Route> r (*x);
3607 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3608 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3609 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3611 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3612 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3613 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3615 if (r->is_master()) {
3619 if (r->is_monitor()) {
3623 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3625 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3626 track_playlist_changed (boost::weak_ptr<Track> (tr));
3627 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3629 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3631 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3632 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3633 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3637 if (!r->presentation_info().special (false)) {
3639 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3641 /* presentation info order may already have been set from XML */
3643 if (!r->presentation_info().order_set()) {
3644 if (order == PresentationInfo::max_order) {
3645 /* just add to the end */
3646 r->set_presentation_order (n_routes + added);
3647 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3649 r->set_presentation_order (order + added);
3650 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3653 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3657 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3658 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3659 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3661 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3663 r->presentation_info().order(),
3664 enum_2_string (r->presentation_info().flags()),
3665 r->presentation_info()));
3669 if (input_auto_connect || output_auto_connect) {
3670 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3671 existing_inputs += r->n_inputs();
3672 existing_outputs += r->n_outputs();
3677 ensure_stripable_sort_order ();
3680 if (_monitor_out && IO::connecting_legal) {
3681 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3683 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3684 if ((*x)->is_monitor()) {
3686 } else if ((*x)->is_master()) {
3689 (*x)->enable_monitor_send ();
3694 reassign_track_numbers ();
3698 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3700 boost::shared_ptr<RouteList> r = routes.reader ();
3701 boost::shared_ptr<Send> s;
3703 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3704 if ((s = (*i)->internal_send_for (dest)) != 0) {
3705 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3711 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3713 boost::shared_ptr<RouteList> r = routes.reader ();
3714 boost::shared_ptr<Send> s;
3716 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3717 if ((s = (*i)->internal_send_for (dest)) != 0) {
3718 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3724 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3726 boost::shared_ptr<RouteList> r = routes.reader ();
3727 boost::shared_ptr<Send> s;
3729 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3730 if ((s = (*i)->internal_send_for (dest)) != 0) {
3731 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3736 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3738 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3740 boost::shared_ptr<RouteList> r = routes.reader ();
3741 boost::shared_ptr<RouteList> t (new RouteList);
3743 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3744 /* no MIDI sends because there are no MIDI busses yet */
3745 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3750 add_internal_sends (dest, p, t);
3754 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3756 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3757 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3762 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3764 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3768 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3770 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3774 if (!dest->internal_return()) {
3775 dest->add_internal_return ();
3778 sender->add_aux_send (dest, before);
3784 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3786 bool mute_changed = false;
3787 bool send_selected = false;
3789 { // RCU Writer scope
3790 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3791 RCUWriter<RouteList> writer (routes);
3792 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3794 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3796 if (_selection->selected (*iter)) {
3797 send_selected = true;
3800 if (*iter == _master_out) {
3804 /* speed up session deletion, don't do the solo dance */
3805 if (0 == (_state_of_the_state & Deletion)) {
3806 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3809 if ((*iter)->mute_control()->muted ()) {
3810 mute_changed = true;
3815 /* deleting the master out seems like a dumb
3816 idea, but its more of a UI policy issue
3820 if (*iter == _master_out) {
3821 _master_out = boost::shared_ptr<Route> ();
3824 if (*iter == _monitor_out) {
3825 _monitor_out.reset ();
3828 // We need to disconnect the route's inputs and outputs
3830 (*iter)->input()->disconnect (0);
3831 (*iter)->output()->disconnect (0);
3833 /* if the route had internal sends sending to it, remove them */
3834 if ((*iter)->internal_return()) {
3836 boost::shared_ptr<RouteList> r = routes.reader ();
3837 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3838 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3840 (*i)->remove_processor (s);
3845 /* if the monitoring section had a pointer to this route, remove it */
3846 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3847 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3848 ProcessorChangeBlocker pcb (this, false);
3849 (*iter)->remove_aux_or_listen (_monitor_out);
3852 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3853 if (mt && mt->step_editing()) {
3854 if (_step_editors > 0) {
3860 /* writer goes out of scope, forces route list update */
3862 } // end of RCU Writer scope
3865 MuteChanged (); /* EMIT SIGNAL */
3868 update_route_solo_state ();
3869 update_latency_compensation ();
3872 /* Re-sort routes to remove the graph's current references to the one that is
3873 * going away, then flush old references out of the graph.
3874 * Wave Tracks: reconnect routes
3877 #ifdef USE_TRACKS_CODE_FEATURES
3878 reconnect_existing_routes(true, false);
3880 routes.flush (); // maybe unsafe, see below.
3884 if (_process_graph && !(_state_of_the_state & Deletion)) {
3885 _process_graph->clear_other_chain ();
3888 /* get rid of it from the dead wood collection in the route list manager */
3889 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3893 /* remove these routes from the selection if appropriate, and signal
3894 * the change *before* we call DropReferences for them.
3897 if (send_selected && !deletion_in_progress()) {
3898 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3899 _selection->remove_stripable_by_id ((*iter)->id());
3902 pc.add (Properties::selected);
3903 PresentationInfo::Change (pc);
3906 /* try to cause everyone to drop their references
3907 * and unregister ports from the backend
3910 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3911 (*iter)->drop_references ();
3914 if (deletion_in_progress()) {
3919 pc.add (Properties::order);
3920 PresentationInfo::Change (pc);
3922 /* save the new state of the world */
3924 if (save_state (_current_snapshot_name)) {
3925 save_history (_current_snapshot_name);
3928 update_route_record_state ();
3932 Session::remove_route (boost::shared_ptr<Route> route)
3934 boost::shared_ptr<RouteList> rl (new RouteList);
3935 rl->push_back (route);
3940 Session::route_mute_changed ()
3942 MuteChanged (); /* EMIT SIGNAL */
3947 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3949 boost::shared_ptr<Route> route (wpr.lock());
3955 assert (Config->get_solo_control_is_listen_control());
3957 if (route->solo_control()->soloed_by_self_or_masters()) {
3959 if (Config->get_exclusive_solo()) {
3961 RouteGroup* rg = route->route_group ();
3962 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3964 boost::shared_ptr<RouteList> r = routes.reader ();
3966 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3967 if ((*i) == route) {
3968 /* already changed */
3972 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3973 /* route does not get solo propagated to it */
3977 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3978 /* this route is a part of the same solo group as the route
3979 * that was changed. Changing that route did change or will
3980 * change all group members appropriately, so we can ignore it
3985 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3991 } else if (_listen_cnt > 0) {
3998 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
4000 boost::shared_ptr<Route> route (wpr.lock());
4006 bool send_changed = false;
4008 if (route->solo_isolate_control()->solo_isolated()) {
4009 if (_solo_isolated_cnt == 0) {
4010 send_changed = true;
4012 _solo_isolated_cnt++;
4013 } else if (_solo_isolated_cnt > 0) {
4014 _solo_isolated_cnt--;
4015 if (_solo_isolated_cnt == 0) {
4016 send_changed = true;
4021 IsolatedChanged (); /* EMIT SIGNAL */
4026 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
4028 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
4030 boost::shared_ptr<Route> route (wpr.lock());
4036 if (Config->get_solo_control_is_listen_control()) {
4037 route_listen_changed (group_override, wpr);
4041 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()));
4043 if (route->solo_control()->transitioned_into_solo() == 0) {
4044 /* route solo changed by upstream/downstream or clear all solo state; not interesting
4047 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()));
4051 boost::shared_ptr<RouteList> r = routes.reader ();
4052 int32_t delta = route->solo_control()->transitioned_into_solo ();
4054 /* the route may be a member of a group that has shared-solo
4055 * semantics. If so, then all members of that group should follow the
4056 * solo of the changed route. But ... this is optional, controlled by a
4057 * Controllable::GroupControlDisposition.
4059 * The first argument to the signal that this method is connected to is the
4060 * GroupControlDisposition value that was used to change solo.
4062 * If the solo change was done with group semantics (either InverseGroup
4063 * (force the entire group to change even if the group shared solo is
4064 * disabled) or UseGroup (use the group, which may or may not have the
4065 * shared solo property enabled)) then as we propagate the change to
4066 * the entire session we should IGNORE THE GROUP that the changed route
4070 RouteGroup* rg = route->route_group ();
4071 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4073 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4075 if (delta == 1 && Config->get_exclusive_solo()) {
4077 /* new solo: disable all other solos, but not the group if its solo-enabled */
4079 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4081 if ((*i) == route) {
4082 /* already changed */
4086 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4087 /* route does not get solo propagated to it */
4091 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4092 /* this route is a part of the same solo group as the route
4093 * that was changed. Changing that route did change or will
4094 * change all group members appropriately, so we can ignore it
4100 (*i)->solo_control()->set_value (0.0, group_override);
4104 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4106 RouteList uninvolved;
4108 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4110 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4111 bool via_sends_only;
4112 bool in_signal_flow;
4114 if ((*i) == route) {
4115 /* already changed */
4119 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4120 /* route does not get solo propagated to it */
4121 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(),
4126 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4127 /* this route is a part of the same solo group as the route
4128 * that was changed. Changing that route did change or will
4129 * change all group members appropriately, so we can ignore it
4135 in_signal_flow = false;
4137 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4139 if ((*i)->feeds (route, &via_sends_only)) {
4140 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4141 if (!via_sends_only) {
4142 if (!route->soloed_by_others_upstream()) {
4143 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4145 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4148 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4150 in_signal_flow = true;
4152 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4155 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4157 if (route->feeds (*i, &via_sends_only)) {
4158 /* propagate solo upstream only if routing other than
4159 sends is involved, but do consider the other route
4160 (*i) to be part of the signal flow even if only
4163 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4167 route->soloed_by_others_downstream(),
4168 route->soloed_by_others_upstream()));
4169 if (!via_sends_only) {
4170 //NB. Triggers Invert Push, which handles soloed by downstream
4171 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4172 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4174 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4176 in_signal_flow = true;
4178 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4181 if (!in_signal_flow) {
4182 uninvolved.push_back (*i);
4186 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4188 /* now notify that the mute state of the routes not involved in the signal
4189 pathway of the just-solo-changed route may have altered.
4192 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4193 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4194 (*i)->act_on_mute ();
4195 /* Session will emit SoloChanged() after all solo changes are
4196 * complete, which should be used by UIs to update mute status
4202 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4204 /* now figure out if anything that matters is soloed (or is "listening")*/
4206 bool something_soloed = false;
4207 bool something_listening = false;
4208 uint32_t listeners = 0;
4209 uint32_t isolated = 0;
4212 r = routes.reader();
4215 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4216 if ((*i)->can_solo()) {
4217 if (Config->get_solo_control_is_listen_control()) {
4218 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4220 something_listening = true;
4223 (*i)->set_listen (false);
4224 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4225 something_soloed = true;
4230 if ((*i)->solo_isolate_control()->solo_isolated()) {
4235 if (something_soloed != _non_soloed_outs_muted) {
4236 _non_soloed_outs_muted = something_soloed;
4237 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4240 if (something_listening != _listening) {
4241 _listening = something_listening;
4242 SoloActive (_listening);
4245 _listen_cnt = listeners;
4247 if (isolated != _solo_isolated_cnt) {
4248 _solo_isolated_cnt = isolated;
4249 IsolatedChanged (); /* EMIT SIGNAL */
4252 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4253 something_soloed, listeners, isolated));
4256 SoloChanged (); /* EMIT SIGNAL */
4261 Session::muted () const
4263 // TODO consider caching the value on every MuteChanged signal,
4264 // Note that API users may also subscribe to MuteChanged and hence
4265 // this method needs to be called first.
4268 get_stripables (all);
4269 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4270 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4273 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4274 if (r && !r->active()) {
4277 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4278 if (mc && mc->muted ()) {
4286 std::vector<boost::weak_ptr<AutomationControl> >
4287 Session::cancel_all_mute ()
4290 get_stripables (all);
4291 std::vector<boost::weak_ptr<AutomationControl> > muted;
4292 boost::shared_ptr<ControlList> cl (new ControlList);
4293 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4294 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4297 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4298 if (r && !r->active()) {
4301 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4302 if (ac && ac->get_value () > 0) {
4304 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4307 if (!cl->empty ()) {
4308 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4314 Session::get_stripables (StripableList& sl) const
4316 boost::shared_ptr<RouteList> r = routes.reader ();
4317 sl.insert (sl.end(), r->begin(), r->end());
4319 VCAList v = _vca_manager->vcas ();
4320 sl.insert (sl.end(), v.begin(), v.end());
4324 Session::get_stripables () const
4327 Session::get_stripables (rv);
4328 rv.sort (Stripable::Sorter ());
4332 boost::shared_ptr<RouteList>
4333 Session::get_routes_with_internal_returns() const
4335 boost::shared_ptr<RouteList> r = routes.reader ();
4336 boost::shared_ptr<RouteList> rl (new RouteList);
4338 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4339 if ((*i)->internal_return ()) {
4347 Session::io_name_is_legal (const std::string& name) const
4349 boost::shared_ptr<RouteList> r = routes.reader ();
4351 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4352 if (name == reserved->first) {
4353 if (!route_by_name (reserved->first)) {
4354 /* first instance of a reserved name is allowed for some */
4355 return reserved->second;
4357 /* all other instances of a reserved name are not allowed */
4362 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4363 if ((*i)->name() == name) {
4367 if ((*i)->has_io_processor_named (name)) {
4376 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4379 vector<string> connections;
4381 /* if we are passed only a single route and we're not told to turn
4382 * others off, then just do the simple thing.
4385 if (flip_others == false && rl->size() == 1) {
4386 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4388 mt->set_input_active (onoff);
4393 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4395 PortSet& ps ((*rt)->input()->ports());
4397 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4398 p->get_connections (connections);
4401 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4402 routes_using_input_from (*s, rl2);
4405 /* scan all relevant routes to see if others are on or off */
4407 bool others_are_already_on = false;
4409 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4411 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4417 if ((*r) != (*rt)) {
4418 if (mt->input_active()) {
4419 others_are_already_on = true;
4422 /* this one needs changing */
4423 mt->set_input_active (onoff);
4429 /* globally reverse other routes */
4431 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4432 if ((*r) != (*rt)) {
4433 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4435 mt->set_input_active (!others_are_already_on);
4444 Session::routes_using_input_from (const string& str, RouteList& rl)
4446 boost::shared_ptr<RouteList> r = routes.reader();
4448 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4449 if ((*i)->input()->connected_to (str)) {
4455 boost::shared_ptr<Route>
4456 Session::route_by_name (string name) const
4458 boost::shared_ptr<RouteList> r = routes.reader ();
4460 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4461 if ((*i)->name() == name) {
4466 return boost::shared_ptr<Route> ((Route*) 0);
4469 boost::shared_ptr<Route>
4470 Session::route_by_id (PBD::ID id) const
4472 boost::shared_ptr<RouteList> r = routes.reader ();
4474 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4475 if ((*i)->id() == id) {
4480 return boost::shared_ptr<Route> ((Route*) 0);
4484 boost::shared_ptr<Stripable>
4485 Session::stripable_by_id (PBD::ID id) const
4488 get_stripables (sl);
4490 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4491 if ((*s)->id() == id) {
4496 return boost::shared_ptr<Stripable>();
4499 boost::shared_ptr<Processor>
4500 Session::processor_by_id (PBD::ID id) const
4502 boost::shared_ptr<RouteList> r = routes.reader ();
4504 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4505 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4511 return boost::shared_ptr<Processor> ();
4514 boost::shared_ptr<Track>
4515 Session::track_by_diskstream_id (PBD::ID id) const
4517 boost::shared_ptr<RouteList> r = routes.reader ();
4519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4520 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4521 if (t && t->using_diskstream_id (id)) {
4526 return boost::shared_ptr<Track> ();
4529 boost::shared_ptr<Route>
4530 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4532 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4535 boost::shared_ptr<Stripable>
4536 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4539 PresentationInfo::order_t match_cnt = 0;
4541 get_stripables (sl);
4542 sl.sort (Stripable::Sorter());
4544 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4546 if ((*s)->presentation_info().hidden()) {
4547 /* if the caller didn't explicitly ask for hidden
4548 stripables, ignore hidden ones. This matches
4549 the semantics of the pre-PresentationOrder
4550 "get by RID" logic of Ardour 4.x and earlier.
4552 XXX at some point we should likely reverse
4553 the logic of the flags, because asking for "the
4554 hidden stripables" is not going to be common,
4555 whereas asking for visible ones is normal.
4558 if (! (flags & PresentationInfo::Hidden)) {
4563 if ((*s)->presentation_info().flag_match (flags)) {
4564 if (match_cnt++ == n) {
4570 /* there is no nth stripable that matches the given flags */
4571 return boost::shared_ptr<Stripable>();
4574 boost::shared_ptr<Route>
4575 Session::route_by_selected_count (uint32_t id) const
4577 RouteList r (*(routes.reader ()));
4578 r.sort (Stripable::Sorter());
4580 RouteList::iterator i;
4582 for (i = r.begin(); i != r.end(); ++i) {
4583 if ((*i)->is_selected()) {
4591 return boost::shared_ptr<Route> ();
4595 Session::reassign_track_numbers ()
4599 RouteList r (*(routes.reader ()));
4600 r.sort (Stripable::Sorter());
4602 StateProtector sp (this);
4604 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4605 if (boost::dynamic_pointer_cast<Track> (*i)) {
4606 (*i)->set_track_number(++tn);
4608 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4609 (*i)->set_track_number(--bn);
4612 const uint32_t decimals = ceilf (log10f (tn + 1));
4613 const bool decimals_changed = _track_number_decimals != decimals;
4614 _track_number_decimals = decimals;
4616 if (decimals_changed && config.get_track_name_number ()) {
4617 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4618 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4620 t->resync_track_name();
4623 // trigger GUI re-layout
4624 config.ParameterChanged("track-name-number");
4628 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4629 boost::shared_ptr<RouteList> rl = routes.reader ();
4630 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4631 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4639 Session::playlist_region_added (boost::weak_ptr<Region> w)
4641 boost::shared_ptr<Region> r = w.lock ();
4646 /* These are the operations that are currently in progress... */
4647 list<GQuark> curr = _current_trans_quarks;
4650 /* ...and these are the operations during which we want to update
4651 the session range location markers.
4654 ops.push_back (Operations::capture);
4655 ops.push_back (Operations::paste);
4656 ops.push_back (Operations::duplicate_region);
4657 ops.push_back (Operations::insert_file);
4658 ops.push_back (Operations::insert_region);
4659 ops.push_back (Operations::drag_region_brush);
4660 ops.push_back (Operations::region_drag);
4661 ops.push_back (Operations::selection_grab);
4662 ops.push_back (Operations::region_fill);
4663 ops.push_back (Operations::fill_selection);
4664 ops.push_back (Operations::create_region);
4665 ops.push_back (Operations::region_copy);
4666 ops.push_back (Operations::fixed_time_region_copy);
4669 /* See if any of the current operations match the ones that we want */
4671 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4673 /* If so, update the session range markers */
4675 maybe_update_session_range (r->position (), r->last_frame ());
4679 /** Update the session range markers if a is before the current start or
4680 * b is after the current end.
4683 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4685 if (_state_of_the_state & Loading) {
4689 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4691 if (_session_range_location == 0) {
4693 set_session_range_location (a, b + session_end_marker_shift_samples);
4697 if (a < _session_range_location->start()) {
4698 _session_range_location->set_start (a);
4701 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4702 _session_range_location->set_end (b);
4708 Session::set_end_is_free (bool yn)
4710 _session_range_end_is_free = yn;
4714 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4716 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4717 maybe_update_session_range (i->to, i->to + i->length);
4722 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4724 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4725 maybe_update_session_range (i->from, i->to);
4729 /* Region management */
4731 boost::shared_ptr<Region>
4732 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4734 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4735 RegionFactory::RegionMap::const_iterator i;
4736 boost::shared_ptr<Region> region;
4738 Glib::Threads::Mutex::Lock lm (region_lock);
4740 for (i = regions.begin(); i != regions.end(); ++i) {
4744 if (region->whole_file()) {
4746 if (child->source_equivalent (region)) {
4752 return boost::shared_ptr<Region> ();
4756 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4758 set<boost::shared_ptr<Region> > relevant_regions;
4760 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4761 RegionFactory::get_regions_using_source (*s, relevant_regions);
4764 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4765 set<boost::shared_ptr<Region> >::iterator tmp;
4770 playlists->destroy_region (*r);
4771 RegionFactory::map_remove (*r);
4773 (*r)->drop_sources ();
4774 (*r)->drop_references ();
4776 relevant_regions.erase (r);
4781 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4784 Glib::Threads::Mutex::Lock ls (source_lock);
4785 /* remove from the main source list */
4786 sources.erase ((*s)->id());
4789 (*s)->mark_for_remove ();
4790 (*s)->drop_references ();
4799 Session::remove_last_capture ()
4801 list<boost::shared_ptr<Source> > srcs;
4803 boost::shared_ptr<RouteList> rl = routes.reader ();
4804 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4805 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4810 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4813 srcs.insert (srcs.end(), l.begin(), l.end());
4818 destroy_sources (srcs);
4820 save_state (_current_snapshot_name);
4825 /* Source Management */
4828 Session::add_source (boost::shared_ptr<Source> source)
4830 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4831 pair<SourceMap::iterator,bool> result;
4833 entry.first = source->id();
4834 entry.second = source;
4837 Glib::Threads::Mutex::Lock lm (source_lock);
4838 result = sources.insert (entry);
4841 if (result.second) {
4843 /* yay, new source */
4845 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4848 if (!fs->within_session()) {
4849 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4855 boost::shared_ptr<AudioFileSource> afs;
4857 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4858 if (Config->get_auto_analyse_audio()) {
4859 Analyser::queue_source_for_analysis (source, false);
4863 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4868 Session::remove_source (boost::weak_ptr<Source> src)
4870 if (_state_of_the_state & Deletion) {
4874 SourceMap::iterator i;
4875 boost::shared_ptr<Source> source = src.lock();
4882 Glib::Threads::Mutex::Lock lm (source_lock);
4884 if ((i = sources.find (source->id())) != sources.end()) {
4889 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4891 /* save state so we don't end up with a session file
4892 referring to non-existent sources.
4895 save_state (_current_snapshot_name);
4899 boost::shared_ptr<Source>
4900 Session::source_by_id (const PBD::ID& id)
4902 Glib::Threads::Mutex::Lock lm (source_lock);
4903 SourceMap::iterator i;
4904 boost::shared_ptr<Source> source;
4906 if ((i = sources.find (id)) != sources.end()) {
4913 boost::shared_ptr<AudioFileSource>
4914 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4916 /* Restricted to audio files because only audio sources have channel
4920 Glib::Threads::Mutex::Lock lm (source_lock);
4922 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4923 boost::shared_ptr<AudioFileSource> afs
4924 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4926 if (afs && afs->path() == path && chn == afs->channel()) {
4931 return boost::shared_ptr<AudioFileSource>();
4934 boost::shared_ptr<MidiSource>
4935 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4937 /* Restricted to MIDI files because audio sources require a channel
4938 for unique identification, in addition to a path.
4941 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4942 if (need_source_lock) {
4946 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4947 boost::shared_ptr<MidiSource> ms
4948 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4949 boost::shared_ptr<FileSource> fs
4950 = boost::dynamic_pointer_cast<FileSource>(s->second);
4952 if (ms && fs && fs->path() == path) {
4957 return boost::shared_ptr<MidiSource>();
4961 Session::count_sources_by_origin (const string& path)
4964 Glib::Threads::Mutex::Lock lm (source_lock);
4966 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4967 boost::shared_ptr<FileSource> fs
4968 = boost::dynamic_pointer_cast<FileSource>(i->second);
4970 if (fs && fs->origin() == path) {
4979 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4981 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4982 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4984 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4989 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4991 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4993 if (Glib::path_is_absolute (filepath)) {
4995 /* rip the session dir from the audiofile source */
4997 string session_path;
4998 bool in_another_session = true;
5000 if (filepath.find (interchange_dir_string) != string::npos) {
5002 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
5003 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
5004 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
5005 session_path = Glib::path_get_dirname (session_path); /* now has session path */
5007 /* see if it is within our session */
5009 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5010 if (i->path == session_path) {
5011 in_another_session = false;
5016 in_another_session = false;
5020 if (in_another_session) {
5021 SessionDirectory sd (session_path);
5022 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
5026 /* 1) if file belongs to this session
5027 * it may be a relative path (interchange/...)
5028 * or just basename (session_state, remove source)
5029 * -> just use the basename
5031 std::string filename = Glib::path_get_basename (filepath);
5034 /* 2) if the file is outside our session dir:
5035 * (imported but not copied) add the path for check-summming */
5037 path = Glib::path_get_dirname (filepath);
5040 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
5044 Session::new_audio_source_path_for_embedded (const std::string& path)
5048 * we know that the filename is already unique because it exists
5049 * out in the filesystem.
5051 * However, when we bring it into the session, we could get a
5054 * Eg. two embedded files:
5059 * When merged into session, these collide.
5061 * There will not be a conflict with in-memory sources
5062 * because when the source was created we already picked
5063 * a unique name for it.
5065 * This collision is not likely to be common, but we have to guard
5066 * against it. So, if there is a collision, take the md5 hash of the
5067 * the path, and use that as the filename instead.
5070 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5071 string base = Glib::path_get_basename (path);
5072 string newpath = Glib::build_filename (sdir.sound_path(), base);
5074 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5078 md5.digestString (path.c_str());
5079 md5.writeToString ();
5080 base = md5.digestChars;
5082 string ext = get_suffix (path);
5089 newpath = Glib::build_filename (sdir.sound_path(), base);
5091 /* if this collides, we're screwed */
5093 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5094 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5103 /** Return true if there are no audio file sources that use @param name as
5104 * the filename component of their path.
5106 * Return false otherwise.
5108 * This method MUST ONLY be used to check in-session, mono files since it
5109 * hard-codes the channel of the audio file source we are looking for as zero.
5111 * If/when Ardour supports native files in non-mono formats, the logic here
5112 * will need to be revisited.
5115 Session::audio_source_name_is_unique (const string& name)
5117 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5118 vector<space_and_path>::iterator i;
5119 uint32_t existing = 0;
5121 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5123 /* note that we search *without* the extension so that
5124 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5125 in the event that this new name is required for
5126 a file format change.
5129 const string spath = *i;
5131 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5136 /* it is possible that we have the path already
5137 * assigned to a source that has not yet been written
5138 * (ie. the write source for a diskstream). we have to
5139 * check this in order to make sure that our candidate
5140 * path isn't used again, because that can lead to
5141 * two Sources point to the same file with different
5142 * notions of their removability.
5146 string possible_path = Glib::build_filename (spath, name);
5148 if (audio_source_by_path_and_channel (possible_path, 0)) {
5154 return (existing == 0);
5158 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)
5161 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5163 if (Profile->get_trx() && destructive) {
5165 sstr << setfill ('0') << setw (4) << cnt;
5166 sstr << legalized_base;
5168 sstr << legalized_base;
5170 if (take_required || related_exists) {
5182 } else if (nchan > 2) {
5187 /* XXX what? more than 26 channels! */
5198 /** Return a unique name based on \a base for a new internal audio source */
5200 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5203 string possible_name;
5204 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5206 bool some_related_source_name_exists = false;
5208 legalized = legalize_for_path (base);
5210 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5212 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5214 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5216 if (audio_source_name_is_unique (possible_name)) {
5220 some_related_source_name_exists = true;
5223 error << string_compose(
5224 _("There are already %1 recordings for %2, which I consider too many."),
5225 limit, base) << endmsg;
5227 throw failed_constructor();
5231 /* We've established that the new name does not exist in any session
5232 * directory, so now find out which one we should use for this new
5236 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5238 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5243 /** Return a unique name based on `base` for a new internal MIDI source */
5245 Session::new_midi_source_path (const string& base, bool need_lock)
5248 char buf[PATH_MAX+1];
5249 const uint32_t limit = 10000;
5251 string possible_path;
5252 string possible_name;
5255 legalized = legalize_for_path (base);
5257 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5258 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5260 /* - the main session folder is the first in the vector.
5261 * - after checking all locations for file-name uniqueness,
5262 * we keep the one from the last iteration as new file name
5263 * - midi files are small and should just be kept in the main session-folder
5265 * -> reverse the array, check main session folder last and use that as location
5268 std::reverse(sdirs.begin(), sdirs.end());
5270 for (cnt = 1; cnt <= limit; ++cnt) {
5272 vector<space_and_path>::iterator i;
5273 uint32_t existing = 0;
5275 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5277 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5278 possible_name = buf;
5280 possible_path = Glib::build_filename (*i, possible_name);
5282 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5286 if (midi_source_by_path (possible_path, need_lock)) {
5291 if (existing == 0) {
5296 error << string_compose(
5297 _("There are already %1 recordings for %2, which I consider too many."),
5298 limit, base) << endmsg;
5304 /* No need to "find best location" for software/app-based RAID, because
5305 MIDI is so small that we always put it in the same place.
5308 return possible_path;
5312 /** Create a new within-session audio source */
5313 boost::shared_ptr<AudioFileSource>
5314 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5316 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5318 if (!path.empty()) {
5319 return boost::dynamic_pointer_cast<AudioFileSource> (
5320 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5322 throw failed_constructor ();
5326 /** Create a new within-session MIDI source */
5327 boost::shared_ptr<MidiSource>
5328 Session::create_midi_source_for_session (string const & basic_name)
5330 const string path = new_midi_source_path (basic_name);
5332 if (!path.empty()) {
5333 return boost::dynamic_pointer_cast<SMFSource> (
5334 SourceFactory::createWritable (
5335 DataType::MIDI, *this, path, false, frame_rate()));
5337 throw failed_constructor ();
5341 /** Create a new within-session MIDI source */
5342 boost::shared_ptr<MidiSource>
5343 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5345 /* the caller passes in the track the source will be used in,
5346 so that we can keep the numbering sane.
5348 Rationale: a track with the name "Foo" that has had N
5349 captures carried out so far will ALREADY have a write source
5350 named "Foo-N+1.mid" waiting to be used for the next capture.
5352 If we call new_midi_source_name() we will get "Foo-N+2". But
5353 there is no region corresponding to "Foo-N+1", so when
5354 "Foo-N+2" appears in the track, the gap presents the user
5355 with odd behaviour - why did it skip past Foo-N+1?
5357 We could explain this to the user in some odd way, but
5358 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5361 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5364 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5366 std::string name = track->steal_write_source_name ();
5369 return boost::shared_ptr<MidiSource>();
5372 /* MIDI files are small, just put them in the first location of the
5373 session source search path.
5376 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5378 return boost::dynamic_pointer_cast<SMFSource> (
5379 SourceFactory::createWritable (
5380 DataType::MIDI, *this, path, false, frame_rate()));
5385 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5387 if (playlist->hidden()) {
5391 playlists->add (playlist);
5394 playlist->release();
5401 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5403 if (_state_of_the_state & Deletion) {
5407 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5413 playlists->remove (playlist);
5419 Session::set_audition (boost::shared_ptr<Region> r)
5421 pending_audition_region = r;
5422 add_post_transport_work (PostTransportAudition);
5423 _butler->schedule_transport_work ();
5427 Session::audition_playlist ()
5429 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5430 ev->region.reset ();
5436 Session::register_lua_function (
5437 const std::string& name,
5438 const std::string& script,
5439 const LuaScriptParamList& args
5442 Glib::Threads::Mutex::Lock lm (lua_lock);
5444 lua_State* L = lua.getState();
5446 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5447 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5448 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5449 if ((*i)->optional && !(*i)->is_set) { continue; }
5450 tbl_arg[(*i)->name] = (*i)->value;
5452 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5455 LuaScriptsChanged (); /* EMIT SIGNAL */
5460 Session::unregister_lua_function (const std::string& name)
5462 Glib::Threads::Mutex::Lock lm (lua_lock);
5463 (*_lua_del)(name); // throws luabridge::LuaException
5464 lua.collect_garbage ();
5467 LuaScriptsChanged (); /* EMIT SIGNAL */
5471 std::vector<std::string>
5472 Session::registered_lua_functions ()
5474 Glib::Threads::Mutex::Lock lm (lua_lock);
5475 std::vector<std::string> rv;
5478 luabridge::LuaRef list ((*_lua_list)());
5479 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5480 if (!i.key ().isString ()) { assert(0); continue; }
5481 rv.push_back (i.key ().cast<std::string> ());
5483 } catch (luabridge::LuaException const& e) { }
5488 static void _lua_print (std::string s) {
5489 std::cout << "SessionLua: " << s << "\n";
5494 Session::try_run_lua (pframes_t nframes)
5496 if (_n_lua_scripts == 0) return;
5497 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5499 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5500 lua.collect_garbage_step ();
5505 Session::setup_lua ()
5508 lua.Print.connect (&_lua_print);
5513 "function ArdourSession ()"
5514 " local self = { scripts = {}, instances = {} }"
5516 " local remove = function (n)"
5517 " self.scripts[n] = nil"
5518 " self.instances[n] = nil"
5519 " Session:scripts_changed()" // call back
5522 " local addinternal = function (n, f, a)"
5523 " assert(type(n) == 'string', 'function-name must be string')"
5524 " assert(type(f) == 'function', 'Given script is a not a function')"
5525 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5526 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5527 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5528 " 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 }"
5529 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5530 " Session:scripts_changed()" // call back
5533 " local add = function (n, b, a)"
5534 " assert(type(b) == 'string', 'ByteCode must be string')"
5535 " load (b)()" // assigns f
5536 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5537 " addinternal (n, load(f), a)"
5540 " local run = function (...)"
5541 " for n, s in pairs (self.instances) do"
5542 " local status, err = pcall (s, ...)"
5543 " if not status then"
5544 " print ('fn \"'.. n .. '\": ', err)"
5551 " local cleanup = function ()"
5552 " self.scripts = nil"
5553 " self.instances = nil"
5556 " local list = function ()"
5558 " for n, _ in pairs (self.scripts) do"
5564 " local function basic_serialize (o)"
5565 " if type(o) == \"number\" then"
5566 " return tostring(o)"
5568 " return string.format(\"%q\", o)"
5572 " local function serialize (name, value)"
5573 " local rv = name .. ' = '"
5575 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5576 " return rv .. basic_serialize(value) .. ' '"
5577 " elseif type(value) == \"table\" then"
5579 " for k,v in pairs(value) do"
5580 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5581 " rv = rv .. serialize(fieldname, v) .. ' '"
5582 " collectgarbage()" // string concatenation allocates a new string :(
5585 " elseif type(value) == \"function\" then"
5586 " return rv .. string.format(\"%q\", string.dump(value, true))"
5588 " error('cannot save a ' .. type(value))"
5593 " local save = function ()"
5594 " return (serialize('scripts', self.scripts))"
5597 " local restore = function (state)"
5598 " self.scripts = {}"
5600 " for n, s in pairs (scripts) do"
5601 " addinternal (n, load(s['f']), s['a'])"
5605 " return { run = run, add = add, remove = remove,"
5606 " list = list, restore = restore, save = save, cleanup = cleanup}"
5609 " sess = ArdourSession ()"
5610 " ArdourSession = nil"
5612 "function ardour () end"
5615 lua_State* L = lua.getState();
5618 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5619 lua.do_command ("sess = nil"); // hide it.
5620 lua.do_command ("collectgarbage()");
5622 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5623 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5624 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5625 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5626 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5627 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5628 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5629 } catch (luabridge::LuaException const& e) {
5630 fatal << string_compose (_("programming error: %1"),
5631 X_("Failed to setup Lua interpreter"))
5633 abort(); /*NOTREACHED*/
5636 LuaBindings::stddef (L);
5637 LuaBindings::common (L);
5638 LuaBindings::dsp (L);
5639 luabridge::push <Session *> (L, this);
5640 lua_setglobal (L, "Session");
5644 Session::scripts_changed ()
5646 assert (!lua_lock.trylock()); // must hold lua_lock
5649 luabridge::LuaRef list ((*_lua_list)());
5651 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5652 if (!i.key ().isString ()) { assert(0); continue; }
5655 _n_lua_scripts = cnt;
5656 } catch (luabridge::LuaException const& e) {
5657 fatal << string_compose (_("programming error: %1"),
5658 X_("Indexing Lua Session Scripts failed."))
5660 abort(); /*NOTREACHED*/
5665 Session::non_realtime_set_audition ()
5667 assert (pending_audition_region);
5668 auditioner->audition_region (pending_audition_region);
5669 pending_audition_region.reset ();
5670 AuditionActive (true); /* EMIT SIGNAL */
5674 Session::audition_region (boost::shared_ptr<Region> r)
5676 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5682 Session::cancel_audition ()
5687 if (auditioner->auditioning()) {
5688 auditioner->cancel_audition ();
5689 AuditionActive (false); /* EMIT SIGNAL */
5694 Session::is_auditioning () const
5696 /* can be called before we have an auditioner object */
5698 return auditioner->auditioning();
5705 Session::graph_reordered ()
5707 /* don't do this stuff if we are setting up connections
5708 from a set_state() call or creating new tracks. Ditto for deletion.
5711 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5715 /* every track/bus asked for this to be handled but it was deferred because
5716 we were connecting. do it now.
5719 request_input_change_handling ();
5723 /* force all diskstreams to update their capture offset values to
5724 reflect any changes in latencies within the graph.
5727 boost::shared_ptr<RouteList> rl = routes.reader ();
5728 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5729 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5731 tr->set_capture_offset ();
5736 /** @return Number of frames that there is disk space available to write,
5739 boost::optional<framecnt_t>
5740 Session::available_capture_duration ()
5742 Glib::Threads::Mutex::Lock lm (space_lock);
5744 if (_total_free_4k_blocks_uncertain) {
5745 return boost::optional<framecnt_t> ();
5748 float sample_bytes_on_disk = 4.0; // keep gcc happy
5750 switch (config.get_native_file_data_format()) {
5752 sample_bytes_on_disk = 4.0;
5756 sample_bytes_on_disk = 3.0;
5760 sample_bytes_on_disk = 2.0;
5764 /* impossible, but keep some gcc versions happy */
5765 fatal << string_compose (_("programming error: %1"),
5766 X_("illegal native file data format"))
5768 abort(); /*NOTREACHED*/
5771 double scale = 4096.0 / sample_bytes_on_disk;
5773 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5774 return max_framecnt;
5777 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5781 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5784 RCUWriter<BundleList> writer (_bundles);
5785 boost::shared_ptr<BundleList> b = writer.get_copy ();
5786 b->push_back (bundle);
5790 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5797 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5799 bool removed = false;
5802 RCUWriter<BundleList> writer (_bundles);
5803 boost::shared_ptr<BundleList> b = writer.get_copy ();
5804 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5806 if (i != b->end()) {
5813 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5819 boost::shared_ptr<Bundle>
5820 Session::bundle_by_name (string name) const
5822 boost::shared_ptr<BundleList> b = _bundles.reader ();
5824 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5825 if ((*i)->name() == name) {
5830 return boost::shared_ptr<Bundle> ();
5834 Session::tempo_map_changed (const PropertyChange&)
5838 playlists->update_after_tempo_map_change ();
5840 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5846 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5848 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5849 (*i)->recompute_frames_from_beat ();
5853 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5854 * the given count with the current block size.
5857 Session::ensure_buffers (ChanCount howmany)
5859 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5863 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5865 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5866 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5871 Session::next_insert_id ()
5873 /* this doesn't really loop forever. just think about it */
5876 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5877 if (!insert_bitset[n]) {
5878 insert_bitset[n] = true;
5884 /* none available, so resize and try again */
5886 insert_bitset.resize (insert_bitset.size() + 16, false);
5891 Session::next_send_id ()
5893 /* this doesn't really loop forever. just think about it */
5896 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5897 if (!send_bitset[n]) {
5898 send_bitset[n] = true;
5904 /* none available, so resize and try again */
5906 send_bitset.resize (send_bitset.size() + 16, false);
5911 Session::next_aux_send_id ()
5913 /* this doesn't really loop forever. just think about it */
5916 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5917 if (!aux_send_bitset[n]) {
5918 aux_send_bitset[n] = true;
5924 /* none available, so resize and try again */
5926 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5931 Session::next_return_id ()
5933 /* this doesn't really loop forever. just think about it */
5936 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5937 if (!return_bitset[n]) {
5938 return_bitset[n] = true;
5944 /* none available, so resize and try again */
5946 return_bitset.resize (return_bitset.size() + 16, false);
5951 Session::mark_send_id (uint32_t id)
5953 if (id >= send_bitset.size()) {
5954 send_bitset.resize (id+16, false);
5956 if (send_bitset[id]) {
5957 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5959 send_bitset[id] = true;
5963 Session::mark_aux_send_id (uint32_t id)
5965 if (id >= aux_send_bitset.size()) {
5966 aux_send_bitset.resize (id+16, false);
5968 if (aux_send_bitset[id]) {
5969 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5971 aux_send_bitset[id] = true;
5975 Session::mark_return_id (uint32_t id)
5977 if (id >= return_bitset.size()) {
5978 return_bitset.resize (id+16, false);
5980 if (return_bitset[id]) {
5981 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5983 return_bitset[id] = true;
5987 Session::mark_insert_id (uint32_t id)
5989 if (id >= insert_bitset.size()) {
5990 insert_bitset.resize (id+16, false);
5992 if (insert_bitset[id]) {
5993 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5995 insert_bitset[id] = true;
5999 Session::unmark_send_id (uint32_t id)
6001 if (id < send_bitset.size()) {
6002 send_bitset[id] = false;
6007 Session::unmark_aux_send_id (uint32_t id)
6009 if (id < aux_send_bitset.size()) {
6010 aux_send_bitset[id] = false;
6015 Session::unmark_return_id (uint32_t id)
6017 if (_state_of_the_state & Deletion) { return; }
6018 if (id < return_bitset.size()) {
6019 return_bitset[id] = false;
6024 Session::unmark_insert_id (uint32_t id)
6026 if (id < insert_bitset.size()) {
6027 insert_bitset[id] = false;
6032 Session::reset_native_file_format ()
6034 boost::shared_ptr<RouteList> rl = routes.reader ();
6036 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6037 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6039 /* don't save state as we do this, there's no point
6041 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
6042 tr->reset_write_sources (false);
6043 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
6049 Session::route_name_unique (string n) const
6051 boost::shared_ptr<RouteList> r = routes.reader ();
6053 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6054 if ((*i)->name() == n) {
6063 Session::route_name_internal (string n) const
6065 if (auditioner && auditioner->name() == n) {
6069 if (_click_io && _click_io->name() == n) {
6077 Session::freeze_all (InterThreadInfo& itt)
6079 boost::shared_ptr<RouteList> r = routes.reader ();
6081 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6083 boost::shared_ptr<Track> t;
6085 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6086 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6096 boost::shared_ptr<Region>
6097 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
6098 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6099 InterThreadInfo& itt,
6100 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6101 bool for_export, bool for_freeze)
6103 boost::shared_ptr<Region> result;
6104 boost::shared_ptr<Playlist> playlist;
6105 boost::shared_ptr<Source> source;
6106 ChanCount diskstream_channels (track.n_channels());
6107 framepos_t position;
6108 framecnt_t this_chunk;
6110 framepos_t latency_skip;
6112 framepos_t len = end - start;
6113 bool need_block_size_reset = false;
6114 ChanCount const max_proc = track.max_processor_streams ();
6115 string legal_playlist_name;
6116 string possible_path;
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 (diskstream_channels.n(track.data_type()) < 1) {
6128 error << _("Cannot write a range with no data.") << endmsg;
6132 // block all process callback handling
6134 block_processing ();
6137 // synchronize with AudioEngine::process_callback()
6138 // make sure processing is not currently running
6139 // and processing_blocked() is honored before
6140 // acquiring thread buffers
6141 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6144 _bounce_processing_active = true;
6146 /* call tree *MUST* hold route_lock */
6148 if ((playlist = track.playlist()) == 0) {
6152 legal_playlist_name = legalize_for_path (playlist->name());
6154 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
6156 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6157 string path = ((track.data_type() == DataType::AUDIO)
6158 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6159 : new_midi_source_path (legal_playlist_name));
6166 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6169 catch (failed_constructor& err) {
6170 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6174 srcs.push_back (source);
6177 /* tell redirects that care that we are about to use a much larger
6178 * blocksize. this will flush all plugins too, so that they are ready
6179 * to be used for this process.
6182 need_block_size_reset = true;
6183 track.set_block_size (bounce_chunk_size);
6184 _engine.main_thread()->get_buffers ();
6188 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6190 /* create a set of reasonably-sized buffers */
6191 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6192 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6194 buffers.set_count (max_proc);
6196 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6197 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6198 boost::shared_ptr<MidiSource> ms;
6200 afs->prepare_for_peakfile_writes ();
6201 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6202 Source::Lock lock(ms->mutex());
6203 ms->mark_streaming_write_started(lock);
6207 while (to_do && !itt.cancel) {
6209 this_chunk = min (to_do, bounce_chunk_size);
6211 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6215 start += this_chunk;
6216 to_do -= this_chunk;
6217 itt.progress = (float) (1.0 - ((double) to_do / len));
6219 if (latency_skip >= bounce_chunk_size) {
6220 latency_skip -= bounce_chunk_size;
6224 const framecnt_t current_chunk = this_chunk - latency_skip;
6227 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6228 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6229 boost::shared_ptr<MidiSource> ms;
6232 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6235 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6236 Source::Lock lock(ms->mutex());
6238 const MidiBuffer& buf = buffers.get_midi(0);
6239 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6240 Evoral::Event<framepos_t> ev = *i;
6241 ev.set_time(ev.time() - position);
6242 ms->append_event_frames(lock, ev, ms->timeline_position());
6249 /* post-roll, pick up delayed processor output */
6250 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6252 while (latency_skip && !itt.cancel) {
6253 this_chunk = min (latency_skip, bounce_chunk_size);
6254 latency_skip -= this_chunk;
6256 buffers.silence (this_chunk, 0);
6257 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6260 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6261 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6264 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6276 xnow = localtime (&now);
6278 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6279 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6280 boost::shared_ptr<MidiSource> ms;
6283 afs->update_header (position, *xnow, now);
6284 afs->flush_header ();
6285 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6286 Source::Lock lock(ms->mutex());
6287 ms->mark_streaming_write_completed(lock);
6291 /* construct a region to represent the bounced material */
6295 plist.add (Properties::start, 0);
6296 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6297 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6299 result = RegionFactory::create (srcs, plist);
6305 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6306 (*src)->mark_for_remove ();
6307 (*src)->drop_references ();
6311 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6312 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6315 afs->done_with_peakfile_writes ();
6319 _bounce_processing_active = false;
6321 if (need_block_size_reset) {
6322 _engine.main_thread()->drop_buffers ();
6323 track.set_block_size (get_block_size());
6326 unblock_processing ();
6332 Session::gain_automation_buffer() const
6334 return ProcessThread::gain_automation_buffer ();
6338 Session::trim_automation_buffer() const
6340 return ProcessThread::trim_automation_buffer ();
6344 Session::send_gain_automation_buffer() const
6346 return ProcessThread::send_gain_automation_buffer ();
6350 Session::scratch_automation_buffer() const
6352 return ProcessThread::scratch_automation_buffer ();
6356 Session::pan_automation_buffer() const
6358 return ProcessThread::pan_automation_buffer ();
6362 Session::get_silent_buffers (ChanCount count)
6364 return ProcessThread::get_silent_buffers (count);
6368 Session::get_scratch_buffers (ChanCount count, bool silence)
6370 return ProcessThread::get_scratch_buffers (count, silence);
6374 Session::get_noinplace_buffers (ChanCount count)
6376 return ProcessThread::get_noinplace_buffers (count);
6380 Session::get_route_buffers (ChanCount count, bool silence)
6382 return ProcessThread::get_route_buffers (count, silence);
6387 Session::get_mix_buffers (ChanCount count)
6389 return ProcessThread::get_mix_buffers (count);
6393 Session::ntracks () const
6396 boost::shared_ptr<RouteList> r = routes.reader ();
6398 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6399 if (boost::dynamic_pointer_cast<Track> (*i)) {
6408 Session::nbusses () const
6411 boost::shared_ptr<RouteList> r = routes.reader ();
6413 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6414 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6423 Session::nstripables (bool with_auditioner_and_monitor) const
6425 uint32_t rv = routes.reader()->size ();
6426 rv += _vca_manager->vcas ().size ();
6428 if (with_auditioner_and_monitor) {
6444 Session::add_automation_list(AutomationList *al)
6446 automation_lists[al->id()] = al;
6449 /** @return true if there is at least one record-enabled track, otherwise false */
6451 Session::have_rec_enabled_track () const
6453 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6457 Session::have_rec_disabled_track () const
6459 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6462 /** Update the state of our rec-enabled tracks flag */
6464 Session::update_route_record_state ()
6466 boost::shared_ptr<RouteList> rl = routes.reader ();
6467 RouteList::iterator i = rl->begin();
6468 while (i != rl->end ()) {
6470 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6471 if (tr && tr->rec_enable_control()->get_value()) {
6478 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6480 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6482 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6483 RecordStateChanged (); /* EMIT SIGNAL */
6486 for (i = rl->begin(); i != rl->end (); ++i) {
6487 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6488 if (tr && !tr->rec_enable_control()->get_value()) {
6493 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6495 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6497 if (record_status() == Recording && record_arm_state_changed ) {
6498 RecordArmStateChanged ();
6504 Session::listen_position_changed ()
6506 ProcessorChangeBlocker pcb (this);
6507 boost::shared_ptr<RouteList> r = routes.reader ();
6508 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6509 (*i)->listen_position_changed ();
6514 Session::solo_control_mode_changed ()
6516 if (soloing() || listening()) {
6518 /* We can't use ::clear_all_solo_state() here because during
6519 session loading at program startup, that will queue a call
6520 to rt_clear_all_solo_state() that will not execute until
6521 AFTER solo states have been established (thus throwing away
6522 the session's saved solo state). So just explicitly turn
6525 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6527 clear_all_solo_state (get_routes());
6532 /** Called when a property of one of our route groups changes */
6534 Session::route_group_property_changed (RouteGroup* rg)
6536 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6539 /** Called when a route is added to one of our route groups */
6541 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6543 RouteAddedToRouteGroup (rg, r);
6546 /** Called when a route is removed from one of our route groups */
6548 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6550 update_route_record_state ();
6551 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6553 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6554 remove_route_group (*rg);
6558 boost::shared_ptr<RouteList>
6559 Session::get_tracks () const
6561 boost::shared_ptr<RouteList> rl = routes.reader ();
6562 boost::shared_ptr<RouteList> tl (new RouteList);
6564 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6565 if (boost::dynamic_pointer_cast<Track> (*r)) {
6566 if (!(*r)->is_auditioner()) {
6574 boost::shared_ptr<RouteList>
6575 Session::get_routes_with_regions_at (framepos_t const p) const
6577 boost::shared_ptr<RouteList> r = routes.reader ();
6578 boost::shared_ptr<RouteList> rl (new RouteList);
6580 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6581 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6586 boost::shared_ptr<Playlist> pl = tr->playlist ();
6591 if (pl->has_region_at (p)) {
6600 Session::goto_end ()
6602 if (_session_range_location) {
6603 request_locate (_session_range_location->end(), false);
6605 request_locate (0, false);
6610 Session::goto_start (bool and_roll)
6612 if (_session_range_location) {
6613 request_locate (_session_range_location->start(), and_roll);
6615 request_locate (0, and_roll);
6620 Session::current_start_frame () const
6622 return _session_range_location ? _session_range_location->start() : 0;
6626 Session::current_end_frame () const
6628 return _session_range_location ? _session_range_location->end() : 0;
6632 Session::set_session_range_location (framepos_t start, framepos_t end)
6634 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6635 _locations->add (_session_range_location);
6639 Session::step_edit_status_change (bool yn)
6645 send = (_step_editors == 0);
6650 send = (_step_editors == 1);
6653 if (_step_editors > 0) {
6659 StepEditStatusChange (val);
6665 Session::start_time_changed (framepos_t old)
6667 /* Update the auto loop range to match the session range
6668 (unless the auto loop range has been changed by the user)
6671 Location* s = _locations->session_range_location ();
6676 Location* l = _locations->auto_loop_location ();
6678 if (l && l->start() == old) {
6679 l->set_start (s->start(), true);
6685 Session::end_time_changed (framepos_t old)
6687 /* Update the auto loop range to match the session range
6688 (unless the auto loop range has been changed by the user)
6691 Location* s = _locations->session_range_location ();
6696 Location* l = _locations->auto_loop_location ();
6698 if (l && l->end() == old) {
6699 l->set_end (s->end(), true);
6704 std::vector<std::string>
6705 Session::source_search_path (DataType type) const
6709 if (session_dirs.size() == 1) {
6711 case DataType::AUDIO:
6712 sp.push_back (_session_dir->sound_path());
6714 case DataType::MIDI:
6715 sp.push_back (_session_dir->midi_path());
6719 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6720 SessionDirectory sdir (i->path);
6722 case DataType::AUDIO:
6723 sp.push_back (sdir.sound_path());
6725 case DataType::MIDI:
6726 sp.push_back (sdir.midi_path());
6732 if (type == DataType::AUDIO) {
6733 const string sound_path_2X = _session_dir->sound_path_2X();
6734 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6735 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6736 sp.push_back (sound_path_2X);
6741 // now check the explicit (possibly user-specified) search path
6744 case DataType::AUDIO:
6745 sp += Searchpath(config.get_audio_search_path ());
6747 case DataType::MIDI:
6748 sp += Searchpath(config.get_midi_search_path ());
6756 Session::ensure_search_path_includes (const string& path, DataType type)
6765 case DataType::AUDIO:
6766 sp += Searchpath(config.get_audio_search_path ());
6768 case DataType::MIDI:
6769 sp += Searchpath (config.get_midi_search_path ());
6773 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6774 /* No need to add this new directory if it has the same inode as
6775 an existing one; checking inode rather than name prevents duplicated
6776 directories when we are using symlinks.
6778 On Windows, I think we could just do if (*i == path) here.
6780 if (PBD::equivalent_paths (*i, path)) {
6788 case DataType::AUDIO:
6789 config.set_audio_search_path (sp.to_string());
6791 case DataType::MIDI:
6792 config.set_midi_search_path (sp.to_string());
6798 Session::remove_dir_from_search_path (const string& dir, DataType type)
6803 case DataType::AUDIO:
6804 sp = Searchpath(config.get_audio_search_path ());
6806 case DataType::MIDI:
6807 sp = Searchpath (config.get_midi_search_path ());
6814 case DataType::AUDIO:
6815 config.set_audio_search_path (sp.to_string());
6817 case DataType::MIDI:
6818 config.set_midi_search_path (sp.to_string());
6824 boost::shared_ptr<Speakers>
6825 Session::get_speakers()
6831 Session::unknown_processors () const
6835 boost::shared_ptr<RouteList> r = routes.reader ();
6836 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6837 list<string> t = (*i)->unknown_processors ();
6838 copy (t.begin(), t.end(), back_inserter (p));
6848 Session::update_latency (bool playback)
6851 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6853 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6856 if (!_engine.running()) {
6860 boost::shared_ptr<RouteList> r = routes.reader ();
6861 framecnt_t max_latency = 0;
6864 /* reverse the list so that we work backwards from the last route to run to the first */
6865 RouteList* rl = routes.reader().get();
6866 r.reset (new RouteList (*rl));
6867 reverse (r->begin(), r->end());
6870 /* compute actual latency values for the given direction and store them all in per-port
6871 structures. this will also publish the same values (to JACK) so that computation of latency
6872 for routes can consistently use public latency values.
6875 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6876 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6879 /* because we latency compensate playback, our published playback latencies should
6880 be the same for all output ports - all material played back by ardour has
6881 the same latency, whether its caused by plugins or by latency compensation. since
6882 these may differ from the values computed above, reset all playback port latencies
6886 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6888 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6889 (*i)->set_public_port_latencies (max_latency, playback);
6894 post_playback_latency ();
6898 post_capture_latency ();
6901 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6905 Session::post_playback_latency ()
6907 set_worst_playback_latency ();
6909 boost::shared_ptr<RouteList> r = routes.reader ();
6911 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6912 if (!(*i)->is_auditioner() && ((*i)->active())) {
6913 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6917 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6918 (*i)->set_latency_compensation (_worst_track_latency);
6923 Session::post_capture_latency ()
6925 set_worst_capture_latency ();
6927 /* reflect any changes in capture latencies into capture offsets
6930 boost::shared_ptr<RouteList> rl = routes.reader();
6931 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6932 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6934 tr->set_capture_offset ();
6940 Session::initialize_latencies ()
6943 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6944 update_latency (false);
6945 update_latency (true);
6948 set_worst_io_latencies ();
6952 Session::set_worst_io_latencies ()
6954 set_worst_playback_latency ();
6955 set_worst_capture_latency ();
6959 Session::set_worst_playback_latency ()
6961 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6965 _worst_output_latency = 0;
6967 if (!_engine.connected()) {
6971 boost::shared_ptr<RouteList> r = routes.reader ();
6973 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6974 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6977 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6981 Session::set_worst_capture_latency ()
6983 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6987 _worst_input_latency = 0;
6989 if (!_engine.connected()) {
6993 boost::shared_ptr<RouteList> r = routes.reader ();
6995 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6996 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6999 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
7003 Session::update_latency_compensation (bool force_whole_graph)
7005 bool some_track_latency_changed = false;
7007 if (_state_of_the_state & (InitialConnecting|Deletion)) {
7011 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
7013 _worst_track_latency = 0;
7015 boost::shared_ptr<RouteList> r = routes.reader ();
7017 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7018 if (!(*i)->is_auditioner() && ((*i)->active())) {
7020 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
7021 some_track_latency_changed = true;
7023 _worst_track_latency = max (tl, _worst_track_latency);
7027 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
7028 (some_track_latency_changed ? "yes" : "no")));
7030 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
7032 if (some_track_latency_changed || force_whole_graph) {
7033 _engine.update_latencies ();
7037 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7038 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
7042 tr->set_capture_offset ();
7047 Session::session_name_is_legal (const string& path)
7049 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7051 for (int i = 0; illegal_chars[i]; ++i) {
7052 if (path.find (illegal_chars[i]) != string::npos) {
7053 return illegal_chars[i];
7061 Session::notify_presentation_info_change ()
7063 if (deletion_in_progress()) {
7067 reassign_track_numbers();
7069 #ifdef USE_TRACKS_CODE_FEATURES
7070 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7071 * if track order has been changed by user
7073 reconnect_existing_routes(true, true);
7079 Session::operation_in_progress (GQuark op) const
7081 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7084 boost::shared_ptr<Port>
7085 Session::ltc_input_port () const
7087 assert (_ltc_input);
7088 return _ltc_input->nth (0);
7091 boost::shared_ptr<Port>
7092 Session::ltc_output_port () const
7094 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
7098 Session::reconnect_ltc_input ()
7102 string src = Config->get_ltc_source_port();
7104 _ltc_input->disconnect (this);
7106 if (src != _("None") && !src.empty()) {
7107 _ltc_input->nth (0)->connect (src);
7110 if ( ARDOUR::Profile->get_trx () ) {
7111 // Tracks need this signal to update timecode_source_dropdown
7112 MtcOrLtcInputPortChanged (); //emit signal
7118 Session::reconnect_ltc_output ()
7122 string src = Config->get_ltc_output_port();
7124 _ltc_output->disconnect (this);
7126 if (src != _("None") && !src.empty()) {
7127 _ltc_output->nth (0)->connect (src);
7133 Session::set_range_selection (framepos_t start, framepos_t end)
7135 _range_selection = Evoral::Range<framepos_t> (start, end);
7136 #ifdef USE_TRACKS_CODE_FEATURES
7137 follow_playhead_priority ();
7142 Session::set_object_selection (framepos_t start, framepos_t end)
7144 _object_selection = Evoral::Range<framepos_t> (start, end);
7145 #ifdef USE_TRACKS_CODE_FEATURES
7146 follow_playhead_priority ();
7151 Session::clear_range_selection ()
7153 _range_selection = Evoral::Range<framepos_t> (-1,-1);
7154 #ifdef USE_TRACKS_CODE_FEATURES
7155 follow_playhead_priority ();
7160 Session::clear_object_selection ()
7162 _object_selection = Evoral::Range<framepos_t> (-1,-1);
7163 #ifdef USE_TRACKS_CODE_FEATURES
7164 follow_playhead_priority ();
7169 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7170 const ChanCount& input_start,
7171 const ChanCount& output_start,
7172 const ChanCount& input_offset,
7173 const ChanCount& output_offset)
7175 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7176 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7177 input_start, output_start,
7178 input_offset, output_offset));
7180 auto_connect_thread_wakeup ();
7184 Session::auto_connect_thread_wakeup ()
7186 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7187 pthread_cond_signal (&_auto_connect_cond);
7188 pthread_mutex_unlock (&_auto_connect_mutex);
7193 Session::queue_latency_recompute ()
7195 g_atomic_int_inc (&_latency_recompute_pending);
7196 auto_connect_thread_wakeup ();
7200 Session::auto_connect (const AutoConnectRequest& ar)
7202 boost::shared_ptr<Route> route = ar.route.lock();
7204 if (!route) { return; }
7206 if (!IO::connecting_legal) {
7210 /* If both inputs and outputs are auto-connected to physical ports,
7211 * use the max of input and output offsets to ensure auto-connected
7212 * port numbers always match up (e.g. the first audio input and the
7213 * first audio output of the route will have the same physical
7214 * port number). Otherwise just use the lowest input or output
7218 const bool in_out_physical =
7219 (Config->get_input_auto_connect() & AutoConnectPhysical)
7220 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7221 && ar.connect_inputs;
7223 const ChanCount in_offset = in_out_physical
7224 ? ChanCount::max(ar.input_offset, ar.output_offset)
7227 const ChanCount out_offset = in_out_physical
7228 ? ChanCount::max(ar.input_offset, ar.output_offset)
7231 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7232 vector<string> physinputs;
7233 vector<string> physoutputs;
7236 /* for connecting track inputs we only want MIDI ports marked
7240 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7242 if (!physinputs.empty() && ar.connect_inputs) {
7243 uint32_t nphysical_in = physinputs.size();
7245 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7248 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7249 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7252 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7258 if (!physoutputs.empty()) {
7259 uint32_t nphysical_out = physoutputs.size();
7260 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7264 * do not create new connections if we reached the limit of physical outputs
7267 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7268 ARDOUR::Profile->get_trx () &&
7269 ar.output_offset.get(*t) == nphysical_out ) {
7273 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7274 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7275 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7276 /* master bus is audio only */
7277 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7278 port = _master_out->input()->ports().port(*t,
7279 i % _master_out->input()->n_ports().get(*t))->name();
7283 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7292 Session::auto_connect_thread_start ()
7294 if (g_atomic_int_get (&_ac_thread_active)) {
7298 while (!_auto_connect_queue.empty ()) {
7299 _auto_connect_queue.pop ();
7302 g_atomic_int_set (&_ac_thread_active, 1);
7303 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7304 g_atomic_int_set (&_ac_thread_active, 0);
7309 Session::auto_connect_thread_terminate ()
7311 if (!g_atomic_int_get (&_ac_thread_active)) {
7316 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7317 while (!_auto_connect_queue.empty ()) {
7318 _auto_connect_queue.pop ();
7322 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7323 * fail to wakeup the thread.
7326 pthread_mutex_lock (&_auto_connect_mutex);
7327 g_atomic_int_set (&_ac_thread_active, 0);
7328 pthread_cond_signal (&_auto_connect_cond);
7329 pthread_mutex_unlock (&_auto_connect_mutex);
7332 pthread_join (_auto_connect_thread, &status);
7336 Session::auto_connect_thread (void *arg)
7338 Session *s = static_cast<Session *>(arg);
7339 s->auto_connect_thread_run ();
7345 Session::auto_connect_thread_run ()
7347 pthread_set_name (X_("autoconnect"));
7348 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7349 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7350 pthread_mutex_lock (&_auto_connect_mutex);
7351 while (g_atomic_int_get (&_ac_thread_active)) {
7353 if (!_auto_connect_queue.empty ()) {
7354 // Why would we need the process lock ??
7355 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7356 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7357 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7358 // We have control over those, but what does jack do?
7359 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7361 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7362 while (!_auto_connect_queue.empty ()) {
7363 const AutoConnectRequest ar (_auto_connect_queue.front());
7364 _auto_connect_queue.pop ();
7371 if (!actively_recording ()) { // might not be needed,
7372 /* this is only used for updating plugin latencies, the
7373 * graph does not change. so it's safe in general.
7375 * .. update_latency_compensation () entails set_capture_offset()
7376 * which calls Diskstream::set_capture_offset () which
7377 * modifies the capture offset... which can be a proplem
7378 * in "prepare_to_stop"
7380 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7381 update_latency_compensation ();
7386 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7387 // jack1 cannot cope with removing ports while processing
7388 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7389 AudioEngine::instance()->clear_pending_port_deletions ();
7392 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7394 pthread_mutex_unlock (&_auto_connect_mutex);
7398 Session::cancel_all_solo ()
7402 get_stripables (sl);
7404 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7405 clear_all_solo_state (routes.reader());