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
516 BootMessage (_("Session loading complete"));
528 Session::next_name_id ()
530 return g_atomic_int_add (&_name_id_counter, 1);
534 Session::name_id_counter ()
536 return g_atomic_int_get (&_name_id_counter);
540 Session::init_name_id_counter (guint n)
542 g_atomic_int_set (&_name_id_counter, n);
546 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
548 if (_engine.current_backend() == 0) {
549 /* backend is unknown ... */
550 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
551 if (r.get_value_or (-1) != 0) {
554 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
556 } else if (_engine.setup_required()) {
557 /* backend is known, but setup is needed */
558 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
559 if (r.get_value_or (-1) != 0) {
562 } else if (!_engine.running()) {
563 if (_engine.start()) {
568 /* at this point the engine should be running */
570 if (!_engine.running()) {
574 return immediately_post_engine ();
579 Session::immediately_post_engine ()
581 /* Do various initializations that should take place directly after we
582 * know that the engine is running, but before we either create a
583 * session or set state for an existing one.
586 if (how_many_dsp_threads () > 1) {
587 /* For now, only create the graph if we are using >1 DSP threads, as
588 it is a bit slower than the old code with 1 thread.
590 _process_graph.reset (new Graph (*this));
593 /* every time we reconnect, recompute worst case output latencies */
595 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
597 if (synced_to_engine()) {
598 _engine.transport_stop ();
601 if (config.get_jack_time_master()) {
602 _engine.transport_locate (_transport_frame);
606 BootMessage (_("Set up LTC"));
608 BootMessage (_("Set up Click"));
610 BootMessage (_("Set up standard connections"));
614 catch (failed_constructor& err) {
618 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
620 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
628 vector<void*> debug_pointers;
630 /* if we got to here, leaving pending capture state around
634 remove_pending_capture_state ();
638 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
641 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
647 /* remove I/O objects before unsetting the engine session */
650 _ltc_output.reset ();
652 /* disconnect from any and all signals that we are connected to */
654 Port::PortSignalDrop (); /* EMIT SIGNAL */
657 /* shutdown control surface protocols while we still have ports
658 and the engine to move data to any devices.
661 ControlProtocolManager::instance().drop_protocols ();
663 /* stop auto dis/connecting */
664 auto_connect_thread_terminate ();
666 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
668 _engine.remove_session ();
670 #ifdef USE_TRACKS_CODE_FEATURES
671 EngineStateController::instance()->remove_session();
674 /* deregister all ports - there will be no process or any other
675 * callbacks from the engine any more.
678 Port::PortDrop (); /* EMIT SIGNAL */
680 /* clear history so that no references to objects are held any more */
684 /* clear state tree so that no references to objects are held any more */
690 /* unregister all lua functions, drop held references (if any) */
691 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
693 lua.do_command ("Session = nil");
701 lua.collect_garbage ();
704 /* reset dynamic state version back to default */
705 Stateful::loading_state_version = 0;
707 _butler->drop_references ();
711 delete _all_route_group;
713 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
714 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
718 if (click_data != default_click) {
719 delete [] click_data;
722 if (click_emphasis_data != default_click_emphasis) {
723 delete [] click_emphasis_data;
728 /* need to remove auditioner before monitoring section
729 * otherwise it is re-connected */
732 /* drop references to routes held by the monitoring section
733 * specifically _monitor_out aux/listen references */
734 remove_monitor_section();
736 /* clear out any pending dead wood from RCU managed objects */
741 AudioDiskstream::free_working_buffers();
743 /* tell everyone who is still standing that we're about to die */
746 /* tell everyone to drop references and delete objects as we go */
748 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
749 RegionFactory::delete_all_regions ();
751 /* Do this early so that VCAs no longer hold references to routes */
753 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
756 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
758 /* reset these three references to special routes before we do the usual route delete thing */
760 _master_out.reset ();
761 _monitor_out.reset ();
764 RCUWriter<RouteList> writer (routes);
765 boost::shared_ptr<RouteList> r = writer.get_copy ();
767 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
768 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
769 (*i)->drop_references ();
773 /* writer goes out of scope and updates master */
778 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
779 Glib::Threads::Mutex::Lock lm (source_lock);
780 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
781 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
782 i->second->drop_references ();
788 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
791 emit_thread_terminate ();
793 pthread_cond_destroy (&_rt_emit_cond);
794 pthread_mutex_destroy (&_rt_emit_mutex);
796 pthread_cond_destroy (&_auto_connect_cond);
797 pthread_mutex_destroy (&_auto_connect_mutex);
799 delete _scene_changer; _scene_changer = 0;
800 delete midi_control_ui; midi_control_ui = 0;
802 delete _mmc; _mmc = 0;
803 delete _midi_ports; _midi_ports = 0;
804 delete _locations; _locations = 0;
809 /* clear event queue, the session is gone, nobody is interested in
810 * those anymore, but they do leak memory if not removed
812 while (!immediate_events.empty ()) {
813 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
814 SessionEvent *ev = immediate_events.front ();
815 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
816 immediate_events.pop_front ();
820 case SessionEvent::AutoLoop:
821 case SessionEvent::AutoLoopDeclick:
822 case SessionEvent::Skip:
823 case SessionEvent::PunchIn:
824 case SessionEvent::PunchOut:
825 case SessionEvent::RecordStart:
826 case SessionEvent::StopOnce:
827 case SessionEvent::RangeStop:
828 case SessionEvent::RangeLocate:
832 case SessionEvent::RealTimeOperation:
839 del = del && !_remove_event (ev);
847 /* unregister all dropped ports, process pending port deletion. */
848 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
849 // jack1 cannot cope with removing ports while processing
850 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
851 AudioEngine::instance()->clear_pending_port_deletions ();
854 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
858 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
860 BOOST_SHOW_POINTERS ();
864 Session::setup_ltc ()
868 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
869 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
871 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
872 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
875 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
876 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
877 // TODO use auto-connect thread somehow (needs a route currently)
878 // see note in Session::auto_connect_thread_run() why process lock is needed.
879 reconnect_ltc_input ();
883 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
884 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
887 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
888 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
889 // TODO use auto-connect thread
890 reconnect_ltc_output ();
894 /* fix up names of LTC ports because we don't want the normal
895 * IO style of NAME/TYPE-{in,out}N
898 _ltc_input->nth (0)->set_name (X_("LTC-in"));
899 _ltc_output->nth (0)->set_name (X_("LTC-out"));
903 Session::setup_click ()
907 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
908 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
910 _click_io.reset (new ClickIO (*this, X_("Click")));
911 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
912 _click_gain->activate ();
914 setup_click_state (state_tree->root());
916 setup_click_state (0);
921 Session::setup_click_state (const XMLNode* node)
923 const XMLNode* child = 0;
925 if (node && (child = find_named_node (*node, "Click")) != 0) {
927 /* existing state for Click */
930 if (Stateful::loading_state_version < 3000) {
931 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
933 const XMLNodeList& children (child->children());
934 XMLNodeList::const_iterator i = children.begin();
935 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
937 if (i != children.end()) {
938 c = _click_gain->set_state (**i, Stateful::loading_state_version);
944 _clicking = Config->get_clicking ();
948 error << _("could not setup Click I/O") << endmsg;
955 /* default state for Click: dual-mono to first 2 physical outputs */
958 _engine.get_physical_outputs (DataType::AUDIO, outs);
960 for (uint32_t physport = 0; physport < 2; ++physport) {
961 if (outs.size() > physport) {
962 if (_click_io->add_port (outs[physport], this)) {
963 // relax, even though its an error
968 if (_click_io->n_ports () > ChanCount::ZERO) {
969 _clicking = Config->get_clicking ();
975 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
976 MidiPortFlags include, MidiPortFlags exclude)
978 _engine.get_physical_inputs (type, inputs, include, exclude);
979 _engine.get_physical_outputs (type, outputs, include, exclude);
983 Session::setup_bundles ()
987 RCUWriter<BundleList> writer (_bundles);
988 boost::shared_ptr<BundleList> b = writer.get_copy ();
989 for (BundleList::iterator i = b->begin(); i != b->end();) {
990 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
998 vector<string> inputs[DataType::num_types];
999 vector<string> outputs[DataType::num_types];
1001 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1002 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
1003 MidiPortFlags (0), /* no specific inclusions */
1004 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1008 /* Create a set of Bundle objects that map
1009 to the physical I/O currently available. We create both
1010 mono and stereo bundles, so that the common cases of mono
1011 and stereo tracks get bundles to put in their mixer strip
1012 in / out menus. There may be a nicer way of achieving that;
1013 it doesn't really scale that well to higher channel counts
1016 /* mono output bundles */
1018 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1020 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1022 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1024 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1027 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1028 c->add_channel (_("mono"), DataType::AUDIO);
1029 c->set_port (0, outputs[DataType::AUDIO][np]);
1031 add_bundle (c, false);
1034 /* stereo output bundles */
1036 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1037 if (np + 1 < outputs[DataType::AUDIO].size()) {
1039 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1040 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1041 c->add_channel (_("L"), DataType::AUDIO);
1042 c->set_port (0, outputs[DataType::AUDIO][np]);
1043 c->add_channel (_("R"), DataType::AUDIO);
1044 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1046 add_bundle (c, false);
1050 /* mono input bundles */
1052 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1054 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1056 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1058 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1061 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1062 c->add_channel (_("mono"), DataType::AUDIO);
1063 c->set_port (0, inputs[DataType::AUDIO][np]);
1065 add_bundle (c, false);
1068 /* stereo input bundles */
1070 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1071 if (np + 1 < inputs[DataType::AUDIO].size()) {
1073 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1075 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1076 c->add_channel (_("L"), DataType::AUDIO);
1077 c->set_port (0, inputs[DataType::AUDIO][np]);
1078 c->add_channel (_("R"), DataType::AUDIO);
1079 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1081 add_bundle (c, false);
1085 /* MIDI input bundles */
1087 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1088 string n = inputs[DataType::MIDI][np];
1090 std::string pn = _engine.get_pretty_name_by_name (n);
1094 boost::erase_first (n, X_("alsa_pcm:"));
1096 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1097 c->add_channel ("", DataType::MIDI);
1098 c->set_port (0, inputs[DataType::MIDI][np]);
1099 add_bundle (c, false);
1102 /* MIDI output bundles */
1104 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1105 string n = outputs[DataType::MIDI][np];
1106 std::string pn = _engine.get_pretty_name_by_name (n);
1110 boost::erase_first (n, X_("alsa_pcm:"));
1112 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1113 c->add_channel ("", DataType::MIDI);
1114 c->set_port (0, outputs[DataType::MIDI][np]);
1115 add_bundle (c, false);
1118 // we trust the backend to only calls us if there's a change
1119 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1123 Session::auto_connect_master_bus ()
1125 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1129 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1130 // In this case it means "Multi Out" output mode
1131 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1135 /* if requested auto-connect the outputs to the first N physical ports.
1138 uint32_t limit = _master_out->n_outputs().n_total();
1139 vector<string> outputs[DataType::num_types];
1141 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1142 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1145 for (uint32_t n = 0; n < limit; ++n) {
1146 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1148 if (outputs[p->type()].size() > n) {
1149 connect_to = outputs[p->type()][n];
1152 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1153 if (_master_out->output()->connect (p, connect_to, this)) {
1154 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1163 Session::remove_monitor_section ()
1165 if (!_monitor_out || Profile->get_trx()) {
1169 /* force reversion to Solo-In-Place */
1170 Config->set_solo_control_is_listen_control (false);
1172 /* if we are auditioning, cancel it ... this is a workaround
1173 to a problem (auditioning does not execute the process graph,
1174 which is needed to remove routes when using >1 core for processing)
1179 /* Hold process lock while doing this so that we don't hear bits and
1180 * pieces of audio as we work on each route.
1183 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1185 /* Connect tracks to monitor section. Note that in an
1186 existing session, the internal sends will already exist, but we want the
1187 routes to notice that they connect to the control out specifically.
1191 boost::shared_ptr<RouteList> r = routes.reader ();
1192 ProcessorChangeBlocker pcb (this, false);
1194 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1196 if ((*x)->is_monitor()) {
1198 } else if ((*x)->is_master()) {
1201 (*x)->remove_aux_or_listen (_monitor_out);
1206 remove_route (_monitor_out);
1207 if (_state_of_the_state & Deletion) {
1211 auto_connect_master_bus ();
1214 auditioner->connect ();
1217 Config->ParameterChanged ("use-monitor-bus");
1221 Session::add_monitor_section ()
1225 if (_monitor_out || !_master_out || Profile->get_trx()) {
1229 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1235 BOOST_MARK_ROUTE(r);
1238 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1239 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1240 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1242 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1247 add_routes (rl, false, false, false, 0);
1249 assert (_monitor_out);
1251 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1252 are undefined, at best.
1255 uint32_t limit = _monitor_out->n_inputs().n_audio();
1259 /* connect the inputs to the master bus outputs. this
1260 * represents a separate data feed from the internal sends from
1261 * each route. as of jan 2011, it allows the monitor section to
1262 * conditionally ignore either the internal sends or the normal
1263 * input feed, but we should really find a better way to do
1267 _master_out->output()->disconnect (this);
1269 for (uint32_t n = 0; n < limit; ++n) {
1270 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1271 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1274 string connect_to = o->name();
1275 if (_monitor_out->input()->connect (p, connect_to, this)) {
1276 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1284 /* if monitor section is not connected, connect it to physical outs
1287 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1289 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1291 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1294 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1296 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1297 Config->get_monitor_bus_preferred_bundle())
1303 /* Monitor bus is audio only */
1305 vector<string> outputs[DataType::num_types];
1307 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1308 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1311 uint32_t mod = outputs[DataType::AUDIO].size();
1312 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1316 for (uint32_t n = 0; n < limit; ++n) {
1318 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1320 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1321 connect_to = outputs[DataType::AUDIO][n % mod];
1324 if (!connect_to.empty()) {
1325 if (_monitor_out->output()->connect (p, connect_to, this)) {
1326 error << string_compose (
1327 _("cannot connect control output %1 to %2"),
1338 /* Hold process lock while doing this so that we don't hear bits and
1339 * pieces of audio as we work on each route.
1342 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1344 /* Connect tracks to monitor section. Note that in an
1345 existing session, the internal sends will already exist, but we want the
1346 routes to notice that they connect to the control out specifically.
1350 boost::shared_ptr<RouteList> rls = routes.reader ();
1352 ProcessorChangeBlocker pcb (this, false /* XXX */);
1354 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1356 if ((*x)->is_monitor()) {
1358 } else if ((*x)->is_master()) {
1361 (*x)->enable_monitor_send ();
1366 auditioner->connect ();
1368 Config->ParameterChanged ("use-monitor-bus");
1372 Session::reset_monitor_section ()
1374 /* Process lock should be held by the caller.*/
1376 if (!_monitor_out || Profile->get_trx()) {
1380 uint32_t limit = _master_out->n_outputs().n_audio();
1382 /* connect the inputs to the master bus outputs. this
1383 * represents a separate data feed from the internal sends from
1384 * each route. as of jan 2011, it allows the monitor section to
1385 * conditionally ignore either the internal sends or the normal
1386 * input feed, but we should really find a better way to do
1390 _master_out->output()->disconnect (this);
1391 _monitor_out->output()->disconnect (this);
1393 // monitor section follow master bus - except midi
1394 ChanCount mon_chn (_master_out->output()->n_ports());
1395 mon_chn.set_midi (0);
1397 _monitor_out->input()->ensure_io (mon_chn, false, this);
1398 _monitor_out->output()->ensure_io (mon_chn, false, this);
1400 for (uint32_t n = 0; n < limit; ++n) {
1401 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1402 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1405 string connect_to = o->name();
1406 if (_monitor_out->input()->connect (p, connect_to, this)) {
1407 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1414 /* connect monitor section to physical outs
1417 if (Config->get_auto_connect_standard_busses()) {
1419 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1421 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1424 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1426 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1427 Config->get_monitor_bus_preferred_bundle())
1433 /* Monitor bus is audio only */
1435 vector<string> outputs[DataType::num_types];
1437 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1438 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1441 uint32_t mod = outputs[DataType::AUDIO].size();
1442 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1446 for (uint32_t n = 0; n < limit; ++n) {
1448 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1450 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1451 connect_to = outputs[DataType::AUDIO][n % mod];
1454 if (!connect_to.empty()) {
1455 if (_monitor_out->output()->connect (p, connect_to, this)) {
1456 error << string_compose (
1457 _("cannot connect control output %1 to %2"),
1468 /* Connect tracks to monitor section. Note that in an
1469 existing session, the internal sends will already exist, but we want the
1470 routes to notice that they connect to the control out specifically.
1474 boost::shared_ptr<RouteList> rls = routes.reader ();
1476 ProcessorChangeBlocker pcb (this, false);
1478 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1480 if ((*x)->is_monitor()) {
1482 } else if ((*x)->is_master()) {
1485 (*x)->enable_monitor_send ();
1491 Session::hookup_io ()
1493 /* stop graph reordering notifications from
1494 causing resorts, etc.
1497 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1501 /* we delay creating the auditioner till now because
1502 it makes its own connections to ports.
1506 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1508 throw failed_constructor ();
1510 a->use_new_diskstream ();
1514 catch (failed_constructor& err) {
1515 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1519 /* load bundles, which we may have postponed earlier on */
1520 if (_bundle_xml_node) {
1521 load_bundles (*_bundle_xml_node);
1522 delete _bundle_xml_node;
1525 /* Tell all IO objects to connect themselves together */
1527 IO::enable_connecting ();
1529 /* Now tell all "floating" ports to connect to whatever
1530 they should be connected to.
1533 AudioEngine::instance()->reconnect_ports ();
1535 /* Anyone who cares about input state, wake up and do something */
1537 IOConnectionsComplete (); /* EMIT SIGNAL */
1539 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1541 /* now handle the whole enchilada as if it was one
1542 graph reorder event.
1547 /* update the full solo state, which can't be
1548 correctly determined on a per-route basis, but
1549 needs the global overview that only the session
1553 update_route_solo_state ();
1557 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1559 boost::shared_ptr<Track> track = wp.lock ();
1564 boost::shared_ptr<Playlist> playlist;
1566 if ((playlist = track->playlist()) != 0) {
1567 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1568 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1569 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1574 Session::record_enabling_legal () const
1576 /* this used to be in here, but survey says.... we don't need to restrict it */
1577 // if (record_status() == Recording) {
1581 if (Config->get_all_safe()) {
1588 Session::set_track_monitor_input_status (bool yn)
1590 boost::shared_ptr<RouteList> rl = routes.reader ();
1591 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1592 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1593 if (tr && tr->rec_enable_control()->get_value()) {
1594 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1595 tr->request_input_monitoring (yn);
1601 Session::auto_punch_start_changed (Location* location)
1603 replace_event (SessionEvent::PunchIn, location->start());
1605 if (get_record_enabled() && config.get_punch_in()) {
1606 /* capture start has been changed, so save new pending state */
1607 save_state ("", true);
1612 Session::auto_punch_end_changed (Location* location)
1614 framepos_t when_to_stop = location->end();
1615 // when_to_stop += _worst_output_latency + _worst_input_latency;
1616 replace_event (SessionEvent::PunchOut, when_to_stop);
1620 Session::auto_punch_changed (Location* location)
1622 framepos_t when_to_stop = location->end();
1624 replace_event (SessionEvent::PunchIn, location->start());
1625 //when_to_stop += _worst_output_latency + _worst_input_latency;
1626 replace_event (SessionEvent::PunchOut, when_to_stop);
1629 /** @param loc A loop location.
1630 * @param pos Filled in with the start time of the required fade-out (in session frames).
1631 * @param length Filled in with the length of the required fade-out.
1634 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1636 pos = max (loc->start(), loc->end() - 64);
1637 length = loc->end() - pos;
1641 Session::auto_loop_changed (Location* location)
1643 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1646 auto_loop_declick_range (location, dcp, dcl);
1648 if (transport_rolling() && play_loop) {
1650 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1652 // if (_transport_frame > location->end()) {
1654 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1655 // relocate to beginning of loop
1656 clear_events (SessionEvent::LocateRoll);
1658 request_locate (location->start(), true);
1661 else if (Config->get_seamless_loop() && !loop_changing) {
1663 // schedule a locate-roll to refill the diskstreams at the
1664 // previous loop end
1665 loop_changing = true;
1667 if (location->end() > last_loopend) {
1668 clear_events (SessionEvent::LocateRoll);
1669 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1675 clear_events (SessionEvent::AutoLoopDeclick);
1676 clear_events (SessionEvent::AutoLoop);
1679 /* possibly move playhead if not rolling; if we are rolling we'll move
1680 to the loop start on stop if that is appropriate.
1685 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1686 if (pos == location->start()) {
1687 request_locate (pos);
1692 last_loopend = location->end();
1697 Session::set_auto_punch_location (Location* location)
1701 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1702 punch_connections.drop_connections();
1703 existing->set_auto_punch (false, this);
1704 remove_event (existing->start(), SessionEvent::PunchIn);
1705 clear_events (SessionEvent::PunchOut);
1706 auto_punch_location_changed (0);
1711 if (location == 0) {
1715 if (location->end() <= location->start()) {
1716 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1720 punch_connections.drop_connections ();
1722 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1723 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1724 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1726 location->set_auto_punch (true, this);
1728 auto_punch_changed (location);
1730 auto_punch_location_changed (location);
1734 Session::set_session_extents (framepos_t start, framepos_t end)
1737 if ((existing = _locations->session_range_location()) == 0) {
1738 //if there is no existing session, we need to make a new session location (should never happen)
1739 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1743 error << _("Session: you can't use that location for session start/end)") << endmsg;
1747 existing->set( start, end );
1753 Session::set_auto_loop_location (Location* location)
1757 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1758 loop_connections.drop_connections ();
1759 existing->set_auto_loop (false, this);
1760 remove_event (existing->end(), SessionEvent::AutoLoop);
1763 auto_loop_declick_range (existing, dcp, dcl);
1764 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1765 auto_loop_location_changed (0);
1770 if (location == 0) {
1774 if (location->end() <= location->start()) {
1775 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1779 last_loopend = location->end();
1781 loop_connections.drop_connections ();
1783 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1784 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1785 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1786 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1788 location->set_auto_loop (true, this);
1790 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1791 // set all tracks to use internal looping
1792 boost::shared_ptr<RouteList> rl = routes.reader ();
1793 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1794 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1795 if (tr && !tr->hidden()) {
1796 tr->set_loop (location);
1801 /* take care of our stuff first */
1803 auto_loop_changed (location);
1805 /* now tell everyone else */
1807 auto_loop_location_changed (location);
1811 Session::update_marks (Location*)
1817 Session::update_skips (Location* loc, bool consolidate)
1819 if (_ignore_skips_updates) {
1823 Locations::LocationList skips;
1826 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1827 consolidate_skips (loc);
1830 sync_locations_to_skips ();
1836 Session::consolidate_skips (Location* loc)
1838 Locations::LocationList all_locations = _locations->list ();
1840 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1842 if (!(*l)->is_skip ()) {
1847 /* don't test against self */
1854 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1855 case Evoral::OverlapInternal:
1856 case Evoral::OverlapExternal:
1857 case Evoral::OverlapStart:
1858 case Evoral::OverlapEnd:
1859 /* adjust new location to cover existing one */
1860 loc->set_start (min (loc->start(), (*l)->start()));
1861 loc->set_end (max (loc->end(), (*l)->end()));
1862 /* we don't need this one any more */
1863 _locations->remove (*l);
1864 /* the location has been deleted, so remove reference to it in our local list */
1865 l = all_locations.erase (l);
1868 case Evoral::OverlapNone:
1876 Session::sync_locations_to_skips ()
1878 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1879 * Session::_sync_locations_to_skips() from the audioengine thread.
1881 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1885 Session::_sync_locations_to_skips ()
1887 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1889 Locations::LocationList const & locs (_locations->list());
1891 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1893 Location* location = *i;
1895 if (location->is_skip() && location->is_skipping()) {
1896 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1904 Session::location_added (Location *location)
1906 if (location->is_auto_punch()) {
1907 set_auto_punch_location (location);
1910 if (location->is_auto_loop()) {
1911 set_auto_loop_location (location);
1914 if (location->is_session_range()) {
1915 /* no need for any signal handling or event setting with the session range,
1916 because we keep a direct reference to it and use its start/end directly.
1918 _session_range_location = location;
1921 if (location->is_mark()) {
1922 /* listen for per-location signals that require us to do any * global updates for marks */
1924 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1925 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1926 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1927 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1928 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1931 if (location->is_range_marker()) {
1932 /* listen for per-location signals that require us to do any * global updates for marks */
1934 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1935 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1936 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1937 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1938 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1941 if (location->is_skip()) {
1942 /* listen for per-location signals that require us to update skip-locate events */
1944 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1945 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1946 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1947 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1948 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1950 update_skips (location, true);
1957 Session::location_removed (Location *location)
1959 if (location->is_auto_loop()) {
1960 set_auto_loop_location (0);
1961 set_track_loop (false);
1964 if (location->is_auto_punch()) {
1965 set_auto_punch_location (0);
1968 if (location->is_session_range()) {
1969 /* this is never supposed to happen */
1970 error << _("programming error: session range removed!") << endl;
1973 if (location->is_skip()) {
1975 update_skips (location, false);
1982 Session::locations_changed ()
1984 _locations->apply (*this, &Session::_locations_changed);
1988 Session::_locations_changed (const Locations::LocationList& locations)
1990 /* There was some mass-change in the Locations object.
1992 We might be re-adding a location here but it doesn't actually matter
1993 for all the locations that the Session takes an interest in.
1997 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1998 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1999 location_added (*i);
2003 update_skips (NULL, false);
2007 Session::enable_record ()
2009 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2010 /* no recording at anything except normal speed */
2015 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2017 if (rs == Recording) {
2021 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2023 _last_record_location = _transport_frame;
2024 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2026 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2027 set_track_monitor_input_status (true);
2030 RecordStateChanged ();
2037 Session::set_all_tracks_record_enabled (bool enable )
2039 boost::shared_ptr<RouteList> rl = routes.reader();
2040 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2044 Session::disable_record (bool rt_context, bool force)
2048 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2050 if (!Config->get_latched_record_enable () || force) {
2051 g_atomic_int_set (&_record_status, Disabled);
2052 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2054 if (rs == Recording) {
2055 g_atomic_int_set (&_record_status, Enabled);
2059 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2060 set_track_monitor_input_status (false);
2063 RecordStateChanged (); /* emit signal */
2066 remove_pending_capture_state ();
2068 unset_preroll_record_punch ();
2073 Session::step_back_from_record ()
2075 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2077 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2078 set_track_monitor_input_status (false);
2081 RecordStateChanged (); /* emit signal */
2086 Session::maybe_enable_record (bool rt_context)
2088 if (_step_editors > 0) {
2092 g_atomic_int_set (&_record_status, Enabled);
2094 /* This function is currently called from somewhere other than an RT thread.
2095 * (except maybe lua scripts, which can use rt_context = true)
2096 * This save_state() call therefore doesn't impact anything. Doing it here
2097 * means that we save pending state of which sources the next record will use,
2098 * which gives us some chance of recovering from a crash during the record.
2102 save_state ("", true);
2105 if (_transport_speed) {
2106 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2110 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2111 RecordStateChanged (); /* EMIT SIGNAL */
2118 Session::audible_frame (bool* latent_locate) const
2122 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2123 offset *= transport_speed ();
2124 if (latent_locate) {
2125 *latent_locate = false;
2128 if (synced_to_engine()) {
2129 /* Note: this is basically just sync-to-JACK */
2130 ret = _engine.transport_frame();
2132 ret = _transport_frame;
2135 if (transport_rolling()) {
2138 /* Check to see if we have passed the first guaranteed
2139 * audible frame past our last start position. if not,
2140 * return that last start point because in terms
2141 * of audible frames, we have not moved yet.
2143 * `Start position' in this context means the time we last
2144 * either started, located, or changed transport direction.
2147 if (_transport_speed > 0.0f) {
2149 if (!play_loop || !have_looped) {
2150 if (ret < _last_roll_or_reversal_location) {
2151 if (latent_locate) {
2152 *latent_locate = true;
2154 return _last_roll_or_reversal_location;
2157 /* the play-position wrapped at the loop-point
2158 * ardour is already playing the beginning of the loop,
2159 * but due to playback latency, the "audible frame"
2160 * is still at the end of the loop.
2162 Location *location = _locations->auto_loop_location();
2163 frameoffset_t lo = location->start() - ret;
2165 ret = location->end () - lo;
2166 if (latent_locate) {
2167 *latent_locate = true;
2172 } else if (_transport_speed < 0.0f) {
2174 /* XXX wot? no backward looping? */
2176 if (ret > _last_roll_or_reversal_location) {
2177 return _last_roll_or_reversal_location;
2182 return std::max ((framepos_t)0, ret);
2187 Session::preroll_samples (framepos_t pos) const
2189 const float pr = Config->get_preroll_seconds();
2190 if (pos >= 0 && pr < 0) {
2191 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2192 const Meter& meter = _tempo_map->meter_at_frame (pos);
2193 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2198 return pr * frame_rate();
2202 Session::set_frame_rate (framecnt_t frames_per_second)
2204 /** \fn void Session::set_frame_size(framecnt_t)
2205 the AudioEngine object that calls this guarantees
2206 that it will not be called while we are also in
2207 ::process(). Its fine to do things that block
2211 if (_base_frame_rate == 0) {
2212 _base_frame_rate = frames_per_second;
2214 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2215 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2217 _nominal_frame_rate = frames_per_second;
2222 reset_write_sources (false);
2224 // XXX we need some equivalent to this, somehow
2225 // SndFileSource::setup_standard_crossfades (frames_per_second);
2229 /* XXX need to reset/reinstantiate all LADSPA plugins */
2233 Session::set_block_size (pframes_t nframes)
2235 /* the AudioEngine guarantees
2236 that it will not be called while we are also in
2237 ::process(). It is therefore fine to do things that block
2242 current_block_size = nframes;
2246 boost::shared_ptr<RouteList> r = routes.reader ();
2248 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2249 (*i)->set_block_size (nframes);
2252 boost::shared_ptr<RouteList> rl = routes.reader ();
2253 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2254 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2256 tr->set_block_size (nframes);
2260 set_worst_io_latencies ();
2266 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2268 boost::shared_ptr<Route> r2;
2270 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2271 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2275 /* make a copy of the existing list of routes that feed r1 */
2277 Route::FedBy existing (r1->fed_by());
2279 /* for each route that feeds r1, recurse, marking it as feeding
2283 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2284 if (!(r2 = i->r.lock ())) {
2285 /* (*i) went away, ignore it */
2289 /* r2 is a route that feeds r1 which somehow feeds base. mark
2290 base as being fed by r2
2293 rbase->add_fed_by (r2, i->sends_only);
2297 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2301 if (r1->feeds (r2) && r2->feeds (r1)) {
2305 /* now recurse, so that we can mark base as being fed by
2306 all routes that feed r2
2309 trace_terminal (r2, rbase);
2316 Session::resort_routes ()
2318 /* don't do anything here with signals emitted
2319 by Routes during initial setup or while we
2320 are being destroyed.
2323 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2327 if (_route_deletion_in_progress) {
2332 RCUWriter<RouteList> writer (routes);
2333 boost::shared_ptr<RouteList> r = writer.get_copy ();
2334 resort_routes_using (r);
2335 /* writer goes out of scope and forces update */
2339 if (DEBUG_ENABLED(DEBUG::Graph)) {
2340 boost::shared_ptr<RouteList> rl = routes.reader ();
2341 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2342 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2344 const Route::FedBy& fb ((*i)->fed_by());
2346 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2347 boost::shared_ptr<Route> sf = f->r.lock();
2349 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2358 /** This is called whenever we need to rebuild the graph of how we will process
2360 * @param r List of routes, in any order.
2364 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2366 /* We are going to build a directed graph of our routes;
2367 this is where the edges of that graph are put.
2372 /* Go through all routes doing two things:
2374 * 1. Collect the edges of the route graph. Each of these edges
2375 * is a pair of routes, one of which directly feeds the other
2376 * either by a JACK connection or by an internal send.
2378 * 2. Begin the process of making routes aware of which other
2379 * routes directly or indirectly feed them. This information
2380 * is used by the solo code.
2383 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2385 /* Clear out the route's list of direct or indirect feeds */
2386 (*i)->clear_fed_by ();
2388 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2390 bool via_sends_only;
2392 /* See if this *j feeds *i according to the current state of the JACK
2393 connections and internal sends.
2395 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2396 /* add the edge to the graph (part #1) */
2397 edges.add (*j, *i, via_sends_only);
2398 /* tell the route (for part #2) */
2399 (*i)->add_fed_by (*j, via_sends_only);
2404 /* Attempt a topological sort of the route graph */
2405 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2407 if (sorted_routes) {
2408 /* We got a satisfactory topological sort, so there is no feedback;
2411 Note: the process graph rechain does not require a
2412 topologically-sorted list, but hey ho.
2414 if (_process_graph) {
2415 _process_graph->rechain (sorted_routes, edges);
2418 _current_route_graph = edges;
2420 /* Complete the building of the routes' lists of what directly
2421 or indirectly feeds them.
2423 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2424 trace_terminal (*i, *i);
2427 *r = *sorted_routes;
2430 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2431 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2432 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2436 SuccessfulGraphSort (); /* EMIT SIGNAL */
2439 /* The topological sort failed, so we have a problem. Tell everyone
2440 and stick to the old graph; this will continue to be processed, so
2441 until the feedback is fixed, what is played back will not quite
2442 reflect what is actually connected. Note also that we do not
2443 do trace_terminal here, as it would fail due to an endless recursion,
2444 so the solo code will think that everything is still connected
2448 FeedbackDetected (); /* EMIT SIGNAL */
2453 /** Find a route name starting with \a base, maybe followed by the
2454 * lowest \a id. \a id will always be added if \a definitely_add_number
2455 * is true on entry; otherwise it will only be added if required
2456 * to make the name unique.
2458 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2459 * The available route name with the lowest ID will be used, and \a id
2460 * will be set to the ID.
2462 * \return false if a route name could not be found, and \a track_name
2463 * and \a id do not reflect a free route name.
2466 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2468 /* the base may conflict with ports that do not belong to existing
2469 routes, but hidden objects like the click track. So check port names
2470 before anything else.
2473 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2474 if (base == reserved->first) {
2475 /* Check if this reserved name already exists, and if
2476 so, disallow it without a numeric suffix.
2478 if (!reserved->second || route_by_name (reserved->first)) {
2479 definitely_add_number = true;
2488 /* if we have "base 1" already, it doesn't make sense to add "base"
2489 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2491 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2492 /* just use the base */
2498 name = string_compose ("%1 %2", base, id);
2500 if (route_by_name (name) == 0) {
2506 } while (id < (UINT_MAX-1));
2511 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2513 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2515 in = ChanCount::ZERO;
2516 out = ChanCount::ZERO;
2518 boost::shared_ptr<RouteList> r = routes.reader ();
2520 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2521 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2522 if (tr && !tr->is_auditioner()) {
2523 in += tr->n_inputs();
2524 out += tr->n_outputs();
2530 Session::default_track_name_pattern (DataType t)
2533 case DataType::AUDIO:
2534 if (Profile->get_trx()) {
2541 case DataType::MIDI:
2548 /** Caller must not hold process lock
2549 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2550 * @param instrument plugin info for the instrument to insert pre-fader, if any
2552 list<boost::shared_ptr<MidiTrack> >
2553 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2554 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2555 RouteGroup* route_group, uint32_t how_many,
2556 string name_template, PresentationInfo::order_t order,
2560 uint32_t track_id = 0;
2562 RouteList new_routes;
2563 list<boost::shared_ptr<MidiTrack> > ret;
2565 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2566 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2569 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2570 error << "cannot find name for new midi track" << endmsg;
2574 boost::shared_ptr<MidiTrack> track;
2577 track.reset (new MidiTrack (*this, track_name, mode));
2579 if (track->init ()) {
2584 track->set_strict_io (true);
2587 track->use_new_diskstream();
2589 BOOST_MARK_TRACK (track);
2592 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2593 if (track->input()->ensure_io (input, false, this)) {
2594 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2598 if (track->output()->ensure_io (output, false, this)) {
2599 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2604 track->non_realtime_input_change();
2607 route_group->add (track);
2610 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2612 new_routes.push_back (track);
2613 ret.push_back (track);
2616 catch (failed_constructor &err) {
2617 error << _("Session: could not create new midi track.") << endmsg;
2621 catch (AudioEngine::PortRegistrationFailure& pfe) {
2623 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;
2631 if (!new_routes.empty()) {
2632 StateProtector sp (this);
2633 if (Profile->get_trx()) {
2634 add_routes (new_routes, false, false, false, order);
2636 add_routes (new_routes, true, true, false, order);
2640 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2641 PluginPtr plugin = instrument->load (*this);
2643 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2647 plugin->load_preset (*pset);
2649 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2651 pi->set_strict_io (true);
2654 (*r)->add_processor (pi, PreFader);
2656 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2657 (*r)->move_instrument_down (false);
2667 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2668 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2669 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2672 uint32_t bus_id = 0;
2676 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2679 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2680 error << "cannot find name for new midi bus" << endmsg;
2685 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2692 bus->set_strict_io (true);
2695 BOOST_MARK_ROUTE(bus);
2698 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2700 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2701 error << _("cannot configure new midi bus input") << endmsg;
2706 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2707 error << _("cannot configure new midi bus output") << endmsg;
2713 route_group->add (bus);
2716 bus->add_internal_return ();
2717 ret.push_back (bus);
2720 catch (failed_constructor &err) {
2721 error << _("Session: could not create new audio route.") << endmsg;
2725 catch (AudioEngine::PortRegistrationFailure& pfe) {
2726 error << pfe.what() << endmsg;
2736 StateProtector sp (this);
2737 add_routes (ret, false, false, false, order);
2740 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2741 PluginPtr plugin = instrument->load (*this);
2743 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2747 plugin->load_preset (*pset);
2749 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2751 pi->set_strict_io (true);
2754 (*r)->add_processor (pi, PreFader);
2756 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2757 (*r)->move_instrument_down (false);
2769 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2771 boost::shared_ptr<Route> midi_track (wmt.lock());
2777 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2779 if (change.after.n_audio() <= change.before.n_audio()) {
2783 /* new audio ports: make sure the audio goes somewhere useful,
2784 * unless the user has no-auto-connect selected.
2786 * The existing ChanCounts don't matter for this call as they are only
2787 * to do with matching input and output indices, and we are only changing
2790 auto_connect_route (midi_track, false, ChanCount(), change.before);
2794 #ifdef USE_TRACKS_CODE_FEATURES
2797 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2799 return route1->remote_control_id() < route2->remote_control_id();
2803 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2805 // it is not allowed to perform connection
2806 if (!IO::connecting_legal) {
2810 // if we are deleting routes we will call this once at the end
2811 if (_route_deletion_in_progress) {
2815 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2821 // We need to disconnect the route's inputs and outputs first
2822 // basing on autoconnect configuration
2823 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2824 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2826 ChanCount existing_inputs;
2827 ChanCount existing_outputs;
2828 count_existing_track_channels (existing_inputs, existing_outputs);
2830 //ChanCount inputs = ChanCount::ZERO;
2831 //ChanCount outputs = ChanCount::ZERO;
2833 RouteList existing_routes = *routes.reader ();
2834 existing_routes.sort (compare_routes_by_remote_id);
2837 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2839 vector<string> physinputs;
2840 vector<string> physoutputs;
2842 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2843 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2845 uint32_t input_n = 0;
2846 uint32_t output_n = 0;
2847 RouteList::iterator rIter = existing_routes.begin();
2848 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2849 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2850 for (; rIter != existing_routes.end(); ++rIter) {
2851 if (*rIter == _master_out || *rIter == _monitor_out ) {
2855 if (current_output_auto_connection == AutoConnectPhysical) {
2856 (*rIter)->amp()->deactivate();
2857 } else if (current_output_auto_connection == AutoConnectMaster) {
2858 (*rIter)->amp()->activate();
2861 if (reconnectIputs) {
2862 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2864 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2866 if (current_input_auto_connection & AutoConnectPhysical) {
2868 if ( input_n == physinputs.size() ) {
2872 string port = physinputs[input_n];
2874 if (port.empty() ) {
2875 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2878 //GZ: check this; could be heavy
2879 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2885 if (reconnectOutputs) {
2887 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2888 if (current_output_auto_connection & AutoConnectPhysical) {
2890 //GZ: check this; could be heavy
2891 (*rIter)->output()->disconnect (this);
2892 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2894 //GZ: check this; could be heavy
2895 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2897 } else if (current_output_auto_connection & AutoConnectMaster){
2899 if (!reconnect_master) {
2903 //GZ: check this; could be heavy
2904 (*rIter)->output()->disconnect (this);
2907 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2908 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2910 error << error << "Master bus is not available" << endmsg;
2915 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2916 if (current_output_auto_connection & AutoConnectPhysical) {
2918 if ( output_n == physoutputs.size() ) {
2922 string port = physoutputs[output_n];
2924 if (port.empty() ) {
2925 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2928 //GZ: check this; could be heavy
2929 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2932 } else if (current_output_auto_connection & AutoConnectMaster) {
2934 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2938 // connect to master bus
2939 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2941 if (port.empty() ) {
2942 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2946 //GZ: check this; could be heavy
2947 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2954 _master_out->output()->disconnect (this);
2955 auto_connect_master_bus ();
2960 session_routes_reconnected (); /* EMIT SIGNAL */
2964 Session::reconnect_midi_scene_ports(bool inputs)
2968 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2970 scene_in_ptr->disconnect_all ();
2972 std::vector<EngineStateController::MidiPortState> midi_port_states;
2973 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2975 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2977 for (; state_iter != midi_port_states.end(); ++state_iter) {
2978 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2979 scene_in_ptr->connect (state_iter->name);
2986 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2988 if (scene_out_ptr ) {
2989 scene_out_ptr->disconnect_all ();
2991 std::vector<EngineStateController::MidiPortState> midi_port_states;
2992 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2994 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2996 for (; state_iter != midi_port_states.end(); ++state_iter) {
2997 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2998 scene_out_ptr->connect (state_iter->name);
3006 Session::reconnect_mtc_ports ()
3008 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
3014 mtc_in_ptr->disconnect_all ();
3016 std::vector<EngineStateController::MidiPortState> midi_port_states;
3017 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
3019 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
3021 for (; state_iter != midi_port_states.end(); ++state_iter) {
3022 if (state_iter->available && state_iter->mtc_in) {
3023 mtc_in_ptr->connect (state_iter->name);
3027 if (!_midi_ports->mtc_input_port ()->connected () &&
3028 config.get_external_sync () &&
3029 (Config->get_sync_source () == MTC) ) {
3030 config.set_external_sync (false);
3033 if ( ARDOUR::Profile->get_trx () ) {
3034 // Tracks need this signal to update timecode_source_dropdown
3035 MtcOrLtcInputPortChanged (); //emit signal
3040 Session::reconnect_mmc_ports(bool inputs)
3042 if (inputs ) { // get all enabled midi input ports
3044 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
3046 mmc_in_ptr->disconnect_all ();
3047 std::vector<std::string> enabled_midi_inputs;
3048 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3050 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3052 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3053 mmc_in_ptr->connect (*port_iter);
3057 } else { // get all enabled midi output ports
3059 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3061 mmc_out_ptr->disconnect_all ();
3062 std::vector<std::string> enabled_midi_outputs;
3063 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3065 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3067 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3068 mmc_out_ptr->connect (*port_iter);
3077 Session::ensure_stripable_sort_order ()
3080 get_stripables (sl);
3081 sl.sort (Stripable::Sorter ());
3083 bool change = false;
3084 PresentationInfo::order_t order = 0;
3086 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3087 boost::shared_ptr<Stripable> s (*si);
3088 if (s->is_monitor () || s->is_auditioner ()) {
3091 if (order != s->presentation_info().order()) {
3092 s->set_presentation_order (order);
3101 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3103 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3105 if (first_new_order == PresentationInfo::max_order) {
3106 /* adding at end, no worries */
3110 /* create a gap in the presentation info to accomodate @param how_many
3114 get_stripables (sl);
3116 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3117 boost::shared_ptr<Stripable> s (*si);
3119 if (s->presentation_info().special (false)) {
3123 if (!s->presentation_info().order_set()) {
3127 if (s->presentation_info().order () >= first_new_order) {
3128 s->set_presentation_order (s->presentation_info().order () + how_many);
3133 /** Caller must not hold process lock
3134 * @param name_template string to use for the start of the name, or "" to use "Audio".
3136 list< boost::shared_ptr<AudioTrack> >
3137 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3138 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3142 uint32_t track_id = 0;
3144 RouteList new_routes;
3145 list<boost::shared_ptr<AudioTrack> > ret;
3147 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3148 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3152 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3153 error << "cannot find name for new audio track" << endmsg;
3157 boost::shared_ptr<AudioTrack> track;
3160 track.reset (new AudioTrack (*this, track_name, mode));
3162 if (track->init ()) {
3166 if (Profile->get_mixbus ()) {
3167 track->set_strict_io (true);
3170 if (ARDOUR::Profile->get_trx ()) {
3171 // TRACKS considers it's not a USE CASE, it's
3172 // a piece of behavior of the session model:
3174 // Gain for a newly created route depends on
3175 // the current output_auto_connect mode:
3177 // 0 for Stereo Out mode
3179 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3180 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3184 track->use_new_diskstream();
3186 BOOST_MARK_TRACK (track);
3189 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3191 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3192 error << string_compose (
3193 _("cannot configure %1 in/%2 out configuration for new audio track"),
3194 input_channels, output_channels)
3199 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3200 error << string_compose (
3201 _("cannot configure %1 in/%2 out configuration for new audio track"),
3202 input_channels, output_channels)
3209 route_group->add (track);
3212 track->non_realtime_input_change();
3214 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3216 new_routes.push_back (track);
3217 ret.push_back (track);
3220 catch (failed_constructor &err) {
3221 error << _("Session: could not create new audio track.") << endmsg;
3225 catch (AudioEngine::PortRegistrationFailure& pfe) {
3227 error << pfe.what() << endmsg;
3235 if (!new_routes.empty()) {
3236 StateProtector sp (this);
3237 if (Profile->get_trx()) {
3238 add_routes (new_routes, false, false, false, order);
3240 add_routes (new_routes, true, true, false, order);
3247 /** Caller must not hold process lock.
3248 * @param name_template string to use for the start of the name, or "" to use "Bus".
3251 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3252 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3255 uint32_t bus_id = 0;
3259 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3262 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3263 error << "cannot find name for new audio bus" << endmsg;
3268 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3274 if (Profile->get_mixbus ()) {
3275 bus->set_strict_io (true);
3278 BOOST_MARK_ROUTE(bus);
3281 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3283 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3284 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3285 input_channels, output_channels)
3291 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3292 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3293 input_channels, output_channels)
3300 route_group->add (bus);
3303 bus->add_internal_return ();
3304 ret.push_back (bus);
3307 catch (failed_constructor &err) {
3308 error << _("Session: could not create new audio route.") << endmsg;
3312 catch (AudioEngine::PortRegistrationFailure& pfe) {
3313 error << pfe.what() << endmsg;
3323 StateProtector sp (this);
3324 if (Profile->get_trx()) {
3325 add_routes (ret, false, false, false, order);
3327 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3336 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3337 PlaylistDisposition pd)
3341 if (!tree.read (template_path.c_str())) {
3345 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3349 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3352 uint32_t number = 0;
3353 const uint32_t being_added = how_many;
3354 /* This will prevent the use of any existing XML-provided PBD::ID
3357 Stateful::ForceIDRegeneration force_ids;
3358 IO::disable_connecting ();
3362 /* We're going to modify the node contents a bit so take a
3363 * copy. The node may be re-used when duplicating more than once.
3366 XMLNode node_copy (node);
3371 if (!name_base.empty()) {
3373 /* if we're adding more than one routes, force
3374 * all the names of the new routes to be
3375 * numbered, via the final parameter.
3378 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3379 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3385 string const route_name = node_copy.property(X_("name"))->value ();
3387 /* generate a new name by adding a number to the end of the template name */
3388 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3389 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3390 abort(); /*NOTREACHED*/
3394 /* set this name in the XML description that we are about to use */
3396 if (pd == CopyPlaylist) {
3397 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3399 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3400 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3401 // Use same name as Route::set_name_in_state so playlist copy
3402 // is picked up when creating the Route in XMLRouteFactory below
3403 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3404 playlist->reset_shares ();
3406 } else if (pd == SharePlaylist) {
3407 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3409 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3410 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3411 playlist->share_with ((node_copy.property (X_("id")))->value());
3415 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3417 Route::set_name_in_state (node_copy, name, rename_playlist);
3419 /* trim bitslots from listen sends so that new ones are used */
3420 XMLNodeList children = node_copy.children ();
3421 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3422 if ((*i)->name() == X_("Processor")) {
3423 /* ForceIDRegeneration does not catch the following */
3424 XMLProperty const * role = (*i)->property (X_("role"));
3425 XMLProperty const * type = (*i)->property (X_("type"));
3426 if (role && role->value() == X_("Aux")) {
3427 /* check if the target bus exists.
3428 * we should not save aux-sends in templates.
3430 XMLProperty const * target = (*i)->property (X_("target"));
3432 (*i)->set_property ("type", "dangling-aux-send");
3435 boost::shared_ptr<Route> r = route_by_id (target->value());
3436 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3437 (*i)->set_property ("type", "dangling-aux-send");
3441 if (role && role->value() == X_("Listen")) {
3442 (*i)->remove_property (X_("bitslot"));
3444 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3445 Delivery::Role xrole;
3446 uint32_t bitslot = 0;
3447 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3448 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3449 (*i)->remove_property (X_("bitslot"));
3450 (*i)->remove_property (X_("name"));
3451 (*i)->set_property ("bitslot", bitslot);
3452 (*i)->set_property ("name", name);
3454 else if (type && type->value() == X_("intreturn")) {
3455 (*i)->remove_property (X_("bitslot"));
3456 (*i)->set_property ("ignore-bitslot", "1");
3458 else if (type && type->value() == X_("return")) {
3459 // Return::set_state() generates a new one
3460 (*i)->remove_property (X_("bitslot"));
3462 else if (type && type->value() == X_("port")) {
3463 // PortInsert::set_state() handles the bitslot
3464 (*i)->remove_property (X_("bitslot"));
3465 (*i)->set_property ("ignore-name", "1");
3470 /* new routes start off unsoloed to avoid issues related to
3471 upstream / downstream buses. */
3472 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3474 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3477 error << _("Session: cannot create track/bus from template description") << endmsg;
3481 if (boost::dynamic_pointer_cast<Track>(route)) {
3482 /* force input/output change signals so that the new diskstream
3483 picks up the configuration of the route. During session
3484 loading this normally happens in a different way.
3487 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3489 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3490 change.after = route->input()->n_ports();
3491 route->input()->changed (change, this);
3492 change.after = route->output()->n_ports();
3493 route->output()->changed (change, this);
3496 ret.push_back (route);
3499 catch (failed_constructor &err) {
3500 error << _("Session: could not create new route from template") << endmsg;
3504 catch (AudioEngine::PortRegistrationFailure& pfe) {
3505 error << pfe.what() << endmsg;
3514 StateProtector sp (this);
3515 if (Profile->get_trx()) {
3516 add_routes (ret, false, false, false, insert_at);
3518 add_routes (ret, true, true, false, insert_at);
3520 IO::enable_connecting ();
3527 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3530 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3531 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3534 error << _("Adding new tracks/busses failed") << endmsg;
3539 update_latency (true);
3540 update_latency (false);
3545 save_state (_current_snapshot_name);
3548 update_route_record_state ();
3550 RouteAdded (new_routes); /* EMIT SIGNAL */
3554 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3556 ChanCount existing_inputs;
3557 ChanCount existing_outputs;
3561 count_existing_track_channels (existing_inputs, existing_outputs);
3564 RCUWriter<RouteList> writer (routes);
3565 boost::shared_ptr<RouteList> r = writer.get_copy ();
3566 n_routes = r->size();
3567 r->insert (r->end(), new_routes.begin(), new_routes.end());
3569 /* if there is no control out and we're not in the middle of loading,
3570 * resort the graph here. if there is a control out, we will resort
3571 * toward the end of this method. if we are in the middle of loading,
3572 * we will resort when done.
3575 if (!_monitor_out && IO::connecting_legal) {
3576 resort_routes_using (r);
3580 /* auditioner and monitor routes are not part of the order */
3582 assert (n_routes > 0);
3586 assert (n_routes > 0);
3591 PresentationInfo::ChangeSuspender cs;
3592 ensure_route_presentation_info_gap (order, new_routes.size());
3594 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3596 boost::weak_ptr<Route> wpr (*x);
3597 boost::shared_ptr<Route> r (*x);
3599 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3600 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3601 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3603 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3604 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3605 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3607 if (r->is_master()) {
3611 if (r->is_monitor()) {
3615 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3617 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3618 track_playlist_changed (boost::weak_ptr<Track> (tr));
3619 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3621 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3623 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3624 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3625 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3629 if (!r->presentation_info().special (false)) {
3631 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3633 /* presentation info order may already have been set from XML */
3635 if (!r->presentation_info().order_set()) {
3636 if (order == PresentationInfo::max_order) {
3637 /* just add to the end */
3638 r->set_presentation_order (n_routes + added);
3639 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3641 r->set_presentation_order (order + added);
3642 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3645 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3649 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3650 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3651 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3653 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3655 r->presentation_info().order(),
3656 enum_2_string (r->presentation_info().flags()),
3657 r->presentation_info()));
3661 if (input_auto_connect || output_auto_connect) {
3662 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3663 existing_inputs += r->n_inputs();
3664 existing_outputs += r->n_outputs();
3669 ensure_stripable_sort_order ();
3672 if (_monitor_out && IO::connecting_legal) {
3673 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3675 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3676 if ((*x)->is_monitor()) {
3678 } else if ((*x)->is_master()) {
3681 (*x)->enable_monitor_send ();
3686 reassign_track_numbers ();
3690 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3692 boost::shared_ptr<RouteList> r = routes.reader ();
3693 boost::shared_ptr<Send> s;
3695 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3696 if ((s = (*i)->internal_send_for (dest)) != 0) {
3697 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3703 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3705 boost::shared_ptr<RouteList> r = routes.reader ();
3706 boost::shared_ptr<Send> s;
3708 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3709 if ((s = (*i)->internal_send_for (dest)) != 0) {
3710 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3716 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3718 boost::shared_ptr<RouteList> r = routes.reader ();
3719 boost::shared_ptr<Send> s;
3721 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3722 if ((s = (*i)->internal_send_for (dest)) != 0) {
3723 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3728 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3730 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3732 boost::shared_ptr<RouteList> r = routes.reader ();
3733 boost::shared_ptr<RouteList> t (new RouteList);
3735 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3736 /* no MIDI sends because there are no MIDI busses yet */
3737 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3742 add_internal_sends (dest, p, t);
3746 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3748 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3749 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3754 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3756 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3760 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3762 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3766 if (!dest->internal_return()) {
3767 dest->add_internal_return ();
3770 sender->add_aux_send (dest, before);
3776 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3778 bool mute_changed = false;
3779 bool send_selected = false;
3781 { // RCU Writer scope
3782 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3783 RCUWriter<RouteList> writer (routes);
3784 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3786 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3788 if (_selection->selected (*iter)) {
3789 send_selected = true;
3792 if (*iter == _master_out) {
3796 /* speed up session deletion, don't do the solo dance */
3797 if (0 == (_state_of_the_state & Deletion)) {
3798 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3801 if ((*iter)->mute_control()->muted ()) {
3802 mute_changed = true;
3807 /* deleting the master out seems like a dumb
3808 idea, but its more of a UI policy issue
3812 if (*iter == _master_out) {
3813 _master_out = boost::shared_ptr<Route> ();
3816 if (*iter == _monitor_out) {
3817 _monitor_out.reset ();
3820 // We need to disconnect the route's inputs and outputs
3822 (*iter)->input()->disconnect (0);
3823 (*iter)->output()->disconnect (0);
3825 /* if the route had internal sends sending to it, remove them */
3826 if ((*iter)->internal_return()) {
3828 boost::shared_ptr<RouteList> r = routes.reader ();
3829 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3830 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3832 (*i)->remove_processor (s);
3837 /* if the monitoring section had a pointer to this route, remove it */
3838 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3839 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3840 ProcessorChangeBlocker pcb (this, false);
3841 (*iter)->remove_aux_or_listen (_monitor_out);
3844 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3845 if (mt && mt->step_editing()) {
3846 if (_step_editors > 0) {
3852 /* writer goes out of scope, forces route list update */
3854 } // end of RCU Writer scope
3857 MuteChanged (); /* EMIT SIGNAL */
3860 update_route_solo_state ();
3861 update_latency_compensation ();
3864 /* Re-sort routes to remove the graph's current references to the one that is
3865 * going away, then flush old references out of the graph.
3866 * Wave Tracks: reconnect routes
3869 #ifdef USE_TRACKS_CODE_FEATURES
3870 reconnect_existing_routes(true, false);
3872 routes.flush (); // maybe unsafe, see below.
3876 if (_process_graph && !(_state_of_the_state & Deletion)) {
3877 _process_graph->clear_other_chain ();
3880 /* get rid of it from the dead wood collection in the route list manager */
3881 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3885 /* remove these routes from the selection if appropriate, and signal
3886 * the change *before* we call DropReferences for them.
3889 if (send_selected && !deletion_in_progress()) {
3890 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3891 _selection->remove_stripable_by_id ((*iter)->id());
3894 pc.add (Properties::selected);
3895 PresentationInfo::Change (pc);
3898 /* try to cause everyone to drop their references
3899 * and unregister ports from the backend
3902 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3903 (*iter)->drop_references ();
3906 if (deletion_in_progress()) {
3911 pc.add (Properties::order);
3912 PresentationInfo::Change (pc);
3914 /* save the new state of the world */
3916 if (save_state (_current_snapshot_name)) {
3917 save_history (_current_snapshot_name);
3920 update_route_record_state ();
3924 Session::remove_route (boost::shared_ptr<Route> route)
3926 boost::shared_ptr<RouteList> rl (new RouteList);
3927 rl->push_back (route);
3932 Session::route_mute_changed ()
3934 MuteChanged (); /* EMIT SIGNAL */
3939 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3941 boost::shared_ptr<Route> route (wpr.lock());
3947 assert (Config->get_solo_control_is_listen_control());
3949 if (route->solo_control()->soloed_by_self_or_masters()) {
3951 if (Config->get_exclusive_solo()) {
3953 RouteGroup* rg = route->route_group ();
3954 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3956 boost::shared_ptr<RouteList> r = routes.reader ();
3958 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3959 if ((*i) == route) {
3960 /* already changed */
3964 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3965 /* route does not get solo propagated to it */
3969 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3970 /* this route is a part of the same solo group as the route
3971 * that was changed. Changing that route did change or will
3972 * change all group members appropriately, so we can ignore it
3977 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3983 } else if (_listen_cnt > 0) {
3990 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3992 boost::shared_ptr<Route> route (wpr.lock());
3998 bool send_changed = false;
4000 if (route->solo_isolate_control()->solo_isolated()) {
4001 if (_solo_isolated_cnt == 0) {
4002 send_changed = true;
4004 _solo_isolated_cnt++;
4005 } else if (_solo_isolated_cnt > 0) {
4006 _solo_isolated_cnt--;
4007 if (_solo_isolated_cnt == 0) {
4008 send_changed = true;
4013 IsolatedChanged (); /* EMIT SIGNAL */
4018 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
4020 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
4022 boost::shared_ptr<Route> route (wpr.lock());
4028 if (Config->get_solo_control_is_listen_control()) {
4029 route_listen_changed (group_override, wpr);
4033 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()));
4035 if (route->solo_control()->transitioned_into_solo() == 0) {
4036 /* route solo changed by upstream/downstream or clear all solo state; not interesting
4039 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()));
4043 boost::shared_ptr<RouteList> r = routes.reader ();
4044 int32_t delta = route->solo_control()->transitioned_into_solo ();
4046 /* the route may be a member of a group that has shared-solo
4047 * semantics. If so, then all members of that group should follow the
4048 * solo of the changed route. But ... this is optional, controlled by a
4049 * Controllable::GroupControlDisposition.
4051 * The first argument to the signal that this method is connected to is the
4052 * GroupControlDisposition value that was used to change solo.
4054 * If the solo change was done with group semantics (either InverseGroup
4055 * (force the entire group to change even if the group shared solo is
4056 * disabled) or UseGroup (use the group, which may or may not have the
4057 * shared solo property enabled)) then as we propagate the change to
4058 * the entire session we should IGNORE THE GROUP that the changed route
4062 RouteGroup* rg = route->route_group ();
4063 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4065 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4067 if (delta == 1 && Config->get_exclusive_solo()) {
4069 /* new solo: disable all other solos, but not the group if its solo-enabled */
4071 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4073 if ((*i) == route) {
4074 /* already changed */
4078 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4079 /* route does not get solo propagated to it */
4083 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4084 /* this route is a part of the same solo group as the route
4085 * that was changed. Changing that route did change or will
4086 * change all group members appropriately, so we can ignore it
4092 (*i)->solo_control()->set_value (0.0, group_override);
4096 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4098 RouteList uninvolved;
4100 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4102 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4103 bool via_sends_only;
4104 bool in_signal_flow;
4106 if ((*i) == route) {
4107 /* already changed */
4111 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4112 /* route does not get solo propagated to it */
4113 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(),
4118 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4119 /* this route is a part of the same solo group as the route
4120 * that was changed. Changing that route did change or will
4121 * change all group members appropriately, so we can ignore it
4127 in_signal_flow = false;
4129 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4131 if ((*i)->feeds (route, &via_sends_only)) {
4132 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4133 if (!via_sends_only) {
4134 if (!route->soloed_by_others_upstream()) {
4135 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4137 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4140 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4142 in_signal_flow = true;
4144 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4147 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4149 if (route->feeds (*i, &via_sends_only)) {
4150 /* propagate solo upstream only if routing other than
4151 sends is involved, but do consider the other route
4152 (*i) to be part of the signal flow even if only
4155 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4159 route->soloed_by_others_downstream(),
4160 route->soloed_by_others_upstream()));
4161 if (!via_sends_only) {
4162 //NB. Triggers Invert Push, which handles soloed by downstream
4163 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4164 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4166 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4168 in_signal_flow = true;
4170 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4173 if (!in_signal_flow) {
4174 uninvolved.push_back (*i);
4178 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4180 /* now notify that the mute state of the routes not involved in the signal
4181 pathway of the just-solo-changed route may have altered.
4184 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4185 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4186 (*i)->act_on_mute ();
4187 /* Session will emit SoloChanged() after all solo changes are
4188 * complete, which should be used by UIs to update mute status
4194 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4196 /* now figure out if anything that matters is soloed (or is "listening")*/
4198 bool something_soloed = false;
4199 bool something_listening = false;
4200 uint32_t listeners = 0;
4201 uint32_t isolated = 0;
4204 r = routes.reader();
4207 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4208 if ((*i)->can_solo()) {
4209 if (Config->get_solo_control_is_listen_control()) {
4210 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4212 something_listening = true;
4215 (*i)->set_listen (false);
4216 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4217 something_soloed = true;
4222 if ((*i)->solo_isolate_control()->solo_isolated()) {
4227 if (something_soloed != _non_soloed_outs_muted) {
4228 _non_soloed_outs_muted = something_soloed;
4229 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4232 if (something_listening != _listening) {
4233 _listening = something_listening;
4234 SoloActive (_listening);
4237 _listen_cnt = listeners;
4239 if (isolated != _solo_isolated_cnt) {
4240 _solo_isolated_cnt = isolated;
4241 IsolatedChanged (); /* EMIT SIGNAL */
4244 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4245 something_soloed, listeners, isolated));
4248 SoloChanged (); /* EMIT SIGNAL */
4253 Session::muted () const
4255 // TODO consider caching the value on every MuteChanged signal,
4256 // Note that API users may also subscribe to MuteChanged and hence
4257 // this method needs to be called first.
4260 get_stripables (all);
4261 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4262 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4265 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4266 if (r && !r->active()) {
4269 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4270 if (mc && mc->muted ()) {
4278 std::vector<boost::weak_ptr<AutomationControl> >
4279 Session::cancel_all_mute ()
4282 get_stripables (all);
4283 std::vector<boost::weak_ptr<AutomationControl> > muted;
4284 boost::shared_ptr<ControlList> cl (new ControlList);
4285 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4286 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4289 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4290 if (r && !r->active()) {
4293 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4294 if (ac && ac->get_value () > 0) {
4296 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4299 if (!cl->empty ()) {
4300 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4306 Session::get_stripables (StripableList& sl) const
4308 boost::shared_ptr<RouteList> r = routes.reader ();
4309 sl.insert (sl.end(), r->begin(), r->end());
4311 VCAList v = _vca_manager->vcas ();
4312 sl.insert (sl.end(), v.begin(), v.end());
4316 Session::get_stripables () const
4319 Session::get_stripables (rv);
4320 rv.sort (Stripable::Sorter ());
4324 boost::shared_ptr<RouteList>
4325 Session::get_routes_with_internal_returns() const
4327 boost::shared_ptr<RouteList> r = routes.reader ();
4328 boost::shared_ptr<RouteList> rl (new RouteList);
4330 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4331 if ((*i)->internal_return ()) {
4339 Session::io_name_is_legal (const std::string& name) const
4341 boost::shared_ptr<RouteList> r = routes.reader ();
4343 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4344 if (name == reserved->first) {
4345 if (!route_by_name (reserved->first)) {
4346 /* first instance of a reserved name is allowed for some */
4347 return reserved->second;
4349 /* all other instances of a reserved name are not allowed */
4354 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4355 if ((*i)->name() == name) {
4359 if ((*i)->has_io_processor_named (name)) {
4368 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4371 vector<string> connections;
4373 /* if we are passed only a single route and we're not told to turn
4374 * others off, then just do the simple thing.
4377 if (flip_others == false && rl->size() == 1) {
4378 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4380 mt->set_input_active (onoff);
4385 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4387 PortSet& ps ((*rt)->input()->ports());
4389 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4390 p->get_connections (connections);
4393 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4394 routes_using_input_from (*s, rl2);
4397 /* scan all relevant routes to see if others are on or off */
4399 bool others_are_already_on = false;
4401 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4403 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4409 if ((*r) != (*rt)) {
4410 if (mt->input_active()) {
4411 others_are_already_on = true;
4414 /* this one needs changing */
4415 mt->set_input_active (onoff);
4421 /* globally reverse other routes */
4423 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4424 if ((*r) != (*rt)) {
4425 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4427 mt->set_input_active (!others_are_already_on);
4436 Session::routes_using_input_from (const string& str, RouteList& rl)
4438 boost::shared_ptr<RouteList> r = routes.reader();
4440 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4441 if ((*i)->input()->connected_to (str)) {
4447 boost::shared_ptr<Route>
4448 Session::route_by_name (string name) const
4450 boost::shared_ptr<RouteList> r = routes.reader ();
4452 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4453 if ((*i)->name() == name) {
4458 return boost::shared_ptr<Route> ((Route*) 0);
4461 boost::shared_ptr<Route>
4462 Session::route_by_id (PBD::ID id) const
4464 boost::shared_ptr<RouteList> r = routes.reader ();
4466 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4467 if ((*i)->id() == id) {
4472 return boost::shared_ptr<Route> ((Route*) 0);
4476 boost::shared_ptr<Stripable>
4477 Session::stripable_by_id (PBD::ID id) const
4480 get_stripables (sl);
4482 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4483 if ((*s)->id() == id) {
4488 return boost::shared_ptr<Stripable>();
4491 boost::shared_ptr<Processor>
4492 Session::processor_by_id (PBD::ID id) const
4494 boost::shared_ptr<RouteList> r = routes.reader ();
4496 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4497 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4503 return boost::shared_ptr<Processor> ();
4506 boost::shared_ptr<Track>
4507 Session::track_by_diskstream_id (PBD::ID id) const
4509 boost::shared_ptr<RouteList> r = routes.reader ();
4511 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4512 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4513 if (t && t->using_diskstream_id (id)) {
4518 return boost::shared_ptr<Track> ();
4521 boost::shared_ptr<Route>
4522 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4524 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4527 boost::shared_ptr<Stripable>
4528 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4531 PresentationInfo::order_t match_cnt = 0;
4533 get_stripables (sl);
4534 sl.sort (Stripable::Sorter());
4536 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4538 if ((*s)->presentation_info().hidden()) {
4539 /* if the caller didn't explicitly ask for hidden
4540 stripables, ignore hidden ones. This matches
4541 the semantics of the pre-PresentationOrder
4542 "get by RID" logic of Ardour 4.x and earlier.
4544 XXX at some point we should likely reverse
4545 the logic of the flags, because asking for "the
4546 hidden stripables" is not going to be common,
4547 whereas asking for visible ones is normal.
4550 if (! (flags & PresentationInfo::Hidden)) {
4555 if ((*s)->presentation_info().flag_match (flags)) {
4556 if (match_cnt++ == n) {
4562 /* there is no nth stripable that matches the given flags */
4563 return boost::shared_ptr<Stripable>();
4566 boost::shared_ptr<Route>
4567 Session::route_by_selected_count (uint32_t id) const
4569 RouteList r (*(routes.reader ()));
4570 r.sort (Stripable::Sorter());
4572 RouteList::iterator i;
4574 for (i = r.begin(); i != r.end(); ++i) {
4575 if ((*i)->is_selected()) {
4583 return boost::shared_ptr<Route> ();
4587 Session::reassign_track_numbers ()
4591 RouteList r (*(routes.reader ()));
4592 r.sort (Stripable::Sorter());
4594 StateProtector sp (this);
4596 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4597 if (boost::dynamic_pointer_cast<Track> (*i)) {
4598 (*i)->set_track_number(++tn);
4600 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4601 (*i)->set_track_number(--bn);
4604 const uint32_t decimals = ceilf (log10f (tn + 1));
4605 const bool decimals_changed = _track_number_decimals != decimals;
4606 _track_number_decimals = decimals;
4608 if (decimals_changed && config.get_track_name_number ()) {
4609 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4610 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4612 t->resync_track_name();
4615 // trigger GUI re-layout
4616 config.ParameterChanged("track-name-number");
4620 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4621 boost::shared_ptr<RouteList> rl = routes.reader ();
4622 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4623 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4631 Session::playlist_region_added (boost::weak_ptr<Region> w)
4633 boost::shared_ptr<Region> r = w.lock ();
4638 /* These are the operations that are currently in progress... */
4639 list<GQuark> curr = _current_trans_quarks;
4642 /* ...and these are the operations during which we want to update
4643 the session range location markers.
4646 ops.push_back (Operations::capture);
4647 ops.push_back (Operations::paste);
4648 ops.push_back (Operations::duplicate_region);
4649 ops.push_back (Operations::insert_file);
4650 ops.push_back (Operations::insert_region);
4651 ops.push_back (Operations::drag_region_brush);
4652 ops.push_back (Operations::region_drag);
4653 ops.push_back (Operations::selection_grab);
4654 ops.push_back (Operations::region_fill);
4655 ops.push_back (Operations::fill_selection);
4656 ops.push_back (Operations::create_region);
4657 ops.push_back (Operations::region_copy);
4658 ops.push_back (Operations::fixed_time_region_copy);
4661 /* See if any of the current operations match the ones that we want */
4663 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4665 /* If so, update the session range markers */
4667 maybe_update_session_range (r->position (), r->last_frame ());
4671 /** Update the session range markers if a is before the current start or
4672 * b is after the current end.
4675 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4677 if (_state_of_the_state & Loading) {
4681 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4683 if (_session_range_location == 0) {
4685 set_session_range_location (a, b + session_end_marker_shift_samples);
4689 if (a < _session_range_location->start()) {
4690 _session_range_location->set_start (a);
4693 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4694 _session_range_location->set_end (b);
4700 Session::set_end_is_free (bool yn)
4702 _session_range_end_is_free = yn;
4706 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4708 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4709 maybe_update_session_range (i->to, i->to + i->length);
4714 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4716 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4717 maybe_update_session_range (i->from, i->to);
4721 /* Region management */
4723 boost::shared_ptr<Region>
4724 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4726 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4727 RegionFactory::RegionMap::const_iterator i;
4728 boost::shared_ptr<Region> region;
4730 Glib::Threads::Mutex::Lock lm (region_lock);
4732 for (i = regions.begin(); i != regions.end(); ++i) {
4736 if (region->whole_file()) {
4738 if (child->source_equivalent (region)) {
4744 return boost::shared_ptr<Region> ();
4748 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4750 set<boost::shared_ptr<Region> > relevant_regions;
4752 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4753 RegionFactory::get_regions_using_source (*s, relevant_regions);
4756 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4757 set<boost::shared_ptr<Region> >::iterator tmp;
4762 playlists->destroy_region (*r);
4763 RegionFactory::map_remove (*r);
4765 (*r)->drop_sources ();
4766 (*r)->drop_references ();
4768 relevant_regions.erase (r);
4773 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4776 Glib::Threads::Mutex::Lock ls (source_lock);
4777 /* remove from the main source list */
4778 sources.erase ((*s)->id());
4781 (*s)->mark_for_remove ();
4782 (*s)->drop_references ();
4791 Session::remove_last_capture ()
4793 list<boost::shared_ptr<Source> > srcs;
4795 boost::shared_ptr<RouteList> rl = routes.reader ();
4796 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4797 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4802 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4805 srcs.insert (srcs.end(), l.begin(), l.end());
4810 destroy_sources (srcs);
4812 save_state (_current_snapshot_name);
4817 /* Source Management */
4820 Session::add_source (boost::shared_ptr<Source> source)
4822 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4823 pair<SourceMap::iterator,bool> result;
4825 entry.first = source->id();
4826 entry.second = source;
4829 Glib::Threads::Mutex::Lock lm (source_lock);
4830 result = sources.insert (entry);
4833 if (result.second) {
4835 /* yay, new source */
4837 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4840 if (!fs->within_session()) {
4841 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4847 boost::shared_ptr<AudioFileSource> afs;
4849 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4850 if (Config->get_auto_analyse_audio()) {
4851 Analyser::queue_source_for_analysis (source, false);
4855 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4860 Session::remove_source (boost::weak_ptr<Source> src)
4862 if (_state_of_the_state & Deletion) {
4866 SourceMap::iterator i;
4867 boost::shared_ptr<Source> source = src.lock();
4874 Glib::Threads::Mutex::Lock lm (source_lock);
4876 if ((i = sources.find (source->id())) != sources.end()) {
4881 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4883 /* save state so we don't end up with a session file
4884 referring to non-existent sources.
4887 save_state (_current_snapshot_name);
4891 boost::shared_ptr<Source>
4892 Session::source_by_id (const PBD::ID& id)
4894 Glib::Threads::Mutex::Lock lm (source_lock);
4895 SourceMap::iterator i;
4896 boost::shared_ptr<Source> source;
4898 if ((i = sources.find (id)) != sources.end()) {
4905 boost::shared_ptr<AudioFileSource>
4906 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4908 /* Restricted to audio files because only audio sources have channel
4912 Glib::Threads::Mutex::Lock lm (source_lock);
4914 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4915 boost::shared_ptr<AudioFileSource> afs
4916 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4918 if (afs && afs->path() == path && chn == afs->channel()) {
4923 return boost::shared_ptr<AudioFileSource>();
4926 boost::shared_ptr<MidiSource>
4927 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4929 /* Restricted to MIDI files because audio sources require a channel
4930 for unique identification, in addition to a path.
4933 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4934 if (need_source_lock) {
4938 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4939 boost::shared_ptr<MidiSource> ms
4940 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4941 boost::shared_ptr<FileSource> fs
4942 = boost::dynamic_pointer_cast<FileSource>(s->second);
4944 if (ms && fs && fs->path() == path) {
4949 return boost::shared_ptr<MidiSource>();
4953 Session::count_sources_by_origin (const string& path)
4956 Glib::Threads::Mutex::Lock lm (source_lock);
4958 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4959 boost::shared_ptr<FileSource> fs
4960 = boost::dynamic_pointer_cast<FileSource>(i->second);
4962 if (fs && fs->origin() == path) {
4971 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4973 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4974 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4976 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4981 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4983 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4985 if (Glib::path_is_absolute (filepath)) {
4987 /* rip the session dir from the audiofile source */
4989 string session_path;
4990 bool in_another_session = true;
4992 if (filepath.find (interchange_dir_string) != string::npos) {
4994 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4995 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4996 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4997 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4999 /* see if it is within our session */
5001 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5002 if (i->path == session_path) {
5003 in_another_session = false;
5008 in_another_session = false;
5012 if (in_another_session) {
5013 SessionDirectory sd (session_path);
5014 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
5018 /* 1) if file belongs to this session
5019 * it may be a relative path (interchange/...)
5020 * or just basename (session_state, remove source)
5021 * -> just use the basename
5023 std::string filename = Glib::path_get_basename (filepath);
5026 /* 2) if the file is outside our session dir:
5027 * (imported but not copied) add the path for check-summming */
5029 path = Glib::path_get_dirname (filepath);
5032 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
5036 Session::new_audio_source_path_for_embedded (const std::string& path)
5040 * we know that the filename is already unique because it exists
5041 * out in the filesystem.
5043 * However, when we bring it into the session, we could get a
5046 * Eg. two embedded files:
5051 * When merged into session, these collide.
5053 * There will not be a conflict with in-memory sources
5054 * because when the source was created we already picked
5055 * a unique name for it.
5057 * This collision is not likely to be common, but we have to guard
5058 * against it. So, if there is a collision, take the md5 hash of the
5059 * the path, and use that as the filename instead.
5062 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5063 string base = Glib::path_get_basename (path);
5064 string newpath = Glib::build_filename (sdir.sound_path(), base);
5066 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5070 md5.digestString (path.c_str());
5071 md5.writeToString ();
5072 base = md5.digestChars;
5074 string ext = get_suffix (path);
5081 newpath = Glib::build_filename (sdir.sound_path(), base);
5083 /* if this collides, we're screwed */
5085 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5086 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5095 /** Return true if there are no audio file sources that use @param name as
5096 * the filename component of their path.
5098 * Return false otherwise.
5100 * This method MUST ONLY be used to check in-session, mono files since it
5101 * hard-codes the channel of the audio file source we are looking for as zero.
5103 * If/when Ardour supports native files in non-mono formats, the logic here
5104 * will need to be revisited.
5107 Session::audio_source_name_is_unique (const string& name)
5109 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5110 vector<space_and_path>::iterator i;
5111 uint32_t existing = 0;
5113 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5115 /* note that we search *without* the extension so that
5116 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5117 in the event that this new name is required for
5118 a file format change.
5121 const string spath = *i;
5123 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5128 /* it is possible that we have the path already
5129 * assigned to a source that has not yet been written
5130 * (ie. the write source for a diskstream). we have to
5131 * check this in order to make sure that our candidate
5132 * path isn't used again, because that can lead to
5133 * two Sources point to the same file with different
5134 * notions of their removability.
5138 string possible_path = Glib::build_filename (spath, name);
5140 if (audio_source_by_path_and_channel (possible_path, 0)) {
5146 return (existing == 0);
5150 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)
5153 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5155 if (Profile->get_trx() && destructive) {
5157 sstr << setfill ('0') << setw (4) << cnt;
5158 sstr << legalized_base;
5160 sstr << legalized_base;
5162 if (take_required || related_exists) {
5174 } else if (nchan > 2) {
5179 /* XXX what? more than 26 channels! */
5190 /** Return a unique name based on \a base for a new internal audio source */
5192 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5195 string possible_name;
5196 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5198 bool some_related_source_name_exists = false;
5200 legalized = legalize_for_path (base);
5202 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5204 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5206 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5208 if (audio_source_name_is_unique (possible_name)) {
5212 some_related_source_name_exists = true;
5215 error << string_compose(
5216 _("There are already %1 recordings for %2, which I consider too many."),
5217 limit, base) << endmsg;
5219 throw failed_constructor();
5223 /* We've established that the new name does not exist in any session
5224 * directory, so now find out which one we should use for this new
5228 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5230 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5235 /** Return a unique name based on `base` for a new internal MIDI source */
5237 Session::new_midi_source_path (const string& base, bool need_lock)
5240 char buf[PATH_MAX+1];
5241 const uint32_t limit = 10000;
5243 string possible_path;
5244 string possible_name;
5247 legalized = legalize_for_path (base);
5249 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5250 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5252 /* - the main session folder is the first in the vector.
5253 * - after checking all locations for file-name uniqueness,
5254 * we keep the one from the last iteration as new file name
5255 * - midi files are small and should just be kept in the main session-folder
5257 * -> reverse the array, check main session folder last and use that as location
5260 std::reverse(sdirs.begin(), sdirs.end());
5262 for (cnt = 1; cnt <= limit; ++cnt) {
5264 vector<space_and_path>::iterator i;
5265 uint32_t existing = 0;
5267 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5269 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5270 possible_name = buf;
5272 possible_path = Glib::build_filename (*i, possible_name);
5274 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5278 if (midi_source_by_path (possible_path, need_lock)) {
5283 if (existing == 0) {
5288 error << string_compose(
5289 _("There are already %1 recordings for %2, which I consider too many."),
5290 limit, base) << endmsg;
5296 /* No need to "find best location" for software/app-based RAID, because
5297 MIDI is so small that we always put it in the same place.
5300 return possible_path;
5304 /** Create a new within-session audio source */
5305 boost::shared_ptr<AudioFileSource>
5306 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5308 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5310 if (!path.empty()) {
5311 return boost::dynamic_pointer_cast<AudioFileSource> (
5312 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5314 throw failed_constructor ();
5318 /** Create a new within-session MIDI source */
5319 boost::shared_ptr<MidiSource>
5320 Session::create_midi_source_for_session (string const & basic_name)
5322 const string path = new_midi_source_path (basic_name);
5324 if (!path.empty()) {
5325 return boost::dynamic_pointer_cast<SMFSource> (
5326 SourceFactory::createWritable (
5327 DataType::MIDI, *this, path, false, frame_rate()));
5329 throw failed_constructor ();
5333 /** Create a new within-session MIDI source */
5334 boost::shared_ptr<MidiSource>
5335 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5337 /* the caller passes in the track the source will be used in,
5338 so that we can keep the numbering sane.
5340 Rationale: a track with the name "Foo" that has had N
5341 captures carried out so far will ALREADY have a write source
5342 named "Foo-N+1.mid" waiting to be used for the next capture.
5344 If we call new_midi_source_name() we will get "Foo-N+2". But
5345 there is no region corresponding to "Foo-N+1", so when
5346 "Foo-N+2" appears in the track, the gap presents the user
5347 with odd behaviour - why did it skip past Foo-N+1?
5349 We could explain this to the user in some odd way, but
5350 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5353 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5356 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5358 std::string name = track->steal_write_source_name ();
5361 return boost::shared_ptr<MidiSource>();
5364 /* MIDI files are small, just put them in the first location of the
5365 session source search path.
5368 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5370 return boost::dynamic_pointer_cast<SMFSource> (
5371 SourceFactory::createWritable (
5372 DataType::MIDI, *this, path, false, frame_rate()));
5377 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5379 if (playlist->hidden()) {
5383 playlists->add (playlist);
5386 playlist->release();
5393 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5395 if (_state_of_the_state & Deletion) {
5399 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5405 playlists->remove (playlist);
5411 Session::set_audition (boost::shared_ptr<Region> r)
5413 pending_audition_region = r;
5414 add_post_transport_work (PostTransportAudition);
5415 _butler->schedule_transport_work ();
5419 Session::audition_playlist ()
5421 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5422 ev->region.reset ();
5428 Session::register_lua_function (
5429 const std::string& name,
5430 const std::string& script,
5431 const LuaScriptParamList& args
5434 Glib::Threads::Mutex::Lock lm (lua_lock);
5436 lua_State* L = lua.getState();
5438 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5439 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5440 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5441 if ((*i)->optional && !(*i)->is_set) { continue; }
5442 tbl_arg[(*i)->name] = (*i)->value;
5444 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5447 LuaScriptsChanged (); /* EMIT SIGNAL */
5452 Session::unregister_lua_function (const std::string& name)
5454 Glib::Threads::Mutex::Lock lm (lua_lock);
5455 (*_lua_del)(name); // throws luabridge::LuaException
5456 lua.collect_garbage ();
5459 LuaScriptsChanged (); /* EMIT SIGNAL */
5463 std::vector<std::string>
5464 Session::registered_lua_functions ()
5466 Glib::Threads::Mutex::Lock lm (lua_lock);
5467 std::vector<std::string> rv;
5470 luabridge::LuaRef list ((*_lua_list)());
5471 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5472 if (!i.key ().isString ()) { assert(0); continue; }
5473 rv.push_back (i.key ().cast<std::string> ());
5475 } catch (luabridge::LuaException const& e) { }
5480 static void _lua_print (std::string s) {
5481 std::cout << "SessionLua: " << s << "\n";
5486 Session::try_run_lua (pframes_t nframes)
5488 if (_n_lua_scripts == 0) return;
5489 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5491 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5492 lua.collect_garbage_step ();
5497 Session::setup_lua ()
5500 lua.Print.connect (&_lua_print);
5504 "function ArdourSession ()"
5505 " local self = { scripts = {}, instances = {} }"
5507 " local remove = function (n)"
5508 " self.scripts[n] = nil"
5509 " self.instances[n] = nil"
5510 " Session:scripts_changed()" // call back
5513 " local addinternal = function (n, f, a)"
5514 " assert(type(n) == 'string', 'function-name must be string')"
5515 " assert(type(f) == 'function', 'Given script is a not a function')"
5516 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5517 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5518 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5519 " local env = _ENV; env.f = nil env.io = nil env.os = nil env.loadfile = nil env.require = nil env.dofile = nil env.package = nil env.debug = nil"
5520 " 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 }"
5521 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5522 " Session:scripts_changed()" // call back
5525 " local add = function (n, b, a)"
5526 " assert(type(b) == 'string', 'ByteCode must be string')"
5527 " load (b)()" // assigns f
5528 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5529 " addinternal (n, load(f), a)"
5532 " local run = function (...)"
5533 " for n, s in pairs (self.instances) do"
5534 " local status, err = pcall (s, ...)"
5535 " if not status then"
5536 " print ('fn \"'.. n .. '\": ', err)"
5543 " local cleanup = function ()"
5544 " self.scripts = nil"
5545 " self.instances = nil"
5548 " local list = function ()"
5550 " for n, _ in pairs (self.scripts) do"
5556 " local function basic_serialize (o)"
5557 " if type(o) == \"number\" then"
5558 " return tostring(o)"
5560 " return string.format(\"%q\", o)"
5564 " local function serialize (name, value)"
5565 " local rv = name .. ' = '"
5567 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5568 " return rv .. basic_serialize(value) .. ' '"
5569 " elseif type(value) == \"table\" then"
5571 " for k,v in pairs(value) do"
5572 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5573 " rv = rv .. serialize(fieldname, v) .. ' '"
5574 " collectgarbage()" // string concatenation allocates a new string :(
5577 " elseif type(value) == \"function\" then"
5578 " return rv .. string.format(\"%q\", string.dump(value, true))"
5580 " error('cannot save a ' .. type(value))"
5585 " local save = function ()"
5586 " return (serialize('scripts', self.scripts))"
5589 " local restore = function (state)"
5590 " self.scripts = {}"
5592 " for n, s in pairs (scripts) do"
5593 " addinternal (n, load(s['f']), s['a'])"
5597 " return { run = run, add = add, remove = remove,"
5598 " list = list, restore = restore, save = save, cleanup = cleanup}"
5601 " sess = ArdourSession ()"
5602 " ArdourSession = nil"
5604 "function ardour () end"
5607 lua_State* L = lua.getState();
5610 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5611 lua.do_command ("sess = nil"); // hide it.
5612 lua.do_command ("collectgarbage()");
5614 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5615 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5616 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5617 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5618 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5619 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5620 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5621 } catch (luabridge::LuaException const& e) {
5622 fatal << string_compose (_("programming error: %1"),
5623 X_("Failed to setup Lua interpreter"))
5625 abort(); /*NOTREACHED*/
5628 LuaBindings::stddef (L);
5629 LuaBindings::common (L);
5630 LuaBindings::dsp (L);
5631 luabridge::push <Session *> (L, this);
5632 lua_setglobal (L, "Session");
5636 Session::scripts_changed ()
5638 assert (!lua_lock.trylock()); // must hold lua_lock
5641 luabridge::LuaRef list ((*_lua_list)());
5643 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5644 if (!i.key ().isString ()) { assert(0); continue; }
5647 _n_lua_scripts = cnt;
5648 } catch (luabridge::LuaException const& e) {
5649 fatal << string_compose (_("programming error: %1"),
5650 X_("Indexing Lua Session Scripts failed."))
5652 abort(); /*NOTREACHED*/
5657 Session::non_realtime_set_audition ()
5659 assert (pending_audition_region);
5660 auditioner->audition_region (pending_audition_region);
5661 pending_audition_region.reset ();
5662 AuditionActive (true); /* EMIT SIGNAL */
5666 Session::audition_region (boost::shared_ptr<Region> r)
5668 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5674 Session::cancel_audition ()
5679 if (auditioner->auditioning()) {
5680 auditioner->cancel_audition ();
5681 AuditionActive (false); /* EMIT SIGNAL */
5686 Session::is_auditioning () const
5688 /* can be called before we have an auditioner object */
5690 return auditioner->auditioning();
5697 Session::graph_reordered ()
5699 /* don't do this stuff if we are setting up connections
5700 from a set_state() call or creating new tracks. Ditto for deletion.
5703 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5707 /* every track/bus asked for this to be handled but it was deferred because
5708 we were connecting. do it now.
5711 request_input_change_handling ();
5715 /* force all diskstreams to update their capture offset values to
5716 reflect any changes in latencies within the graph.
5719 boost::shared_ptr<RouteList> rl = routes.reader ();
5720 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5721 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5723 tr->set_capture_offset ();
5728 /** @return Number of frames that there is disk space available to write,
5731 boost::optional<framecnt_t>
5732 Session::available_capture_duration ()
5734 Glib::Threads::Mutex::Lock lm (space_lock);
5736 if (_total_free_4k_blocks_uncertain) {
5737 return boost::optional<framecnt_t> ();
5740 float sample_bytes_on_disk = 4.0; // keep gcc happy
5742 switch (config.get_native_file_data_format()) {
5744 sample_bytes_on_disk = 4.0;
5748 sample_bytes_on_disk = 3.0;
5752 sample_bytes_on_disk = 2.0;
5756 /* impossible, but keep some gcc versions happy */
5757 fatal << string_compose (_("programming error: %1"),
5758 X_("illegal native file data format"))
5760 abort(); /*NOTREACHED*/
5763 double scale = 4096.0 / sample_bytes_on_disk;
5765 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5766 return max_framecnt;
5769 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5773 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5776 RCUWriter<BundleList> writer (_bundles);
5777 boost::shared_ptr<BundleList> b = writer.get_copy ();
5778 b->push_back (bundle);
5782 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5789 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5791 bool removed = false;
5794 RCUWriter<BundleList> writer (_bundles);
5795 boost::shared_ptr<BundleList> b = writer.get_copy ();
5796 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5798 if (i != b->end()) {
5805 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5811 boost::shared_ptr<Bundle>
5812 Session::bundle_by_name (string name) const
5814 boost::shared_ptr<BundleList> b = _bundles.reader ();
5816 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5817 if ((*i)->name() == name) {
5822 return boost::shared_ptr<Bundle> ();
5826 Session::tempo_map_changed (const PropertyChange&)
5830 playlists->update_after_tempo_map_change ();
5832 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5838 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5840 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5841 (*i)->recompute_frames_from_beat ();
5845 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5846 * the given count with the current block size.
5849 Session::ensure_buffers (ChanCount howmany)
5851 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5855 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5857 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5858 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5863 Session::next_insert_id ()
5865 /* this doesn't really loop forever. just think about it */
5868 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5869 if (!insert_bitset[n]) {
5870 insert_bitset[n] = true;
5876 /* none available, so resize and try again */
5878 insert_bitset.resize (insert_bitset.size() + 16, false);
5883 Session::next_send_id ()
5885 /* this doesn't really loop forever. just think about it */
5888 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5889 if (!send_bitset[n]) {
5890 send_bitset[n] = true;
5896 /* none available, so resize and try again */
5898 send_bitset.resize (send_bitset.size() + 16, false);
5903 Session::next_aux_send_id ()
5905 /* this doesn't really loop forever. just think about it */
5908 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5909 if (!aux_send_bitset[n]) {
5910 aux_send_bitset[n] = true;
5916 /* none available, so resize and try again */
5918 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5923 Session::next_return_id ()
5925 /* this doesn't really loop forever. just think about it */
5928 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5929 if (!return_bitset[n]) {
5930 return_bitset[n] = true;
5936 /* none available, so resize and try again */
5938 return_bitset.resize (return_bitset.size() + 16, false);
5943 Session::mark_send_id (uint32_t id)
5945 if (id >= send_bitset.size()) {
5946 send_bitset.resize (id+16, false);
5948 if (send_bitset[id]) {
5949 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5951 send_bitset[id] = true;
5955 Session::mark_aux_send_id (uint32_t id)
5957 if (id >= aux_send_bitset.size()) {
5958 aux_send_bitset.resize (id+16, false);
5960 if (aux_send_bitset[id]) {
5961 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5963 aux_send_bitset[id] = true;
5967 Session::mark_return_id (uint32_t id)
5969 if (id >= return_bitset.size()) {
5970 return_bitset.resize (id+16, false);
5972 if (return_bitset[id]) {
5973 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5975 return_bitset[id] = true;
5979 Session::mark_insert_id (uint32_t id)
5981 if (id >= insert_bitset.size()) {
5982 insert_bitset.resize (id+16, false);
5984 if (insert_bitset[id]) {
5985 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5987 insert_bitset[id] = true;
5991 Session::unmark_send_id (uint32_t id)
5993 if (id < send_bitset.size()) {
5994 send_bitset[id] = false;
5999 Session::unmark_aux_send_id (uint32_t id)
6001 if (id < aux_send_bitset.size()) {
6002 aux_send_bitset[id] = false;
6007 Session::unmark_return_id (uint32_t id)
6009 if (_state_of_the_state & Deletion) { return; }
6010 if (id < return_bitset.size()) {
6011 return_bitset[id] = false;
6016 Session::unmark_insert_id (uint32_t id)
6018 if (id < insert_bitset.size()) {
6019 insert_bitset[id] = false;
6024 Session::reset_native_file_format ()
6026 boost::shared_ptr<RouteList> rl = routes.reader ();
6028 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6029 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6031 /* don't save state as we do this, there's no point
6033 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
6034 tr->reset_write_sources (false);
6035 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
6041 Session::route_name_unique (string n) const
6043 boost::shared_ptr<RouteList> r = routes.reader ();
6045 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6046 if ((*i)->name() == n) {
6055 Session::route_name_internal (string n) const
6057 if (auditioner && auditioner->name() == n) {
6061 if (_click_io && _click_io->name() == n) {
6069 Session::freeze_all (InterThreadInfo& itt)
6071 boost::shared_ptr<RouteList> r = routes.reader ();
6073 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6075 boost::shared_ptr<Track> t;
6077 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6078 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6088 boost::shared_ptr<Region>
6089 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
6090 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6091 InterThreadInfo& itt,
6092 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6093 bool for_export, bool for_freeze)
6095 boost::shared_ptr<Region> result;
6096 boost::shared_ptr<Playlist> playlist;
6097 boost::shared_ptr<Source> source;
6098 ChanCount diskstream_channels (track.n_channels());
6099 framepos_t position;
6100 framecnt_t this_chunk;
6102 framepos_t latency_skip;
6104 framepos_t len = end - start;
6105 bool need_block_size_reset = false;
6106 ChanCount const max_proc = track.max_processor_streams ();
6107 string legal_playlist_name;
6108 string possible_path;
6111 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
6112 end, start) << endmsg;
6116 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
6117 include_endpoint, for_export, for_freeze);
6119 if (diskstream_channels.n(track.data_type()) < 1) {
6120 error << _("Cannot write a range with no data.") << endmsg;
6124 // block all process callback handling
6126 block_processing ();
6129 // synchronize with AudioEngine::process_callback()
6130 // make sure processing is not currently running
6131 // and processing_blocked() is honored before
6132 // acquiring thread buffers
6133 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6136 _bounce_processing_active = true;
6138 /* call tree *MUST* hold route_lock */
6140 if ((playlist = track.playlist()) == 0) {
6144 legal_playlist_name = legalize_for_path (playlist->name());
6146 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
6148 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6149 string path = ((track.data_type() == DataType::AUDIO)
6150 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6151 : new_midi_source_path (legal_playlist_name));
6158 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6161 catch (failed_constructor& err) {
6162 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6166 srcs.push_back (source);
6169 /* tell redirects that care that we are about to use a much larger
6170 * blocksize. this will flush all plugins too, so that they are ready
6171 * to be used for this process.
6174 need_block_size_reset = true;
6175 track.set_block_size (bounce_chunk_size);
6176 _engine.main_thread()->get_buffers ();
6180 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6182 /* create a set of reasonably-sized buffers */
6183 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6184 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6186 buffers.set_count (max_proc);
6188 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6189 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6190 boost::shared_ptr<MidiSource> ms;
6192 afs->prepare_for_peakfile_writes ();
6193 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6194 Source::Lock lock(ms->mutex());
6195 ms->mark_streaming_write_started(lock);
6199 while (to_do && !itt.cancel) {
6201 this_chunk = min (to_do, bounce_chunk_size);
6203 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6207 start += this_chunk;
6208 to_do -= this_chunk;
6209 itt.progress = (float) (1.0 - ((double) to_do / len));
6211 if (latency_skip >= bounce_chunk_size) {
6212 latency_skip -= bounce_chunk_size;
6216 const framecnt_t current_chunk = this_chunk - latency_skip;
6219 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6220 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6221 boost::shared_ptr<MidiSource> ms;
6224 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6227 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6228 Source::Lock lock(ms->mutex());
6230 const MidiBuffer& buf = buffers.get_midi(0);
6231 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6232 Evoral::Event<framepos_t> ev = *i;
6233 ev.set_time(ev.time() - position);
6234 ms->append_event_frames(lock, ev, ms->timeline_position());
6241 /* post-roll, pick up delayed processor output */
6242 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6244 while (latency_skip && !itt.cancel) {
6245 this_chunk = min (latency_skip, bounce_chunk_size);
6246 latency_skip -= this_chunk;
6248 buffers.silence (this_chunk, 0);
6249 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6252 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6253 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6256 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6268 xnow = localtime (&now);
6270 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6271 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6272 boost::shared_ptr<MidiSource> ms;
6275 afs->update_header (position, *xnow, now);
6276 afs->flush_header ();
6277 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6278 Source::Lock lock(ms->mutex());
6279 ms->mark_streaming_write_completed(lock);
6283 /* construct a region to represent the bounced material */
6287 plist.add (Properties::start, 0);
6288 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6289 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6291 result = RegionFactory::create (srcs, plist);
6297 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6298 (*src)->mark_for_remove ();
6299 (*src)->drop_references ();
6303 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6304 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6307 afs->done_with_peakfile_writes ();
6311 _bounce_processing_active = false;
6313 if (need_block_size_reset) {
6314 _engine.main_thread()->drop_buffers ();
6315 track.set_block_size (get_block_size());
6318 unblock_processing ();
6324 Session::gain_automation_buffer() const
6326 return ProcessThread::gain_automation_buffer ();
6330 Session::trim_automation_buffer() const
6332 return ProcessThread::trim_automation_buffer ();
6336 Session::send_gain_automation_buffer() const
6338 return ProcessThread::send_gain_automation_buffer ();
6342 Session::scratch_automation_buffer() const
6344 return ProcessThread::scratch_automation_buffer ();
6348 Session::pan_automation_buffer() const
6350 return ProcessThread::pan_automation_buffer ();
6354 Session::get_silent_buffers (ChanCount count)
6356 return ProcessThread::get_silent_buffers (count);
6360 Session::get_scratch_buffers (ChanCount count, bool silence)
6362 return ProcessThread::get_scratch_buffers (count, silence);
6366 Session::get_noinplace_buffers (ChanCount count)
6368 return ProcessThread::get_noinplace_buffers (count);
6372 Session::get_route_buffers (ChanCount count, bool silence)
6374 return ProcessThread::get_route_buffers (count, silence);
6379 Session::get_mix_buffers (ChanCount count)
6381 return ProcessThread::get_mix_buffers (count);
6385 Session::ntracks () const
6388 boost::shared_ptr<RouteList> r = routes.reader ();
6390 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6391 if (boost::dynamic_pointer_cast<Track> (*i)) {
6400 Session::nbusses () const
6403 boost::shared_ptr<RouteList> r = routes.reader ();
6405 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6406 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6415 Session::nstripables (bool with_auditioner_and_monitor) const
6417 uint32_t rv = routes.reader()->size ();
6418 rv += _vca_manager->vcas ().size ();
6420 if (with_auditioner_and_monitor) {
6436 Session::add_automation_list(AutomationList *al)
6438 automation_lists[al->id()] = al;
6441 /** @return true if there is at least one record-enabled track, otherwise false */
6443 Session::have_rec_enabled_track () const
6445 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6449 Session::have_rec_disabled_track () const
6451 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6454 /** Update the state of our rec-enabled tracks flag */
6456 Session::update_route_record_state ()
6458 boost::shared_ptr<RouteList> rl = routes.reader ();
6459 RouteList::iterator i = rl->begin();
6460 while (i != rl->end ()) {
6462 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6463 if (tr && tr->rec_enable_control()->get_value()) {
6470 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6472 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6474 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6475 RecordStateChanged (); /* EMIT SIGNAL */
6478 for (i = rl->begin(); i != rl->end (); ++i) {
6479 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6480 if (tr && !tr->rec_enable_control()->get_value()) {
6485 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6487 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6489 if (record_status() == Recording && record_arm_state_changed ) {
6490 RecordArmStateChanged ();
6496 Session::listen_position_changed ()
6498 ProcessorChangeBlocker pcb (this);
6499 boost::shared_ptr<RouteList> r = routes.reader ();
6500 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6501 (*i)->listen_position_changed ();
6506 Session::solo_control_mode_changed ()
6508 if (soloing() || listening()) {
6510 /* We can't use ::clear_all_solo_state() here because during
6511 session loading at program startup, that will queue a call
6512 to rt_clear_all_solo_state() that will not execute until
6513 AFTER solo states have been established (thus throwing away
6514 the session's saved solo state). So just explicitly turn
6517 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6519 clear_all_solo_state (get_routes());
6524 /** Called when a property of one of our route groups changes */
6526 Session::route_group_property_changed (RouteGroup* rg)
6528 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6531 /** Called when a route is added to one of our route groups */
6533 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6535 RouteAddedToRouteGroup (rg, r);
6538 /** Called when a route is removed from one of our route groups */
6540 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6542 update_route_record_state ();
6543 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6545 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6546 remove_route_group (*rg);
6550 boost::shared_ptr<RouteList>
6551 Session::get_tracks () const
6553 boost::shared_ptr<RouteList> rl = routes.reader ();
6554 boost::shared_ptr<RouteList> tl (new RouteList);
6556 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6557 if (boost::dynamic_pointer_cast<Track> (*r)) {
6558 if (!(*r)->is_auditioner()) {
6566 boost::shared_ptr<RouteList>
6567 Session::get_routes_with_regions_at (framepos_t const p) const
6569 boost::shared_ptr<RouteList> r = routes.reader ();
6570 boost::shared_ptr<RouteList> rl (new RouteList);
6572 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6573 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6578 boost::shared_ptr<Playlist> pl = tr->playlist ();
6583 if (pl->has_region_at (p)) {
6592 Session::goto_end ()
6594 if (_session_range_location) {
6595 request_locate (_session_range_location->end(), false);
6597 request_locate (0, false);
6602 Session::goto_start (bool and_roll)
6604 if (_session_range_location) {
6605 request_locate (_session_range_location->start(), and_roll);
6607 request_locate (0, and_roll);
6612 Session::current_start_frame () const
6614 return _session_range_location ? _session_range_location->start() : 0;
6618 Session::current_end_frame () const
6620 return _session_range_location ? _session_range_location->end() : 0;
6624 Session::set_session_range_location (framepos_t start, framepos_t end)
6626 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6627 _locations->add (_session_range_location);
6631 Session::step_edit_status_change (bool yn)
6637 send = (_step_editors == 0);
6642 send = (_step_editors == 1);
6645 if (_step_editors > 0) {
6651 StepEditStatusChange (val);
6657 Session::start_time_changed (framepos_t old)
6659 /* Update the auto loop range to match the session range
6660 (unless the auto loop range has been changed by the user)
6663 Location* s = _locations->session_range_location ();
6668 Location* l = _locations->auto_loop_location ();
6670 if (l && l->start() == old) {
6671 l->set_start (s->start(), true);
6677 Session::end_time_changed (framepos_t old)
6679 /* Update the auto loop range to match the session range
6680 (unless the auto loop range has been changed by the user)
6683 Location* s = _locations->session_range_location ();
6688 Location* l = _locations->auto_loop_location ();
6690 if (l && l->end() == old) {
6691 l->set_end (s->end(), true);
6696 std::vector<std::string>
6697 Session::source_search_path (DataType type) const
6701 if (session_dirs.size() == 1) {
6703 case DataType::AUDIO:
6704 sp.push_back (_session_dir->sound_path());
6706 case DataType::MIDI:
6707 sp.push_back (_session_dir->midi_path());
6711 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6712 SessionDirectory sdir (i->path);
6714 case DataType::AUDIO:
6715 sp.push_back (sdir.sound_path());
6717 case DataType::MIDI:
6718 sp.push_back (sdir.midi_path());
6724 if (type == DataType::AUDIO) {
6725 const string sound_path_2X = _session_dir->sound_path_2X();
6726 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6727 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6728 sp.push_back (sound_path_2X);
6733 // now check the explicit (possibly user-specified) search path
6736 case DataType::AUDIO:
6737 sp += Searchpath(config.get_audio_search_path ());
6739 case DataType::MIDI:
6740 sp += Searchpath(config.get_midi_search_path ());
6748 Session::ensure_search_path_includes (const string& path, DataType type)
6757 case DataType::AUDIO:
6758 sp += Searchpath(config.get_audio_search_path ());
6760 case DataType::MIDI:
6761 sp += Searchpath (config.get_midi_search_path ());
6765 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6766 /* No need to add this new directory if it has the same inode as
6767 an existing one; checking inode rather than name prevents duplicated
6768 directories when we are using symlinks.
6770 On Windows, I think we could just do if (*i == path) here.
6772 if (PBD::equivalent_paths (*i, path)) {
6780 case DataType::AUDIO:
6781 config.set_audio_search_path (sp.to_string());
6783 case DataType::MIDI:
6784 config.set_midi_search_path (sp.to_string());
6790 Session::remove_dir_from_search_path (const string& dir, DataType type)
6795 case DataType::AUDIO:
6796 sp = Searchpath(config.get_audio_search_path ());
6798 case DataType::MIDI:
6799 sp = Searchpath (config.get_midi_search_path ());
6806 case DataType::AUDIO:
6807 config.set_audio_search_path (sp.to_string());
6809 case DataType::MIDI:
6810 config.set_midi_search_path (sp.to_string());
6816 boost::shared_ptr<Speakers>
6817 Session::get_speakers()
6823 Session::unknown_processors () const
6827 boost::shared_ptr<RouteList> r = routes.reader ();
6828 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6829 list<string> t = (*i)->unknown_processors ();
6830 copy (t.begin(), t.end(), back_inserter (p));
6840 Session::update_latency (bool playback)
6843 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6845 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6848 if (!_engine.running()) {
6852 boost::shared_ptr<RouteList> r = routes.reader ();
6853 framecnt_t max_latency = 0;
6856 /* reverse the list so that we work backwards from the last route to run to the first */
6857 RouteList* rl = routes.reader().get();
6858 r.reset (new RouteList (*rl));
6859 reverse (r->begin(), r->end());
6862 /* compute actual latency values for the given direction and store them all in per-port
6863 structures. this will also publish the same values (to JACK) so that computation of latency
6864 for routes can consistently use public latency values.
6867 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6868 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6871 /* because we latency compensate playback, our published playback latencies should
6872 be the same for all output ports - all material played back by ardour has
6873 the same latency, whether its caused by plugins or by latency compensation. since
6874 these may differ from the values computed above, reset all playback port latencies
6878 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6880 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6881 (*i)->set_public_port_latencies (max_latency, playback);
6886 post_playback_latency ();
6890 post_capture_latency ();
6893 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6897 Session::post_playback_latency ()
6899 set_worst_playback_latency ();
6901 boost::shared_ptr<RouteList> r = routes.reader ();
6903 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6904 if (!(*i)->is_auditioner() && ((*i)->active())) {
6905 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6909 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6910 (*i)->set_latency_compensation (_worst_track_latency);
6915 Session::post_capture_latency ()
6917 set_worst_capture_latency ();
6919 /* reflect any changes in capture latencies into capture offsets
6922 boost::shared_ptr<RouteList> rl = routes.reader();
6923 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6924 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6926 tr->set_capture_offset ();
6932 Session::initialize_latencies ()
6935 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6936 update_latency (false);
6937 update_latency (true);
6940 set_worst_io_latencies ();
6944 Session::set_worst_io_latencies ()
6946 set_worst_playback_latency ();
6947 set_worst_capture_latency ();
6951 Session::set_worst_playback_latency ()
6953 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6957 _worst_output_latency = 0;
6959 if (!_engine.connected()) {
6963 boost::shared_ptr<RouteList> r = routes.reader ();
6965 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6966 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6969 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6973 Session::set_worst_capture_latency ()
6975 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6979 _worst_input_latency = 0;
6981 if (!_engine.connected()) {
6985 boost::shared_ptr<RouteList> r = routes.reader ();
6987 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6988 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6991 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6995 Session::update_latency_compensation (bool force_whole_graph)
6997 bool some_track_latency_changed = false;
6999 if (_state_of_the_state & (InitialConnecting|Deletion)) {
7003 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
7005 _worst_track_latency = 0;
7007 boost::shared_ptr<RouteList> r = routes.reader ();
7009 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7010 if (!(*i)->is_auditioner() && ((*i)->active())) {
7012 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
7013 some_track_latency_changed = true;
7015 _worst_track_latency = max (tl, _worst_track_latency);
7019 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
7020 (some_track_latency_changed ? "yes" : "no")));
7022 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
7024 if (some_track_latency_changed || force_whole_graph) {
7025 _engine.update_latencies ();
7029 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7030 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
7034 tr->set_capture_offset ();
7039 Session::session_name_is_legal (const string& path)
7041 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7043 for (int i = 0; illegal_chars[i]; ++i) {
7044 if (path.find (illegal_chars[i]) != string::npos) {
7045 return illegal_chars[i];
7053 Session::notify_presentation_info_change ()
7055 if (deletion_in_progress()) {
7059 reassign_track_numbers();
7061 #ifdef USE_TRACKS_CODE_FEATURES
7062 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7063 * if track order has been changed by user
7065 reconnect_existing_routes(true, true);
7071 Session::operation_in_progress (GQuark op) const
7073 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7076 boost::shared_ptr<Port>
7077 Session::ltc_input_port () const
7079 assert (_ltc_input);
7080 return _ltc_input->nth (0);
7083 boost::shared_ptr<Port>
7084 Session::ltc_output_port () const
7086 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
7090 Session::reconnect_ltc_input ()
7094 string src = Config->get_ltc_source_port();
7096 _ltc_input->disconnect (this);
7098 if (src != _("None") && !src.empty()) {
7099 _ltc_input->nth (0)->connect (src);
7102 if ( ARDOUR::Profile->get_trx () ) {
7103 // Tracks need this signal to update timecode_source_dropdown
7104 MtcOrLtcInputPortChanged (); //emit signal
7110 Session::reconnect_ltc_output ()
7114 string src = Config->get_ltc_output_port();
7116 _ltc_output->disconnect (this);
7118 if (src != _("None") && !src.empty()) {
7119 _ltc_output->nth (0)->connect (src);
7125 Session::set_range_selection (framepos_t start, framepos_t end)
7127 _range_selection = Evoral::Range<framepos_t> (start, end);
7128 #ifdef USE_TRACKS_CODE_FEATURES
7129 follow_playhead_priority ();
7134 Session::set_object_selection (framepos_t start, framepos_t end)
7136 _object_selection = Evoral::Range<framepos_t> (start, end);
7137 #ifdef USE_TRACKS_CODE_FEATURES
7138 follow_playhead_priority ();
7143 Session::clear_range_selection ()
7145 _range_selection = Evoral::Range<framepos_t> (-1,-1);
7146 #ifdef USE_TRACKS_CODE_FEATURES
7147 follow_playhead_priority ();
7152 Session::clear_object_selection ()
7154 _object_selection = Evoral::Range<framepos_t> (-1,-1);
7155 #ifdef USE_TRACKS_CODE_FEATURES
7156 follow_playhead_priority ();
7161 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7162 const ChanCount& input_start,
7163 const ChanCount& output_start,
7164 const ChanCount& input_offset,
7165 const ChanCount& output_offset)
7167 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7168 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7169 input_start, output_start,
7170 input_offset, output_offset));
7172 auto_connect_thread_wakeup ();
7176 Session::auto_connect_thread_wakeup ()
7178 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7179 pthread_cond_signal (&_auto_connect_cond);
7180 pthread_mutex_unlock (&_auto_connect_mutex);
7185 Session::queue_latency_recompute ()
7187 g_atomic_int_inc (&_latency_recompute_pending);
7188 auto_connect_thread_wakeup ();
7192 Session::auto_connect (const AutoConnectRequest& ar)
7194 boost::shared_ptr<Route> route = ar.route.lock();
7196 if (!route) { return; }
7198 if (!IO::connecting_legal) {
7202 /* If both inputs and outputs are auto-connected to physical ports,
7203 * use the max of input and output offsets to ensure auto-connected
7204 * port numbers always match up (e.g. the first audio input and the
7205 * first audio output of the route will have the same physical
7206 * port number). Otherwise just use the lowest input or output
7210 const bool in_out_physical =
7211 (Config->get_input_auto_connect() & AutoConnectPhysical)
7212 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7213 && ar.connect_inputs;
7215 const ChanCount in_offset = in_out_physical
7216 ? ChanCount::max(ar.input_offset, ar.output_offset)
7219 const ChanCount out_offset = in_out_physical
7220 ? ChanCount::max(ar.input_offset, ar.output_offset)
7223 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7224 vector<string> physinputs;
7225 vector<string> physoutputs;
7228 /* for connecting track inputs we only want MIDI ports marked
7232 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7234 if (!physinputs.empty() && ar.connect_inputs) {
7235 uint32_t nphysical_in = physinputs.size();
7237 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7240 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7241 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7244 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7250 if (!physoutputs.empty()) {
7251 uint32_t nphysical_out = physoutputs.size();
7252 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7256 * do not create new connections if we reached the limit of physical outputs
7259 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7260 ARDOUR::Profile->get_trx () &&
7261 ar.output_offset.get(*t) == nphysical_out ) {
7265 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7266 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7267 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7268 /* master bus is audio only */
7269 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7270 port = _master_out->input()->ports().port(*t,
7271 i % _master_out->input()->n_ports().get(*t))->name();
7275 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7284 Session::auto_connect_thread_start ()
7286 if (g_atomic_int_get (&_ac_thread_active)) {
7290 while (!_auto_connect_queue.empty ()) {
7291 _auto_connect_queue.pop ();
7294 g_atomic_int_set (&_ac_thread_active, 1);
7295 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7296 g_atomic_int_set (&_ac_thread_active, 0);
7301 Session::auto_connect_thread_terminate ()
7303 if (!g_atomic_int_get (&_ac_thread_active)) {
7308 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7309 while (!_auto_connect_queue.empty ()) {
7310 _auto_connect_queue.pop ();
7314 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7315 * fail to wakeup the thread.
7318 pthread_mutex_lock (&_auto_connect_mutex);
7319 g_atomic_int_set (&_ac_thread_active, 0);
7320 pthread_cond_signal (&_auto_connect_cond);
7321 pthread_mutex_unlock (&_auto_connect_mutex);
7324 pthread_join (_auto_connect_thread, &status);
7328 Session::auto_connect_thread (void *arg)
7330 Session *s = static_cast<Session *>(arg);
7331 s->auto_connect_thread_run ();
7337 Session::auto_connect_thread_run ()
7339 pthread_set_name (X_("autoconnect"));
7340 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7341 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7342 pthread_mutex_lock (&_auto_connect_mutex);
7343 while (g_atomic_int_get (&_ac_thread_active)) {
7345 if (!_auto_connect_queue.empty ()) {
7346 // Why would we need the process lock ??
7347 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7348 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7349 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7350 // We have control over those, but what does jack do?
7351 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7353 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7354 while (!_auto_connect_queue.empty ()) {
7355 const AutoConnectRequest ar (_auto_connect_queue.front());
7356 _auto_connect_queue.pop ();
7363 if (!actively_recording ()) { // might not be needed,
7364 /* this is only used for updating plugin latencies, the
7365 * graph does not change. so it's safe in general.
7367 * .. update_latency_compensation () entails set_capture_offset()
7368 * which calls Diskstream::set_capture_offset () which
7369 * modifies the capture offset... which can be a proplem
7370 * in "prepare_to_stop"
7372 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7373 update_latency_compensation ();
7378 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7379 // jack1 cannot cope with removing ports while processing
7380 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7381 AudioEngine::instance()->clear_pending_port_deletions ();
7384 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7386 pthread_mutex_unlock (&_auto_connect_mutex);
7390 Session::cancel_all_solo ()
7394 get_stripables (sl);
7396 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7397 clear_all_solo_state (routes.reader());