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 /* disconnect from any and all signals that we are connected to */
649 Port::PortSignalDrop (); /* EMIT SIGNAL */
652 /* shutdown control surface protocols while we still have ports
653 and the engine to move data to any devices.
656 ControlProtocolManager::instance().drop_protocols ();
658 /* stop auto dis/connecting */
659 auto_connect_thread_terminate ();
661 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
663 _engine.remove_session ();
665 #ifdef USE_TRACKS_CODE_FEATURES
666 EngineStateController::instance()->remove_session();
669 /* deregister all ports - there will be no process or any other
670 * callbacks from the engine any more.
673 Port::PortDrop (); /* EMIT SIGNAL */
675 /* clear history so that no references to objects are held any more */
679 /* clear state tree so that no references to objects are held any more */
685 /* unregister all lua functions, drop held references (if any) */
686 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
688 lua.do_command ("Session = nil");
696 lua.collect_garbage ();
699 /* reset dynamic state version back to default */
700 Stateful::loading_state_version = 0;
702 _butler->drop_references ();
706 delete _all_route_group;
708 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
709 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
713 if (click_data != default_click) {
714 delete [] click_data;
717 if (click_emphasis_data != default_click_emphasis) {
718 delete [] click_emphasis_data;
723 /* need to remove auditioner before monitoring section
724 * otherwise it is re-connected */
727 /* drop references to routes held by the monitoring section
728 * specifically _monitor_out aux/listen references */
729 remove_monitor_section();
731 /* clear out any pending dead wood from RCU managed objects */
736 AudioDiskstream::free_working_buffers();
738 /* tell everyone who is still standing that we're about to die */
741 /* tell everyone to drop references and delete objects as we go */
743 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
744 RegionFactory::delete_all_regions ();
746 /* Do this early so that VCAs no longer hold references to routes */
748 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
751 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
753 /* reset these three references to special routes before we do the usual route delete thing */
755 _master_out.reset ();
756 _monitor_out.reset ();
759 RCUWriter<RouteList> writer (routes);
760 boost::shared_ptr<RouteList> r = writer.get_copy ();
762 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
763 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
764 (*i)->drop_references ();
768 /* writer goes out of scope and updates master */
773 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
774 Glib::Threads::Mutex::Lock lm (source_lock);
775 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
776 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
777 i->second->drop_references ();
783 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
786 emit_thread_terminate ();
788 pthread_cond_destroy (&_rt_emit_cond);
789 pthread_mutex_destroy (&_rt_emit_mutex);
791 pthread_cond_destroy (&_auto_connect_cond);
792 pthread_mutex_destroy (&_auto_connect_mutex);
794 delete _scene_changer; _scene_changer = 0;
795 delete midi_control_ui; midi_control_ui = 0;
797 delete _mmc; _mmc = 0;
798 delete _midi_ports; _midi_ports = 0;
799 delete _locations; _locations = 0;
804 /* clear event queue, the session is gone, nobody is interested in
805 * those anymore, but they do leak memory if not removed
807 while (!immediate_events.empty ()) {
808 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
809 SessionEvent *ev = immediate_events.front ();
810 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
811 immediate_events.pop_front ();
815 case SessionEvent::AutoLoop:
816 case SessionEvent::AutoLoopDeclick:
817 case SessionEvent::Skip:
818 case SessionEvent::PunchIn:
819 case SessionEvent::PunchOut:
820 case SessionEvent::RecordStart:
821 case SessionEvent::StopOnce:
822 case SessionEvent::RangeStop:
823 case SessionEvent::RangeLocate:
827 case SessionEvent::RealTimeOperation:
834 del = del && !_remove_event (ev);
842 /* unregister all dropped ports, process pending port deletion. */
843 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
844 // jack1 cannot cope with removing ports while processing
845 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
846 AudioEngine::instance()->clear_pending_port_deletions ();
849 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
853 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
855 BOOST_SHOW_POINTERS ();
859 Session::setup_ltc ()
863 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
864 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
866 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
867 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
870 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
871 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
872 // TODO use auto-connect thread somehow (needs a route currently)
873 // see note in Session::auto_connect_thread_run() why process lock is needed.
874 reconnect_ltc_input ();
878 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
879 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
882 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
883 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
884 // TODO use auto-connect thread
885 reconnect_ltc_output ();
889 /* fix up names of LTC ports because we don't want the normal
890 * IO style of NAME/TYPE-{in,out}N
893 _ltc_input->nth (0)->set_name (X_("LTC-in"));
894 _ltc_output->nth (0)->set_name (X_("LTC-out"));
898 Session::setup_click ()
902 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
903 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
905 _click_io.reset (new ClickIO (*this, X_("Click")));
906 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
907 _click_gain->activate ();
909 setup_click_state (state_tree->root());
911 setup_click_state (0);
916 Session::setup_click_state (const XMLNode* node)
918 const XMLNode* child = 0;
920 if (node && (child = find_named_node (*node, "Click")) != 0) {
922 /* existing state for Click */
925 if (Stateful::loading_state_version < 3000) {
926 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
928 const XMLNodeList& children (child->children());
929 XMLNodeList::const_iterator i = children.begin();
930 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
932 if (i != children.end()) {
933 c = _click_gain->set_state (**i, Stateful::loading_state_version);
939 _clicking = Config->get_clicking ();
943 error << _("could not setup Click I/O") << endmsg;
950 /* default state for Click: dual-mono to first 2 physical outputs */
953 _engine.get_physical_outputs (DataType::AUDIO, outs);
955 for (uint32_t physport = 0; physport < 2; ++physport) {
956 if (outs.size() > physport) {
957 if (_click_io->add_port (outs[physport], this)) {
958 // relax, even though its an error
963 if (_click_io->n_ports () > ChanCount::ZERO) {
964 _clicking = Config->get_clicking ();
970 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
971 MidiPortFlags include, MidiPortFlags exclude)
973 _engine.get_physical_inputs (type, inputs, include, exclude);
974 _engine.get_physical_outputs (type, outputs, include, exclude);
978 Session::setup_bundles ()
982 RCUWriter<BundleList> writer (_bundles);
983 boost::shared_ptr<BundleList> b = writer.get_copy ();
984 for (BundleList::iterator i = b->begin(); i != b->end();) {
985 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
993 vector<string> inputs[DataType::num_types];
994 vector<string> outputs[DataType::num_types];
996 for (uint32_t i = 0; i < DataType::num_types; ++i) {
997 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
998 MidiPortFlags (0), /* no specific inclusions */
999 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1003 /* Create a set of Bundle objects that map
1004 to the physical I/O currently available. We create both
1005 mono and stereo bundles, so that the common cases of mono
1006 and stereo tracks get bundles to put in their mixer strip
1007 in / out menus. There may be a nicer way of achieving that;
1008 it doesn't really scale that well to higher channel counts
1011 /* mono output bundles */
1013 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1015 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1017 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1019 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1022 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1023 c->add_channel (_("mono"), DataType::AUDIO);
1024 c->set_port (0, outputs[DataType::AUDIO][np]);
1026 add_bundle (c, false);
1029 /* stereo output bundles */
1031 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1032 if (np + 1 < outputs[DataType::AUDIO].size()) {
1034 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1035 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1036 c->add_channel (_("L"), DataType::AUDIO);
1037 c->set_port (0, outputs[DataType::AUDIO][np]);
1038 c->add_channel (_("R"), DataType::AUDIO);
1039 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1041 add_bundle (c, false);
1045 /* mono input bundles */
1047 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1049 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1051 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1053 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1056 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1057 c->add_channel (_("mono"), DataType::AUDIO);
1058 c->set_port (0, inputs[DataType::AUDIO][np]);
1060 add_bundle (c, false);
1063 /* stereo input bundles */
1065 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1066 if (np + 1 < inputs[DataType::AUDIO].size()) {
1068 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1070 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1071 c->add_channel (_("L"), DataType::AUDIO);
1072 c->set_port (0, inputs[DataType::AUDIO][np]);
1073 c->add_channel (_("R"), DataType::AUDIO);
1074 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1076 add_bundle (c, false);
1080 /* MIDI input bundles */
1082 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1083 string n = inputs[DataType::MIDI][np];
1085 std::string pn = _engine.get_pretty_name_by_name (n);
1089 boost::erase_first (n, X_("alsa_pcm:"));
1091 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1092 c->add_channel ("", DataType::MIDI);
1093 c->set_port (0, inputs[DataType::MIDI][np]);
1094 add_bundle (c, false);
1097 /* MIDI output bundles */
1099 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1100 string n = outputs[DataType::MIDI][np];
1101 std::string pn = _engine.get_pretty_name_by_name (n);
1105 boost::erase_first (n, X_("alsa_pcm:"));
1107 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1108 c->add_channel ("", DataType::MIDI);
1109 c->set_port (0, outputs[DataType::MIDI][np]);
1110 add_bundle (c, false);
1113 // we trust the backend to only calls us if there's a change
1114 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1118 Session::auto_connect_master_bus ()
1120 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1124 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1125 // In this case it means "Multi Out" output mode
1126 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1130 /* if requested auto-connect the outputs to the first N physical ports.
1133 uint32_t limit = _master_out->n_outputs().n_total();
1134 vector<string> outputs[DataType::num_types];
1136 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1137 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1140 for (uint32_t n = 0; n < limit; ++n) {
1141 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1143 if (outputs[p->type()].size() > n) {
1144 connect_to = outputs[p->type()][n];
1147 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1148 if (_master_out->output()->connect (p, connect_to, this)) {
1149 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1158 Session::remove_monitor_section ()
1160 if (!_monitor_out || Profile->get_trx()) {
1164 /* force reversion to Solo-In-Place */
1165 Config->set_solo_control_is_listen_control (false);
1167 /* if we are auditioning, cancel it ... this is a workaround
1168 to a problem (auditioning does not execute the process graph,
1169 which is needed to remove routes when using >1 core for processing)
1174 /* Hold process lock while doing this so that we don't hear bits and
1175 * pieces of audio as we work on each route.
1178 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1180 /* Connect tracks to monitor section. Note that in an
1181 existing session, the internal sends will already exist, but we want the
1182 routes to notice that they connect to the control out specifically.
1186 boost::shared_ptr<RouteList> r = routes.reader ();
1187 ProcessorChangeBlocker pcb (this, false);
1189 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1191 if ((*x)->is_monitor()) {
1193 } else if ((*x)->is_master()) {
1196 (*x)->remove_aux_or_listen (_monitor_out);
1201 remove_route (_monitor_out);
1202 if (_state_of_the_state & Deletion) {
1206 auto_connect_master_bus ();
1209 auditioner->connect ();
1212 Config->ParameterChanged ("use-monitor-bus");
1216 Session::add_monitor_section ()
1220 if (_monitor_out || !_master_out || Profile->get_trx()) {
1224 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1230 BOOST_MARK_ROUTE(r);
1233 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1234 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1235 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1237 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1242 add_routes (rl, false, false, false, 0);
1244 assert (_monitor_out);
1246 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1247 are undefined, at best.
1250 uint32_t limit = _monitor_out->n_inputs().n_audio();
1254 /* connect the inputs to the master bus outputs. this
1255 * represents a separate data feed from the internal sends from
1256 * each route. as of jan 2011, it allows the monitor section to
1257 * conditionally ignore either the internal sends or the normal
1258 * input feed, but we should really find a better way to do
1262 _master_out->output()->disconnect (this);
1264 for (uint32_t n = 0; n < limit; ++n) {
1265 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1266 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1269 string connect_to = o->name();
1270 if (_monitor_out->input()->connect (p, connect_to, this)) {
1271 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1279 /* if monitor section is not connected, connect it to physical outs
1282 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1284 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1286 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1289 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1291 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1292 Config->get_monitor_bus_preferred_bundle())
1298 /* Monitor bus is audio only */
1300 vector<string> outputs[DataType::num_types];
1302 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1303 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1306 uint32_t mod = outputs[DataType::AUDIO].size();
1307 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1311 for (uint32_t n = 0; n < limit; ++n) {
1313 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1315 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1316 connect_to = outputs[DataType::AUDIO][n % mod];
1319 if (!connect_to.empty()) {
1320 if (_monitor_out->output()->connect (p, connect_to, this)) {
1321 error << string_compose (
1322 _("cannot connect control output %1 to %2"),
1333 /* Hold process lock while doing this so that we don't hear bits and
1334 * pieces of audio as we work on each route.
1337 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1339 /* Connect tracks to monitor section. Note that in an
1340 existing session, the internal sends will already exist, but we want the
1341 routes to notice that they connect to the control out specifically.
1345 boost::shared_ptr<RouteList> rls = routes.reader ();
1347 ProcessorChangeBlocker pcb (this, false /* XXX */);
1349 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1351 if ((*x)->is_monitor()) {
1353 } else if ((*x)->is_master()) {
1356 (*x)->enable_monitor_send ();
1361 auditioner->connect ();
1363 Config->ParameterChanged ("use-monitor-bus");
1367 Session::reset_monitor_section ()
1369 /* Process lock should be held by the caller.*/
1371 if (!_monitor_out || Profile->get_trx()) {
1375 uint32_t limit = _master_out->n_outputs().n_audio();
1377 /* connect the inputs to the master bus outputs. this
1378 * represents a separate data feed from the internal sends from
1379 * each route. as of jan 2011, it allows the monitor section to
1380 * conditionally ignore either the internal sends or the normal
1381 * input feed, but we should really find a better way to do
1385 _master_out->output()->disconnect (this);
1386 _monitor_out->output()->disconnect (this);
1388 // monitor section follow master bus - except midi
1389 ChanCount mon_chn (_master_out->output()->n_ports());
1390 mon_chn.set_midi (0);
1392 _monitor_out->input()->ensure_io (mon_chn, false, this);
1393 _monitor_out->output()->ensure_io (mon_chn, false, this);
1395 for (uint32_t n = 0; n < limit; ++n) {
1396 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1397 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1400 string connect_to = o->name();
1401 if (_monitor_out->input()->connect (p, connect_to, this)) {
1402 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1409 /* connect monitor section to physical outs
1412 if (Config->get_auto_connect_standard_busses()) {
1414 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1416 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1419 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1421 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1422 Config->get_monitor_bus_preferred_bundle())
1428 /* Monitor bus is audio only */
1430 vector<string> outputs[DataType::num_types];
1432 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1433 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1436 uint32_t mod = outputs[DataType::AUDIO].size();
1437 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1441 for (uint32_t n = 0; n < limit; ++n) {
1443 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1445 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1446 connect_to = outputs[DataType::AUDIO][n % mod];
1449 if (!connect_to.empty()) {
1450 if (_monitor_out->output()->connect (p, connect_to, this)) {
1451 error << string_compose (
1452 _("cannot connect control output %1 to %2"),
1463 /* Connect tracks to monitor section. Note that in an
1464 existing session, the internal sends will already exist, but we want the
1465 routes to notice that they connect to the control out specifically.
1469 boost::shared_ptr<RouteList> rls = routes.reader ();
1471 ProcessorChangeBlocker pcb (this, false);
1473 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1475 if ((*x)->is_monitor()) {
1477 } else if ((*x)->is_master()) {
1480 (*x)->enable_monitor_send ();
1486 Session::hookup_io ()
1488 /* stop graph reordering notifications from
1489 causing resorts, etc.
1492 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1496 /* we delay creating the auditioner till now because
1497 it makes its own connections to ports.
1501 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1503 throw failed_constructor ();
1505 a->use_new_diskstream ();
1509 catch (failed_constructor& err) {
1510 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1514 /* load bundles, which we may have postponed earlier on */
1515 if (_bundle_xml_node) {
1516 load_bundles (*_bundle_xml_node);
1517 delete _bundle_xml_node;
1520 /* Tell all IO objects to connect themselves together */
1522 IO::enable_connecting ();
1524 /* Now tell all "floating" ports to connect to whatever
1525 they should be connected to.
1528 AudioEngine::instance()->reconnect_ports ();
1530 /* Anyone who cares about input state, wake up and do something */
1532 IOConnectionsComplete (); /* EMIT SIGNAL */
1534 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1536 /* now handle the whole enchilada as if it was one
1537 graph reorder event.
1542 /* update the full solo state, which can't be
1543 correctly determined on a per-route basis, but
1544 needs the global overview that only the session
1548 update_route_solo_state ();
1552 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1554 boost::shared_ptr<Track> track = wp.lock ();
1559 boost::shared_ptr<Playlist> playlist;
1561 if ((playlist = track->playlist()) != 0) {
1562 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1563 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1564 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1569 Session::record_enabling_legal () const
1571 /* this used to be in here, but survey says.... we don't need to restrict it */
1572 // if (record_status() == Recording) {
1576 if (Config->get_all_safe()) {
1583 Session::set_track_monitor_input_status (bool yn)
1585 boost::shared_ptr<RouteList> rl = routes.reader ();
1586 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1587 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1588 if (tr && tr->rec_enable_control()->get_value()) {
1589 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1590 tr->request_input_monitoring (yn);
1596 Session::auto_punch_start_changed (Location* location)
1598 replace_event (SessionEvent::PunchIn, location->start());
1600 if (get_record_enabled() && config.get_punch_in()) {
1601 /* capture start has been changed, so save new pending state */
1602 save_state ("", true);
1607 Session::auto_punch_end_changed (Location* location)
1609 framepos_t when_to_stop = location->end();
1610 // when_to_stop += _worst_output_latency + _worst_input_latency;
1611 replace_event (SessionEvent::PunchOut, when_to_stop);
1615 Session::auto_punch_changed (Location* location)
1617 framepos_t when_to_stop = location->end();
1619 replace_event (SessionEvent::PunchIn, location->start());
1620 //when_to_stop += _worst_output_latency + _worst_input_latency;
1621 replace_event (SessionEvent::PunchOut, when_to_stop);
1624 /** @param loc A loop location.
1625 * @param pos Filled in with the start time of the required fade-out (in session frames).
1626 * @param length Filled in with the length of the required fade-out.
1629 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1631 pos = max (loc->start(), loc->end() - 64);
1632 length = loc->end() - pos;
1636 Session::auto_loop_changed (Location* location)
1638 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1641 auto_loop_declick_range (location, dcp, dcl);
1643 if (transport_rolling() && play_loop) {
1645 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1647 // if (_transport_frame > location->end()) {
1649 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1650 // relocate to beginning of loop
1651 clear_events (SessionEvent::LocateRoll);
1653 request_locate (location->start(), true);
1656 else if (Config->get_seamless_loop() && !loop_changing) {
1658 // schedule a locate-roll to refill the diskstreams at the
1659 // previous loop end
1660 loop_changing = true;
1662 if (location->end() > last_loopend) {
1663 clear_events (SessionEvent::LocateRoll);
1664 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1670 clear_events (SessionEvent::AutoLoopDeclick);
1671 clear_events (SessionEvent::AutoLoop);
1674 /* possibly move playhead if not rolling; if we are rolling we'll move
1675 to the loop start on stop if that is appropriate.
1680 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1681 if (pos == location->start()) {
1682 request_locate (pos);
1687 last_loopend = location->end();
1692 Session::set_auto_punch_location (Location* location)
1696 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1697 punch_connections.drop_connections();
1698 existing->set_auto_punch (false, this);
1699 remove_event (existing->start(), SessionEvent::PunchIn);
1700 clear_events (SessionEvent::PunchOut);
1701 auto_punch_location_changed (0);
1706 if (location == 0) {
1710 if (location->end() <= location->start()) {
1711 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1715 punch_connections.drop_connections ();
1717 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1718 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1719 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1721 location->set_auto_punch (true, this);
1723 auto_punch_changed (location);
1725 auto_punch_location_changed (location);
1729 Session::set_session_extents (framepos_t start, framepos_t end)
1732 if ((existing = _locations->session_range_location()) == 0) {
1733 //if there is no existing session, we need to make a new session location (should never happen)
1734 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1738 error << _("Session: you can't use that location for session start/end)") << endmsg;
1742 existing->set( start, end );
1748 Session::set_auto_loop_location (Location* location)
1752 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1753 loop_connections.drop_connections ();
1754 existing->set_auto_loop (false, this);
1755 remove_event (existing->end(), SessionEvent::AutoLoop);
1758 auto_loop_declick_range (existing, dcp, dcl);
1759 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1760 auto_loop_location_changed (0);
1765 if (location == 0) {
1769 if (location->end() <= location->start()) {
1770 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1774 last_loopend = location->end();
1776 loop_connections.drop_connections ();
1778 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1779 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1780 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1781 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1783 location->set_auto_loop (true, this);
1785 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1786 // set all tracks to use internal looping
1787 boost::shared_ptr<RouteList> rl = routes.reader ();
1788 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1789 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1790 if (tr && !tr->hidden()) {
1791 tr->set_loop (location);
1796 /* take care of our stuff first */
1798 auto_loop_changed (location);
1800 /* now tell everyone else */
1802 auto_loop_location_changed (location);
1806 Session::update_marks (Location*)
1812 Session::update_skips (Location* loc, bool consolidate)
1814 if (_ignore_skips_updates) {
1818 Locations::LocationList skips;
1821 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1822 consolidate_skips (loc);
1825 sync_locations_to_skips ();
1831 Session::consolidate_skips (Location* loc)
1833 Locations::LocationList all_locations = _locations->list ();
1835 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1837 if (!(*l)->is_skip ()) {
1842 /* don't test against self */
1849 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1850 case Evoral::OverlapInternal:
1851 case Evoral::OverlapExternal:
1852 case Evoral::OverlapStart:
1853 case Evoral::OverlapEnd:
1854 /* adjust new location to cover existing one */
1855 loc->set_start (min (loc->start(), (*l)->start()));
1856 loc->set_end (max (loc->end(), (*l)->end()));
1857 /* we don't need this one any more */
1858 _locations->remove (*l);
1859 /* the location has been deleted, so remove reference to it in our local list */
1860 l = all_locations.erase (l);
1863 case Evoral::OverlapNone:
1871 Session::sync_locations_to_skips ()
1873 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1874 * Session::_sync_locations_to_skips() from the audioengine thread.
1876 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1880 Session::_sync_locations_to_skips ()
1882 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1884 Locations::LocationList const & locs (_locations->list());
1886 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1888 Location* location = *i;
1890 if (location->is_skip() && location->is_skipping()) {
1891 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1899 Session::location_added (Location *location)
1901 if (location->is_auto_punch()) {
1902 set_auto_punch_location (location);
1905 if (location->is_auto_loop()) {
1906 set_auto_loop_location (location);
1909 if (location->is_session_range()) {
1910 /* no need for any signal handling or event setting with the session range,
1911 because we keep a direct reference to it and use its start/end directly.
1913 _session_range_location = location;
1916 if (location->is_mark()) {
1917 /* listen for per-location signals that require us to do any * global updates for marks */
1919 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1920 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1921 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1922 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1923 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1926 if (location->is_range_marker()) {
1927 /* listen for per-location signals that require us to do any * global updates for marks */
1929 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1930 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1931 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1932 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1933 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1936 if (location->is_skip()) {
1937 /* listen for per-location signals that require us to update skip-locate events */
1939 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1940 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1941 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1942 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1943 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1945 update_skips (location, true);
1952 Session::location_removed (Location *location)
1954 if (location->is_auto_loop()) {
1955 set_auto_loop_location (0);
1956 set_track_loop (false);
1959 if (location->is_auto_punch()) {
1960 set_auto_punch_location (0);
1963 if (location->is_session_range()) {
1964 /* this is never supposed to happen */
1965 error << _("programming error: session range removed!") << endl;
1968 if (location->is_skip()) {
1970 update_skips (location, false);
1977 Session::locations_changed ()
1979 _locations->apply (*this, &Session::_locations_changed);
1983 Session::_locations_changed (const Locations::LocationList& locations)
1985 /* There was some mass-change in the Locations object.
1987 We might be re-adding a location here but it doesn't actually matter
1988 for all the locations that the Session takes an interest in.
1992 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1993 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1994 location_added (*i);
1998 update_skips (NULL, false);
2002 Session::enable_record ()
2004 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2005 /* no recording at anything except normal speed */
2010 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2012 if (rs == Recording) {
2016 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2018 _last_record_location = _transport_frame;
2019 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2021 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2022 set_track_monitor_input_status (true);
2025 RecordStateChanged ();
2032 Session::set_all_tracks_record_enabled (bool enable )
2034 boost::shared_ptr<RouteList> rl = routes.reader();
2035 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2039 Session::disable_record (bool rt_context, bool force)
2043 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2045 if (!Config->get_latched_record_enable () || force) {
2046 g_atomic_int_set (&_record_status, Disabled);
2047 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2049 if (rs == Recording) {
2050 g_atomic_int_set (&_record_status, Enabled);
2054 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2055 set_track_monitor_input_status (false);
2058 RecordStateChanged (); /* emit signal */
2061 remove_pending_capture_state ();
2063 unset_preroll_record_punch ();
2068 Session::step_back_from_record ()
2070 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2072 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2073 set_track_monitor_input_status (false);
2076 RecordStateChanged (); /* emit signal */
2081 Session::maybe_enable_record (bool rt_context)
2083 if (_step_editors > 0) {
2087 g_atomic_int_set (&_record_status, Enabled);
2089 /* This function is currently called from somewhere other than an RT thread.
2090 * (except maybe lua scripts, which can use rt_context = true)
2091 * This save_state() call therefore doesn't impact anything. Doing it here
2092 * means that we save pending state of which sources the next record will use,
2093 * which gives us some chance of recovering from a crash during the record.
2097 save_state ("", true);
2100 if (_transport_speed) {
2101 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2105 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2106 RecordStateChanged (); /* EMIT SIGNAL */
2113 Session::audible_frame (bool* latent_locate) const
2117 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2118 offset *= transport_speed ();
2119 if (latent_locate) {
2120 *latent_locate = false;
2123 if (synced_to_engine()) {
2124 /* Note: this is basically just sync-to-JACK */
2125 ret = _engine.transport_frame();
2127 ret = _transport_frame;
2130 if (transport_rolling()) {
2133 /* Check to see if we have passed the first guaranteed
2134 * audible frame past our last start position. if not,
2135 * return that last start point because in terms
2136 * of audible frames, we have not moved yet.
2138 * `Start position' in this context means the time we last
2139 * either started, located, or changed transport direction.
2142 if (_transport_speed > 0.0f) {
2144 if (!play_loop || !have_looped) {
2145 if (ret < _last_roll_or_reversal_location) {
2146 if (latent_locate) {
2147 *latent_locate = true;
2149 return _last_roll_or_reversal_location;
2152 /* the play-position wrapped at the loop-point
2153 * ardour is already playing the beginning of the loop,
2154 * but due to playback latency, the "audible frame"
2155 * is still at the end of the loop.
2157 Location *location = _locations->auto_loop_location();
2158 frameoffset_t lo = location->start() - ret;
2160 ret = location->end () - lo;
2161 if (latent_locate) {
2162 *latent_locate = true;
2167 } else if (_transport_speed < 0.0f) {
2169 /* XXX wot? no backward looping? */
2171 if (ret > _last_roll_or_reversal_location) {
2172 return _last_roll_or_reversal_location;
2177 return std::max ((framepos_t)0, ret);
2182 Session::preroll_samples (framepos_t pos) const
2184 const float pr = Config->get_preroll_seconds();
2185 if (pos >= 0 && pr < 0) {
2186 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2187 const Meter& meter = _tempo_map->meter_at_frame (pos);
2188 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2193 return pr * frame_rate();
2197 Session::set_frame_rate (framecnt_t frames_per_second)
2199 /** \fn void Session::set_frame_size(framecnt_t)
2200 the AudioEngine object that calls this guarantees
2201 that it will not be called while we are also in
2202 ::process(). Its fine to do things that block
2206 if (_base_frame_rate == 0) {
2207 _base_frame_rate = frames_per_second;
2209 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2210 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2212 _nominal_frame_rate = frames_per_second;
2217 reset_write_sources (false);
2219 // XXX we need some equivalent to this, somehow
2220 // SndFileSource::setup_standard_crossfades (frames_per_second);
2224 /* XXX need to reset/reinstantiate all LADSPA plugins */
2228 Session::set_block_size (pframes_t nframes)
2230 /* the AudioEngine guarantees
2231 that it will not be called while we are also in
2232 ::process(). It is therefore fine to do things that block
2237 current_block_size = nframes;
2241 boost::shared_ptr<RouteList> r = routes.reader ();
2243 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2244 (*i)->set_block_size (nframes);
2247 boost::shared_ptr<RouteList> rl = routes.reader ();
2248 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2249 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2251 tr->set_block_size (nframes);
2255 set_worst_io_latencies ();
2261 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2263 boost::shared_ptr<Route> r2;
2265 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2266 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2270 /* make a copy of the existing list of routes that feed r1 */
2272 Route::FedBy existing (r1->fed_by());
2274 /* for each route that feeds r1, recurse, marking it as feeding
2278 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2279 if (!(r2 = i->r.lock ())) {
2280 /* (*i) went away, ignore it */
2284 /* r2 is a route that feeds r1 which somehow feeds base. mark
2285 base as being fed by r2
2288 rbase->add_fed_by (r2, i->sends_only);
2292 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2296 if (r1->feeds (r2) && r2->feeds (r1)) {
2300 /* now recurse, so that we can mark base as being fed by
2301 all routes that feed r2
2304 trace_terminal (r2, rbase);
2311 Session::resort_routes ()
2313 /* don't do anything here with signals emitted
2314 by Routes during initial setup or while we
2315 are being destroyed.
2318 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2322 if (_route_deletion_in_progress) {
2327 RCUWriter<RouteList> writer (routes);
2328 boost::shared_ptr<RouteList> r = writer.get_copy ();
2329 resort_routes_using (r);
2330 /* writer goes out of scope and forces update */
2334 if (DEBUG_ENABLED(DEBUG::Graph)) {
2335 boost::shared_ptr<RouteList> rl = routes.reader ();
2336 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2337 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2339 const Route::FedBy& fb ((*i)->fed_by());
2341 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2342 boost::shared_ptr<Route> sf = f->r.lock();
2344 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2353 /** This is called whenever we need to rebuild the graph of how we will process
2355 * @param r List of routes, in any order.
2359 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2361 /* We are going to build a directed graph of our routes;
2362 this is where the edges of that graph are put.
2367 /* Go through all routes doing two things:
2369 * 1. Collect the edges of the route graph. Each of these edges
2370 * is a pair of routes, one of which directly feeds the other
2371 * either by a JACK connection or by an internal send.
2373 * 2. Begin the process of making routes aware of which other
2374 * routes directly or indirectly feed them. This information
2375 * is used by the solo code.
2378 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2380 /* Clear out the route's list of direct or indirect feeds */
2381 (*i)->clear_fed_by ();
2383 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2385 bool via_sends_only;
2387 /* See if this *j feeds *i according to the current state of the JACK
2388 connections and internal sends.
2390 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2391 /* add the edge to the graph (part #1) */
2392 edges.add (*j, *i, via_sends_only);
2393 /* tell the route (for part #2) */
2394 (*i)->add_fed_by (*j, via_sends_only);
2399 /* Attempt a topological sort of the route graph */
2400 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2402 if (sorted_routes) {
2403 /* We got a satisfactory topological sort, so there is no feedback;
2406 Note: the process graph rechain does not require a
2407 topologically-sorted list, but hey ho.
2409 if (_process_graph) {
2410 _process_graph->rechain (sorted_routes, edges);
2413 _current_route_graph = edges;
2415 /* Complete the building of the routes' lists of what directly
2416 or indirectly feeds them.
2418 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2419 trace_terminal (*i, *i);
2422 *r = *sorted_routes;
2425 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2426 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2427 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2431 SuccessfulGraphSort (); /* EMIT SIGNAL */
2434 /* The topological sort failed, so we have a problem. Tell everyone
2435 and stick to the old graph; this will continue to be processed, so
2436 until the feedback is fixed, what is played back will not quite
2437 reflect what is actually connected. Note also that we do not
2438 do trace_terminal here, as it would fail due to an endless recursion,
2439 so the solo code will think that everything is still connected
2443 FeedbackDetected (); /* EMIT SIGNAL */
2448 /** Find a route name starting with \a base, maybe followed by the
2449 * lowest \a id. \a id will always be added if \a definitely_add_number
2450 * is true on entry; otherwise it will only be added if required
2451 * to make the name unique.
2453 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2454 * The available route name with the lowest ID will be used, and \a id
2455 * will be set to the ID.
2457 * \return false if a route name could not be found, and \a track_name
2458 * and \a id do not reflect a free route name.
2461 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2463 /* the base may conflict with ports that do not belong to existing
2464 routes, but hidden objects like the click track. So check port names
2465 before anything else.
2468 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2469 if (base == reserved->first) {
2470 /* Check if this reserved name already exists, and if
2471 so, disallow it without a numeric suffix.
2473 if (!reserved->second || route_by_name (reserved->first)) {
2474 definitely_add_number = true;
2483 /* if we have "base 1" already, it doesn't make sense to add "base"
2484 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2486 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2487 /* just use the base */
2493 name = string_compose ("%1 %2", base, id);
2495 if (route_by_name (name) == 0) {
2501 } while (id < (UINT_MAX-1));
2506 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2508 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2510 in = ChanCount::ZERO;
2511 out = ChanCount::ZERO;
2513 boost::shared_ptr<RouteList> r = routes.reader ();
2515 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2516 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2517 if (tr && !tr->is_auditioner()) {
2518 in += tr->n_inputs();
2519 out += tr->n_outputs();
2525 Session::default_track_name_pattern (DataType t)
2528 case DataType::AUDIO:
2529 if (Profile->get_trx()) {
2536 case DataType::MIDI:
2543 /** Caller must not hold process lock
2544 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2545 * @param instrument plugin info for the instrument to insert pre-fader, if any
2547 list<boost::shared_ptr<MidiTrack> >
2548 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2549 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2550 RouteGroup* route_group, uint32_t how_many,
2551 string name_template, PresentationInfo::order_t order,
2555 uint32_t track_id = 0;
2557 RouteList new_routes;
2558 list<boost::shared_ptr<MidiTrack> > ret;
2560 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2561 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2564 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2565 error << "cannot find name for new midi track" << endmsg;
2569 boost::shared_ptr<MidiTrack> track;
2572 track.reset (new MidiTrack (*this, track_name, mode));
2574 if (track->init ()) {
2579 track->set_strict_io (true);
2582 track->use_new_diskstream();
2584 BOOST_MARK_TRACK (track);
2587 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2588 if (track->input()->ensure_io (input, false, this)) {
2589 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2593 if (track->output()->ensure_io (output, false, this)) {
2594 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2599 track->non_realtime_input_change();
2602 route_group->add (track);
2605 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2607 new_routes.push_back (track);
2608 ret.push_back (track);
2611 catch (failed_constructor &err) {
2612 error << _("Session: could not create new midi track.") << endmsg;
2616 catch (AudioEngine::PortRegistrationFailure& pfe) {
2618 error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
2626 if (!new_routes.empty()) {
2627 StateProtector sp (this);
2628 if (Profile->get_trx()) {
2629 add_routes (new_routes, false, false, false, order);
2631 add_routes (new_routes, true, true, false, order);
2635 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2636 PluginPtr plugin = instrument->load (*this);
2638 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2642 plugin->load_preset (*pset);
2644 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2646 pi->set_strict_io (true);
2649 (*r)->add_processor (pi, PreFader);
2651 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2652 (*r)->move_instrument_down (false);
2662 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2663 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2664 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2667 uint32_t bus_id = 0;
2671 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2674 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2675 error << "cannot find name for new midi bus" << endmsg;
2680 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2687 bus->set_strict_io (true);
2690 BOOST_MARK_ROUTE(bus);
2693 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2695 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2696 error << _("cannot configure new midi bus input") << endmsg;
2701 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2702 error << _("cannot configure new midi bus output") << endmsg;
2708 route_group->add (bus);
2711 bus->add_internal_return ();
2712 ret.push_back (bus);
2715 catch (failed_constructor &err) {
2716 error << _("Session: could not create new audio route.") << endmsg;
2720 catch (AudioEngine::PortRegistrationFailure& pfe) {
2721 error << pfe.what() << endmsg;
2731 StateProtector sp (this);
2732 add_routes (ret, false, false, false, order);
2735 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2736 PluginPtr plugin = instrument->load (*this);
2738 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2742 plugin->load_preset (*pset);
2744 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2746 pi->set_strict_io (true);
2749 (*r)->add_processor (pi, PreFader);
2751 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2752 (*r)->move_instrument_down (false);
2764 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2766 boost::shared_ptr<Route> midi_track (wmt.lock());
2772 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2774 if (change.after.n_audio() <= change.before.n_audio()) {
2778 /* new audio ports: make sure the audio goes somewhere useful,
2779 * unless the user has no-auto-connect selected.
2781 * The existing ChanCounts don't matter for this call as they are only
2782 * to do with matching input and output indices, and we are only changing
2785 auto_connect_route (midi_track, false, ChanCount(), change.before);
2789 #ifdef USE_TRACKS_CODE_FEATURES
2792 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2794 return route1->remote_control_id() < route2->remote_control_id();
2798 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2800 // it is not allowed to perform connection
2801 if (!IO::connecting_legal) {
2805 // if we are deleting routes we will call this once at the end
2806 if (_route_deletion_in_progress) {
2810 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2816 // We need to disconnect the route's inputs and outputs first
2817 // basing on autoconnect configuration
2818 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2819 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2821 ChanCount existing_inputs;
2822 ChanCount existing_outputs;
2823 count_existing_track_channels (existing_inputs, existing_outputs);
2825 //ChanCount inputs = ChanCount::ZERO;
2826 //ChanCount outputs = ChanCount::ZERO;
2828 RouteList existing_routes = *routes.reader ();
2829 existing_routes.sort (compare_routes_by_remote_id);
2832 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2834 vector<string> physinputs;
2835 vector<string> physoutputs;
2837 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2838 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2840 uint32_t input_n = 0;
2841 uint32_t output_n = 0;
2842 RouteList::iterator rIter = existing_routes.begin();
2843 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2844 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2845 for (; rIter != existing_routes.end(); ++rIter) {
2846 if (*rIter == _master_out || *rIter == _monitor_out ) {
2850 if (current_output_auto_connection == AutoConnectPhysical) {
2851 (*rIter)->amp()->deactivate();
2852 } else if (current_output_auto_connection == AutoConnectMaster) {
2853 (*rIter)->amp()->activate();
2856 if (reconnectIputs) {
2857 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2859 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2861 if (current_input_auto_connection & AutoConnectPhysical) {
2863 if ( input_n == physinputs.size() ) {
2867 string port = physinputs[input_n];
2869 if (port.empty() ) {
2870 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2873 //GZ: check this; could be heavy
2874 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2880 if (reconnectOutputs) {
2882 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2883 if (current_output_auto_connection & AutoConnectPhysical) {
2885 //GZ: check this; could be heavy
2886 (*rIter)->output()->disconnect (this);
2887 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2889 //GZ: check this; could be heavy
2890 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2892 } else if (current_output_auto_connection & AutoConnectMaster){
2894 if (!reconnect_master) {
2898 //GZ: check this; could be heavy
2899 (*rIter)->output()->disconnect (this);
2902 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2903 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2905 error << error << "Master bus is not available" << endmsg;
2910 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2911 if (current_output_auto_connection & AutoConnectPhysical) {
2913 if ( output_n == physoutputs.size() ) {
2917 string port = physoutputs[output_n];
2919 if (port.empty() ) {
2920 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2923 //GZ: check this; could be heavy
2924 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2927 } else if (current_output_auto_connection & AutoConnectMaster) {
2929 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2933 // connect to master bus
2934 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2936 if (port.empty() ) {
2937 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2941 //GZ: check this; could be heavy
2942 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2949 _master_out->output()->disconnect (this);
2950 auto_connect_master_bus ();
2955 session_routes_reconnected (); /* EMIT SIGNAL */
2959 Session::reconnect_midi_scene_ports(bool inputs)
2963 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2965 scene_in_ptr->disconnect_all ();
2967 std::vector<EngineStateController::MidiPortState> midi_port_states;
2968 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2970 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2972 for (; state_iter != midi_port_states.end(); ++state_iter) {
2973 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2974 scene_in_ptr->connect (state_iter->name);
2981 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2983 if (scene_out_ptr ) {
2984 scene_out_ptr->disconnect_all ();
2986 std::vector<EngineStateController::MidiPortState> midi_port_states;
2987 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2989 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2991 for (; state_iter != midi_port_states.end(); ++state_iter) {
2992 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2993 scene_out_ptr->connect (state_iter->name);
3001 Session::reconnect_mtc_ports ()
3003 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
3009 mtc_in_ptr->disconnect_all ();
3011 std::vector<EngineStateController::MidiPortState> midi_port_states;
3012 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
3014 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
3016 for (; state_iter != midi_port_states.end(); ++state_iter) {
3017 if (state_iter->available && state_iter->mtc_in) {
3018 mtc_in_ptr->connect (state_iter->name);
3022 if (!_midi_ports->mtc_input_port ()->connected () &&
3023 config.get_external_sync () &&
3024 (Config->get_sync_source () == MTC) ) {
3025 config.set_external_sync (false);
3028 if ( ARDOUR::Profile->get_trx () ) {
3029 // Tracks need this signal to update timecode_source_dropdown
3030 MtcOrLtcInputPortChanged (); //emit signal
3035 Session::reconnect_mmc_ports(bool inputs)
3037 if (inputs ) { // get all enabled midi input ports
3039 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
3041 mmc_in_ptr->disconnect_all ();
3042 std::vector<std::string> enabled_midi_inputs;
3043 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3045 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3047 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3048 mmc_in_ptr->connect (*port_iter);
3052 } else { // get all enabled midi output ports
3054 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3056 mmc_out_ptr->disconnect_all ();
3057 std::vector<std::string> enabled_midi_outputs;
3058 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3060 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3062 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3063 mmc_out_ptr->connect (*port_iter);
3072 Session::ensure_stripable_sort_order ()
3075 get_stripables (sl);
3076 sl.sort (Stripable::Sorter ());
3078 bool change = false;
3079 PresentationInfo::order_t order = 0;
3081 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3082 boost::shared_ptr<Stripable> s (*si);
3083 if (s->is_monitor () || s->is_auditioner ()) {
3086 if (order != s->presentation_info().order()) {
3087 s->set_presentation_order (order);
3096 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3098 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3100 if (first_new_order == PresentationInfo::max_order) {
3101 /* adding at end, no worries */
3105 /* create a gap in the presentation info to accomodate @param how_many
3109 get_stripables (sl);
3111 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3112 boost::shared_ptr<Stripable> s (*si);
3114 if (s->presentation_info().special (false)) {
3118 if (!s->presentation_info().order_set()) {
3122 if (s->presentation_info().order () >= first_new_order) {
3123 s->set_presentation_order (s->presentation_info().order () + how_many);
3128 /** Caller must not hold process lock
3129 * @param name_template string to use for the start of the name, or "" to use "Audio".
3131 list< boost::shared_ptr<AudioTrack> >
3132 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3133 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3137 uint32_t track_id = 0;
3139 RouteList new_routes;
3140 list<boost::shared_ptr<AudioTrack> > ret;
3142 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3143 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3147 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3148 error << "cannot find name for new audio track" << endmsg;
3152 boost::shared_ptr<AudioTrack> track;
3155 track.reset (new AudioTrack (*this, track_name, mode));
3157 if (track->init ()) {
3161 if (Profile->get_mixbus ()) {
3162 track->set_strict_io (true);
3165 if (ARDOUR::Profile->get_trx ()) {
3166 // TRACKS considers it's not a USE CASE, it's
3167 // a piece of behavior of the session model:
3169 // Gain for a newly created route depends on
3170 // the current output_auto_connect mode:
3172 // 0 for Stereo Out mode
3174 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3175 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3179 track->use_new_diskstream();
3181 BOOST_MARK_TRACK (track);
3184 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3186 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3187 error << string_compose (
3188 _("cannot configure %1 in/%2 out configuration for new audio track"),
3189 input_channels, output_channels)
3194 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3195 error << string_compose (
3196 _("cannot configure %1 in/%2 out configuration for new audio track"),
3197 input_channels, output_channels)
3204 route_group->add (track);
3207 track->non_realtime_input_change();
3209 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3211 new_routes.push_back (track);
3212 ret.push_back (track);
3215 catch (failed_constructor &err) {
3216 error << _("Session: could not create new audio track.") << endmsg;
3220 catch (AudioEngine::PortRegistrationFailure& pfe) {
3222 error << pfe.what() << endmsg;
3230 if (!new_routes.empty()) {
3231 StateProtector sp (this);
3232 if (Profile->get_trx()) {
3233 add_routes (new_routes, false, false, false, order);
3235 add_routes (new_routes, true, true, false, order);
3242 /** Caller must not hold process lock.
3243 * @param name_template string to use for the start of the name, or "" to use "Bus".
3246 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3247 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3250 uint32_t bus_id = 0;
3254 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3257 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3258 error << "cannot find name for new audio bus" << endmsg;
3263 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3269 if (Profile->get_mixbus ()) {
3270 bus->set_strict_io (true);
3273 BOOST_MARK_ROUTE(bus);
3276 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3278 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3279 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3280 input_channels, output_channels)
3286 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3287 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3288 input_channels, output_channels)
3295 route_group->add (bus);
3298 bus->add_internal_return ();
3299 ret.push_back (bus);
3302 catch (failed_constructor &err) {
3303 error << _("Session: could not create new audio route.") << endmsg;
3307 catch (AudioEngine::PortRegistrationFailure& pfe) {
3308 error << pfe.what() << endmsg;
3318 StateProtector sp (this);
3319 if (Profile->get_trx()) {
3320 add_routes (ret, false, false, false, order);
3322 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3331 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3332 PlaylistDisposition pd)
3336 if (!tree.read (template_path.c_str())) {
3340 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3344 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3347 uint32_t number = 0;
3348 const uint32_t being_added = how_many;
3349 /* This will prevent the use of any existing XML-provided PBD::ID
3352 Stateful::ForceIDRegeneration force_ids;
3353 IO::disable_connecting ();
3357 /* We're going to modify the node contents a bit so take a
3358 * copy. The node may be re-used when duplicating more than once.
3361 XMLNode node_copy (node);
3366 if (!name_base.empty()) {
3368 /* if we're adding more than one routes, force
3369 * all the names of the new routes to be
3370 * numbered, via the final parameter.
3373 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3374 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3380 string const route_name = node_copy.property(X_("name"))->value ();
3382 /* generate a new name by adding a number to the end of the template name */
3383 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3384 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3385 abort(); /*NOTREACHED*/
3389 /* set this name in the XML description that we are about to use */
3391 if (pd == CopyPlaylist) {
3392 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3394 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3395 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3396 // Use same name as Route::set_name_in_state so playlist copy
3397 // is picked up when creating the Route in XMLRouteFactory below
3398 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3399 playlist->reset_shares ();
3401 } else if (pd == SharePlaylist) {
3402 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3404 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3405 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3406 playlist->share_with ((node_copy.property (X_("id")))->value());
3410 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3412 Route::set_name_in_state (node_copy, name, rename_playlist);
3414 /* trim bitslots from listen sends so that new ones are used */
3415 XMLNodeList children = node_copy.children ();
3416 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3417 if ((*i)->name() == X_("Processor")) {
3418 /* ForceIDRegeneration does not catch the following */
3419 XMLProperty const * role = (*i)->property (X_("role"));
3420 XMLProperty const * type = (*i)->property (X_("type"));
3421 if (role && role->value() == X_("Aux")) {
3422 /* check if the target bus exists.
3423 * we should not save aux-sends in templates.
3425 XMLProperty const * target = (*i)->property (X_("target"));
3427 (*i)->set_property ("type", "dangling-aux-send");
3430 boost::shared_ptr<Route> r = route_by_id (target->value());
3431 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3432 (*i)->set_property ("type", "dangling-aux-send");
3436 if (role && role->value() == X_("Listen")) {
3437 (*i)->remove_property (X_("bitslot"));
3439 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3440 Delivery::Role xrole;
3441 uint32_t bitslot = 0;
3442 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3443 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3444 (*i)->remove_property (X_("bitslot"));
3445 (*i)->remove_property (X_("name"));
3446 (*i)->set_property ("bitslot", bitslot);
3447 (*i)->set_property ("name", name);
3449 else if (type && type->value() == X_("intreturn")) {
3450 (*i)->remove_property (X_("bitslot"));
3451 (*i)->set_property ("ignore-bitslot", "1");
3453 else if (type && type->value() == X_("return")) {
3454 // Return::set_state() generates a new one
3455 (*i)->remove_property (X_("bitslot"));
3457 else if (type && type->value() == X_("port")) {
3458 // PortInsert::set_state() handles the bitslot
3459 (*i)->remove_property (X_("bitslot"));
3460 (*i)->set_property ("ignore-name", "1");
3465 /* new routes start off unsoloed to avoid issues related to
3466 upstream / downstream buses. */
3467 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3469 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3472 error << _("Session: cannot create track/bus from template description") << endmsg;
3476 if (boost::dynamic_pointer_cast<Track>(route)) {
3477 /* force input/output change signals so that the new diskstream
3478 picks up the configuration of the route. During session
3479 loading this normally happens in a different way.
3482 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3484 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3485 change.after = route->input()->n_ports();
3486 route->input()->changed (change, this);
3487 change.after = route->output()->n_ports();
3488 route->output()->changed (change, this);
3491 ret.push_back (route);
3494 catch (failed_constructor &err) {
3495 error << _("Session: could not create new route from template") << endmsg;
3499 catch (AudioEngine::PortRegistrationFailure& pfe) {
3500 error << pfe.what() << endmsg;
3509 StateProtector sp (this);
3510 if (Profile->get_trx()) {
3511 add_routes (ret, false, false, false, insert_at);
3513 add_routes (ret, true, true, false, insert_at);
3515 IO::enable_connecting ();
3522 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3525 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3526 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3529 error << _("Adding new tracks/busses failed") << endmsg;
3534 update_latency (true);
3535 update_latency (false);
3540 save_state (_current_snapshot_name);
3543 update_route_record_state ();
3545 RouteAdded (new_routes); /* EMIT SIGNAL */
3549 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3551 ChanCount existing_inputs;
3552 ChanCount existing_outputs;
3556 count_existing_track_channels (existing_inputs, existing_outputs);
3559 RCUWriter<RouteList> writer (routes);
3560 boost::shared_ptr<RouteList> r = writer.get_copy ();
3561 n_routes = r->size();
3562 r->insert (r->end(), new_routes.begin(), new_routes.end());
3564 /* if there is no control out and we're not in the middle of loading,
3565 * resort the graph here. if there is a control out, we will resort
3566 * toward the end of this method. if we are in the middle of loading,
3567 * we will resort when done.
3570 if (!_monitor_out && IO::connecting_legal) {
3571 resort_routes_using (r);
3575 /* auditioner and monitor routes are not part of the order */
3577 assert (n_routes > 0);
3581 assert (n_routes > 0);
3586 PresentationInfo::ChangeSuspender cs;
3587 ensure_route_presentation_info_gap (order, new_routes.size());
3589 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3591 boost::weak_ptr<Route> wpr (*x);
3592 boost::shared_ptr<Route> r (*x);
3594 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3595 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3596 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3598 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3599 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3600 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3602 if (r->is_master()) {
3606 if (r->is_monitor()) {
3610 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3612 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3613 track_playlist_changed (boost::weak_ptr<Track> (tr));
3614 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3616 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3618 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3619 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3620 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3624 if (!r->presentation_info().special (false)) {
3626 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3628 /* presentation info order may already have been set from XML */
3630 if (!r->presentation_info().order_set()) {
3631 if (order == PresentationInfo::max_order) {
3632 /* just add to the end */
3633 r->set_presentation_order (n_routes + added);
3634 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3636 r->set_presentation_order (order + added);
3637 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3640 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3644 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3645 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3646 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3648 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3650 r->presentation_info().order(),
3651 enum_2_string (r->presentation_info().flags()),
3652 r->presentation_info()));
3656 if (input_auto_connect || output_auto_connect) {
3657 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3658 existing_inputs += r->n_inputs();
3659 existing_outputs += r->n_outputs();
3664 ensure_stripable_sort_order ();
3667 if (_monitor_out && IO::connecting_legal) {
3668 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3670 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3671 if ((*x)->is_monitor()) {
3673 } else if ((*x)->is_master()) {
3676 (*x)->enable_monitor_send ();
3681 reassign_track_numbers ();
3685 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3687 boost::shared_ptr<RouteList> r = routes.reader ();
3688 boost::shared_ptr<Send> s;
3690 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3691 if ((s = (*i)->internal_send_for (dest)) != 0) {
3692 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3698 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3700 boost::shared_ptr<RouteList> r = routes.reader ();
3701 boost::shared_ptr<Send> s;
3703 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3704 if ((s = (*i)->internal_send_for (dest)) != 0) {
3705 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3711 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3713 boost::shared_ptr<RouteList> r = routes.reader ();
3714 boost::shared_ptr<Send> s;
3716 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3717 if ((s = (*i)->internal_send_for (dest)) != 0) {
3718 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3723 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3725 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3727 boost::shared_ptr<RouteList> r = routes.reader ();
3728 boost::shared_ptr<RouteList> t (new RouteList);
3730 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3731 /* no MIDI sends because there are no MIDI busses yet */
3732 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3737 add_internal_sends (dest, p, t);
3741 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3743 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3744 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3749 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3751 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3755 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3757 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3761 if (!dest->internal_return()) {
3762 dest->add_internal_return ();
3765 sender->add_aux_send (dest, before);
3771 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3773 bool mute_changed = false;
3774 bool send_selected = false;
3776 { // RCU Writer scope
3777 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3778 RCUWriter<RouteList> writer (routes);
3779 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3781 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3783 if (_selection->selected (*iter)) {
3784 send_selected = true;
3787 if (*iter == _master_out) {
3791 /* speed up session deletion, don't do the solo dance */
3792 if (0 == (_state_of_the_state & Deletion)) {
3793 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3796 if ((*iter)->mute_control()->muted ()) {
3797 mute_changed = true;
3802 /* deleting the master out seems like a dumb
3803 idea, but its more of a UI policy issue
3807 if (*iter == _master_out) {
3808 _master_out = boost::shared_ptr<Route> ();
3811 if (*iter == _monitor_out) {
3812 _monitor_out.reset ();
3815 // We need to disconnect the route's inputs and outputs
3817 (*iter)->input()->disconnect (0);
3818 (*iter)->output()->disconnect (0);
3820 /* if the route had internal sends sending to it, remove them */
3821 if ((*iter)->internal_return()) {
3823 boost::shared_ptr<RouteList> r = routes.reader ();
3824 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3825 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3827 (*i)->remove_processor (s);
3832 /* if the monitoring section had a pointer to this route, remove it */
3833 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3834 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3835 ProcessorChangeBlocker pcb (this, false);
3836 (*iter)->remove_aux_or_listen (_monitor_out);
3839 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3840 if (mt && mt->step_editing()) {
3841 if (_step_editors > 0) {
3847 /* writer goes out of scope, forces route list update */
3849 } // end of RCU Writer scope
3852 MuteChanged (); /* EMIT SIGNAL */
3855 update_route_solo_state ();
3856 update_latency_compensation ();
3859 /* Re-sort routes to remove the graph's current references to the one that is
3860 * going away, then flush old references out of the graph.
3861 * Wave Tracks: reconnect routes
3864 #ifdef USE_TRACKS_CODE_FEATURES
3865 reconnect_existing_routes(true, false);
3867 routes.flush (); // maybe unsafe, see below.
3871 if (_process_graph && !(_state_of_the_state & Deletion)) {
3872 _process_graph->clear_other_chain ();
3875 /* get rid of it from the dead wood collection in the route list manager */
3876 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3880 /* remove these routes from the selection if appropriate, and signal
3881 * the change *before* we call DropReferences for them.
3884 if (send_selected && !deletion_in_progress()) {
3885 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3886 _selection->remove_stripable_by_id ((*iter)->id());
3889 pc.add (Properties::selected);
3890 PresentationInfo::Change (pc);
3893 /* try to cause everyone to drop their references
3894 * and unregister ports from the backend
3897 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3898 (*iter)->drop_references ();
3901 if (deletion_in_progress()) {
3906 pc.add (Properties::order);
3907 PresentationInfo::Change (pc);
3909 /* save the new state of the world */
3911 if (save_state (_current_snapshot_name)) {
3912 save_history (_current_snapshot_name);
3915 update_route_record_state ();
3919 Session::remove_route (boost::shared_ptr<Route> route)
3921 boost::shared_ptr<RouteList> rl (new RouteList);
3922 rl->push_back (route);
3927 Session::route_mute_changed ()
3929 MuteChanged (); /* EMIT SIGNAL */
3934 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3936 boost::shared_ptr<Route> route (wpr.lock());
3942 assert (Config->get_solo_control_is_listen_control());
3944 if (route->solo_control()->soloed_by_self_or_masters()) {
3946 if (Config->get_exclusive_solo()) {
3948 RouteGroup* rg = route->route_group ();
3949 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3951 boost::shared_ptr<RouteList> r = routes.reader ();
3953 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3954 if ((*i) == route) {
3955 /* already changed */
3959 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3960 /* route does not get solo propagated to it */
3964 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3965 /* this route is a part of the same solo group as the route
3966 * that was changed. Changing that route did change or will
3967 * change all group members appropriately, so we can ignore it
3972 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3978 } else if (_listen_cnt > 0) {
3985 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3987 boost::shared_ptr<Route> route (wpr.lock());
3993 bool send_changed = false;
3995 if (route->solo_isolate_control()->solo_isolated()) {
3996 if (_solo_isolated_cnt == 0) {
3997 send_changed = true;
3999 _solo_isolated_cnt++;
4000 } else if (_solo_isolated_cnt > 0) {
4001 _solo_isolated_cnt--;
4002 if (_solo_isolated_cnt == 0) {
4003 send_changed = true;
4008 IsolatedChanged (); /* EMIT SIGNAL */
4013 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
4015 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
4017 boost::shared_ptr<Route> route (wpr.lock());
4023 if (Config->get_solo_control_is_listen_control()) {
4024 route_listen_changed (group_override, wpr);
4028 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()));
4030 if (route->solo_control()->transitioned_into_solo() == 0) {
4031 /* route solo changed by upstream/downstream or clear all solo state; not interesting
4034 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()));
4038 boost::shared_ptr<RouteList> r = routes.reader ();
4039 int32_t delta = route->solo_control()->transitioned_into_solo ();
4041 /* the route may be a member of a group that has shared-solo
4042 * semantics. If so, then all members of that group should follow the
4043 * solo of the changed route. But ... this is optional, controlled by a
4044 * Controllable::GroupControlDisposition.
4046 * The first argument to the signal that this method is connected to is the
4047 * GroupControlDisposition value that was used to change solo.
4049 * If the solo change was done with group semantics (either InverseGroup
4050 * (force the entire group to change even if the group shared solo is
4051 * disabled) or UseGroup (use the group, which may or may not have the
4052 * shared solo property enabled)) then as we propagate the change to
4053 * the entire session we should IGNORE THE GROUP that the changed route
4057 RouteGroup* rg = route->route_group ();
4058 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4060 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4062 if (delta == 1 && Config->get_exclusive_solo()) {
4064 /* new solo: disable all other solos, but not the group if its solo-enabled */
4066 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4068 if ((*i) == route) {
4069 /* already changed */
4073 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4074 /* route does not get solo propagated to it */
4078 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4079 /* this route is a part of the same solo group as the route
4080 * that was changed. Changing that route did change or will
4081 * change all group members appropriately, so we can ignore it
4087 (*i)->solo_control()->set_value (0.0, group_override);
4091 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4093 RouteList uninvolved;
4095 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4097 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4098 bool via_sends_only;
4099 bool in_signal_flow;
4101 if ((*i) == route) {
4102 /* already changed */
4106 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4107 /* route does not get solo propagated to it */
4108 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(),
4113 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4114 /* this route is a part of the same solo group as the route
4115 * that was changed. Changing that route did change or will
4116 * change all group members appropriately, so we can ignore it
4122 in_signal_flow = false;
4124 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4126 if ((*i)->feeds (route, &via_sends_only)) {
4127 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4128 if (!via_sends_only) {
4129 if (!route->soloed_by_others_upstream()) {
4130 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4132 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4135 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4137 in_signal_flow = true;
4139 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4142 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4144 if (route->feeds (*i, &via_sends_only)) {
4145 /* propagate solo upstream only if routing other than
4146 sends is involved, but do consider the other route
4147 (*i) to be part of the signal flow even if only
4150 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4154 route->soloed_by_others_downstream(),
4155 route->soloed_by_others_upstream()));
4156 if (!via_sends_only) {
4157 //NB. Triggers Invert Push, which handles soloed by downstream
4158 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4159 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4161 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4163 in_signal_flow = true;
4165 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4168 if (!in_signal_flow) {
4169 uninvolved.push_back (*i);
4173 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4175 /* now notify that the mute state of the routes not involved in the signal
4176 pathway of the just-solo-changed route may have altered.
4179 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4180 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4181 (*i)->act_on_mute ();
4182 /* Session will emit SoloChanged() after all solo changes are
4183 * complete, which should be used by UIs to update mute status
4189 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4191 /* now figure out if anything that matters is soloed (or is "listening")*/
4193 bool something_soloed = false;
4194 bool something_listening = false;
4195 uint32_t listeners = 0;
4196 uint32_t isolated = 0;
4199 r = routes.reader();
4202 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4203 if ((*i)->can_solo()) {
4204 if (Config->get_solo_control_is_listen_control()) {
4205 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4207 something_listening = true;
4210 (*i)->set_listen (false);
4211 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4212 something_soloed = true;
4217 if ((*i)->solo_isolate_control()->solo_isolated()) {
4222 if (something_soloed != _non_soloed_outs_muted) {
4223 _non_soloed_outs_muted = something_soloed;
4224 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4227 if (something_listening != _listening) {
4228 _listening = something_listening;
4229 SoloActive (_listening);
4232 _listen_cnt = listeners;
4234 if (isolated != _solo_isolated_cnt) {
4235 _solo_isolated_cnt = isolated;
4236 IsolatedChanged (); /* EMIT SIGNAL */
4239 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4240 something_soloed, listeners, isolated));
4243 SoloChanged (); /* EMIT SIGNAL */
4248 Session::muted () const
4250 // TODO consider caching the value on every MuteChanged signal,
4251 // Note that API users may also subscribe to MuteChanged and hence
4252 // this method needs to be called first.
4255 get_stripables (all);
4256 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4257 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4260 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4261 if (r && !r->active()) {
4264 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4265 if (mc && mc->muted ()) {
4273 std::vector<boost::weak_ptr<AutomationControl> >
4274 Session::cancel_all_mute ()
4277 get_stripables (all);
4278 std::vector<boost::weak_ptr<AutomationControl> > muted;
4279 boost::shared_ptr<ControlList> cl (new ControlList);
4280 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4281 if ((*i)->is_auditioner() || (*i)->is_monitor()) {
4284 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4285 if (r && !r->active()) {
4288 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4289 if (ac && ac->get_value () > 0) {
4291 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4294 if (!cl->empty ()) {
4295 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4301 Session::get_stripables (StripableList& sl) const
4303 boost::shared_ptr<RouteList> r = routes.reader ();
4304 sl.insert (sl.end(), r->begin(), r->end());
4306 VCAList v = _vca_manager->vcas ();
4307 sl.insert (sl.end(), v.begin(), v.end());
4311 Session::get_stripables () const
4314 Session::get_stripables (rv);
4315 rv.sort (Stripable::Sorter ());
4319 boost::shared_ptr<RouteList>
4320 Session::get_routes_with_internal_returns() const
4322 boost::shared_ptr<RouteList> r = routes.reader ();
4323 boost::shared_ptr<RouteList> rl (new RouteList);
4325 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4326 if ((*i)->internal_return ()) {
4334 Session::io_name_is_legal (const std::string& name) const
4336 boost::shared_ptr<RouteList> r = routes.reader ();
4338 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4339 if (name == reserved->first) {
4340 if (!route_by_name (reserved->first)) {
4341 /* first instance of a reserved name is allowed for some */
4342 return reserved->second;
4344 /* all other instances of a reserved name are not allowed */
4349 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4350 if ((*i)->name() == name) {
4354 if ((*i)->has_io_processor_named (name)) {
4363 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4366 vector<string> connections;
4368 /* if we are passed only a single route and we're not told to turn
4369 * others off, then just do the simple thing.
4372 if (flip_others == false && rl->size() == 1) {
4373 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4375 mt->set_input_active (onoff);
4380 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4382 PortSet& ps ((*rt)->input()->ports());
4384 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4385 p->get_connections (connections);
4388 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4389 routes_using_input_from (*s, rl2);
4392 /* scan all relevant routes to see if others are on or off */
4394 bool others_are_already_on = false;
4396 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4398 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4404 if ((*r) != (*rt)) {
4405 if (mt->input_active()) {
4406 others_are_already_on = true;
4409 /* this one needs changing */
4410 mt->set_input_active (onoff);
4416 /* globally reverse other routes */
4418 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4419 if ((*r) != (*rt)) {
4420 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4422 mt->set_input_active (!others_are_already_on);
4431 Session::routes_using_input_from (const string& str, RouteList& rl)
4433 boost::shared_ptr<RouteList> r = routes.reader();
4435 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4436 if ((*i)->input()->connected_to (str)) {
4442 boost::shared_ptr<Route>
4443 Session::route_by_name (string name) const
4445 boost::shared_ptr<RouteList> r = routes.reader ();
4447 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4448 if ((*i)->name() == name) {
4453 return boost::shared_ptr<Route> ((Route*) 0);
4456 boost::shared_ptr<Route>
4457 Session::route_by_id (PBD::ID id) const
4459 boost::shared_ptr<RouteList> r = routes.reader ();
4461 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4462 if ((*i)->id() == id) {
4467 return boost::shared_ptr<Route> ((Route*) 0);
4471 boost::shared_ptr<Stripable>
4472 Session::stripable_by_id (PBD::ID id) const
4475 get_stripables (sl);
4477 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4478 if ((*s)->id() == id) {
4483 return boost::shared_ptr<Stripable>();
4486 boost::shared_ptr<Processor>
4487 Session::processor_by_id (PBD::ID id) const
4489 boost::shared_ptr<RouteList> r = routes.reader ();
4491 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4492 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4498 return boost::shared_ptr<Processor> ();
4501 boost::shared_ptr<Track>
4502 Session::track_by_diskstream_id (PBD::ID id) const
4504 boost::shared_ptr<RouteList> r = routes.reader ();
4506 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4507 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4508 if (t && t->using_diskstream_id (id)) {
4513 return boost::shared_ptr<Track> ();
4516 boost::shared_ptr<Route>
4517 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4519 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4522 boost::shared_ptr<Stripable>
4523 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4526 PresentationInfo::order_t match_cnt = 0;
4528 get_stripables (sl);
4529 sl.sort (Stripable::Sorter());
4531 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4533 if ((*s)->presentation_info().hidden()) {
4534 /* if the caller didn't explicitly ask for hidden
4535 stripables, ignore hidden ones. This matches
4536 the semantics of the pre-PresentationOrder
4537 "get by RID" logic of Ardour 4.x and earlier.
4539 XXX at some point we should likely reverse
4540 the logic of the flags, because asking for "the
4541 hidden stripables" is not going to be common,
4542 whereas asking for visible ones is normal.
4545 if (! (flags & PresentationInfo::Hidden)) {
4550 if ((*s)->presentation_info().flag_match (flags)) {
4551 if (match_cnt++ == n) {
4557 /* there is no nth stripable that matches the given flags */
4558 return boost::shared_ptr<Stripable>();
4561 boost::shared_ptr<Route>
4562 Session::route_by_selected_count (uint32_t id) const
4564 RouteList r (*(routes.reader ()));
4565 r.sort (Stripable::Sorter());
4567 RouteList::iterator i;
4569 for (i = r.begin(); i != r.end(); ++i) {
4570 if ((*i)->is_selected()) {
4578 return boost::shared_ptr<Route> ();
4582 Session::reassign_track_numbers ()
4586 RouteList r (*(routes.reader ()));
4587 r.sort (Stripable::Sorter());
4589 StateProtector sp (this);
4591 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4592 if (boost::dynamic_pointer_cast<Track> (*i)) {
4593 (*i)->set_track_number(++tn);
4595 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4596 (*i)->set_track_number(--bn);
4599 const uint32_t decimals = ceilf (log10f (tn + 1));
4600 const bool decimals_changed = _track_number_decimals != decimals;
4601 _track_number_decimals = decimals;
4603 if (decimals_changed && config.get_track_name_number ()) {
4604 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4605 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4607 t->resync_track_name();
4610 // trigger GUI re-layout
4611 config.ParameterChanged("track-name-number");
4615 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4616 boost::shared_ptr<RouteList> rl = routes.reader ();
4617 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4618 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4626 Session::playlist_region_added (boost::weak_ptr<Region> w)
4628 boost::shared_ptr<Region> r = w.lock ();
4633 /* These are the operations that are currently in progress... */
4634 list<GQuark> curr = _current_trans_quarks;
4637 /* ...and these are the operations during which we want to update
4638 the session range location markers.
4641 ops.push_back (Operations::capture);
4642 ops.push_back (Operations::paste);
4643 ops.push_back (Operations::duplicate_region);
4644 ops.push_back (Operations::insert_file);
4645 ops.push_back (Operations::insert_region);
4646 ops.push_back (Operations::drag_region_brush);
4647 ops.push_back (Operations::region_drag);
4648 ops.push_back (Operations::selection_grab);
4649 ops.push_back (Operations::region_fill);
4650 ops.push_back (Operations::fill_selection);
4651 ops.push_back (Operations::create_region);
4652 ops.push_back (Operations::region_copy);
4653 ops.push_back (Operations::fixed_time_region_copy);
4656 /* See if any of the current operations match the ones that we want */
4658 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4660 /* If so, update the session range markers */
4662 maybe_update_session_range (r->position (), r->last_frame ());
4666 /** Update the session range markers if a is before the current start or
4667 * b is after the current end.
4670 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4672 if (_state_of_the_state & Loading) {
4676 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4678 if (_session_range_location == 0) {
4680 set_session_range_location (a, b + session_end_marker_shift_samples);
4684 if (a < _session_range_location->start()) {
4685 _session_range_location->set_start (a);
4688 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4689 _session_range_location->set_end (b);
4695 Session::set_end_is_free (bool yn)
4697 _session_range_end_is_free = yn;
4701 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4703 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4704 maybe_update_session_range (i->to, i->to + i->length);
4709 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4711 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4712 maybe_update_session_range (i->from, i->to);
4716 /* Region management */
4718 boost::shared_ptr<Region>
4719 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4721 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4722 RegionFactory::RegionMap::const_iterator i;
4723 boost::shared_ptr<Region> region;
4725 Glib::Threads::Mutex::Lock lm (region_lock);
4727 for (i = regions.begin(); i != regions.end(); ++i) {
4731 if (region->whole_file()) {
4733 if (child->source_equivalent (region)) {
4739 return boost::shared_ptr<Region> ();
4743 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4745 set<boost::shared_ptr<Region> > relevant_regions;
4747 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4748 RegionFactory::get_regions_using_source (*s, relevant_regions);
4751 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4752 set<boost::shared_ptr<Region> >::iterator tmp;
4757 playlists->destroy_region (*r);
4758 RegionFactory::map_remove (*r);
4760 (*r)->drop_sources ();
4761 (*r)->drop_references ();
4763 relevant_regions.erase (r);
4768 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4771 Glib::Threads::Mutex::Lock ls (source_lock);
4772 /* remove from the main source list */
4773 sources.erase ((*s)->id());
4776 (*s)->mark_for_remove ();
4777 (*s)->drop_references ();
4786 Session::remove_last_capture ()
4788 list<boost::shared_ptr<Source> > srcs;
4790 boost::shared_ptr<RouteList> rl = routes.reader ();
4791 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4792 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4797 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4800 srcs.insert (srcs.end(), l.begin(), l.end());
4805 destroy_sources (srcs);
4807 save_state (_current_snapshot_name);
4812 /* Source Management */
4815 Session::add_source (boost::shared_ptr<Source> source)
4817 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4818 pair<SourceMap::iterator,bool> result;
4820 entry.first = source->id();
4821 entry.second = source;
4824 Glib::Threads::Mutex::Lock lm (source_lock);
4825 result = sources.insert (entry);
4828 if (result.second) {
4830 /* yay, new source */
4832 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4835 if (!fs->within_session()) {
4836 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4842 boost::shared_ptr<AudioFileSource> afs;
4844 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4845 if (Config->get_auto_analyse_audio()) {
4846 Analyser::queue_source_for_analysis (source, false);
4850 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4855 Session::remove_source (boost::weak_ptr<Source> src)
4857 if (_state_of_the_state & Deletion) {
4861 SourceMap::iterator i;
4862 boost::shared_ptr<Source> source = src.lock();
4869 Glib::Threads::Mutex::Lock lm (source_lock);
4871 if ((i = sources.find (source->id())) != sources.end()) {
4876 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4878 /* save state so we don't end up with a session file
4879 referring to non-existent sources.
4882 save_state (_current_snapshot_name);
4886 boost::shared_ptr<Source>
4887 Session::source_by_id (const PBD::ID& id)
4889 Glib::Threads::Mutex::Lock lm (source_lock);
4890 SourceMap::iterator i;
4891 boost::shared_ptr<Source> source;
4893 if ((i = sources.find (id)) != sources.end()) {
4900 boost::shared_ptr<AudioFileSource>
4901 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4903 /* Restricted to audio files because only audio sources have channel
4907 Glib::Threads::Mutex::Lock lm (source_lock);
4909 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4910 boost::shared_ptr<AudioFileSource> afs
4911 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4913 if (afs && afs->path() == path && chn == afs->channel()) {
4918 return boost::shared_ptr<AudioFileSource>();
4921 boost::shared_ptr<MidiSource>
4922 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4924 /* Restricted to MIDI files because audio sources require a channel
4925 for unique identification, in addition to a path.
4928 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4929 if (need_source_lock) {
4933 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4934 boost::shared_ptr<MidiSource> ms
4935 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4936 boost::shared_ptr<FileSource> fs
4937 = boost::dynamic_pointer_cast<FileSource>(s->second);
4939 if (ms && fs && fs->path() == path) {
4944 return boost::shared_ptr<MidiSource>();
4948 Session::count_sources_by_origin (const string& path)
4951 Glib::Threads::Mutex::Lock lm (source_lock);
4953 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4954 boost::shared_ptr<FileSource> fs
4955 = boost::dynamic_pointer_cast<FileSource>(i->second);
4957 if (fs && fs->origin() == path) {
4966 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4968 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4969 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4971 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4976 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4978 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4980 if (Glib::path_is_absolute (filepath)) {
4982 /* rip the session dir from the audiofile source */
4984 string session_path;
4985 bool in_another_session = true;
4987 if (filepath.find (interchange_dir_string) != string::npos) {
4989 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4990 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4991 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4992 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4994 /* see if it is within our session */
4996 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4997 if (i->path == session_path) {
4998 in_another_session = false;
5003 in_another_session = false;
5007 if (in_another_session) {
5008 SessionDirectory sd (session_path);
5009 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
5013 /* 1) if file belongs to this session
5014 * it may be a relative path (interchange/...)
5015 * or just basename (session_state, remove source)
5016 * -> just use the basename
5018 std::string filename = Glib::path_get_basename (filepath);
5021 /* 2) if the file is outside our session dir:
5022 * (imported but not copied) add the path for check-summming */
5024 path = Glib::path_get_dirname (filepath);
5027 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
5031 Session::new_audio_source_path_for_embedded (const std::string& path)
5035 * we know that the filename is already unique because it exists
5036 * out in the filesystem.
5038 * However, when we bring it into the session, we could get a
5041 * Eg. two embedded files:
5046 * When merged into session, these collide.
5048 * There will not be a conflict with in-memory sources
5049 * because when the source was created we already picked
5050 * a unique name for it.
5052 * This collision is not likely to be common, but we have to guard
5053 * against it. So, if there is a collision, take the md5 hash of the
5054 * the path, and use that as the filename instead.
5057 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5058 string base = Glib::path_get_basename (path);
5059 string newpath = Glib::build_filename (sdir.sound_path(), base);
5061 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5065 md5.digestString (path.c_str());
5066 md5.writeToString ();
5067 base = md5.digestChars;
5069 string ext = get_suffix (path);
5076 newpath = Glib::build_filename (sdir.sound_path(), base);
5078 /* if this collides, we're screwed */
5080 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5081 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5090 /** Return true if there are no audio file sources that use @param name as
5091 * the filename component of their path.
5093 * Return false otherwise.
5095 * This method MUST ONLY be used to check in-session, mono files since it
5096 * hard-codes the channel of the audio file source we are looking for as zero.
5098 * If/when Ardour supports native files in non-mono formats, the logic here
5099 * will need to be revisited.
5102 Session::audio_source_name_is_unique (const string& name)
5104 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5105 vector<space_and_path>::iterator i;
5106 uint32_t existing = 0;
5108 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5110 /* note that we search *without* the extension so that
5111 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5112 in the event that this new name is required for
5113 a file format change.
5116 const string spath = *i;
5118 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5123 /* it is possible that we have the path already
5124 * assigned to a source that has not yet been written
5125 * (ie. the write source for a diskstream). we have to
5126 * check this in order to make sure that our candidate
5127 * path isn't used again, because that can lead to
5128 * two Sources point to the same file with different
5129 * notions of their removability.
5133 string possible_path = Glib::build_filename (spath, name);
5135 if (audio_source_by_path_and_channel (possible_path, 0)) {
5141 return (existing == 0);
5145 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)
5148 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5150 if (Profile->get_trx() && destructive) {
5152 sstr << setfill ('0') << setw (4) << cnt;
5153 sstr << legalized_base;
5155 sstr << legalized_base;
5157 if (take_required || related_exists) {
5169 } else if (nchan > 2) {
5174 /* XXX what? more than 26 channels! */
5185 /** Return a unique name based on \a base for a new internal audio source */
5187 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5190 string possible_name;
5191 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5193 bool some_related_source_name_exists = false;
5195 legalized = legalize_for_path (base);
5197 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5199 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5201 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5203 if (audio_source_name_is_unique (possible_name)) {
5207 some_related_source_name_exists = true;
5210 error << string_compose(
5211 _("There are already %1 recordings for %2, which I consider too many."),
5212 limit, base) << endmsg;
5214 throw failed_constructor();
5218 /* We've established that the new name does not exist in any session
5219 * directory, so now find out which one we should use for this new
5223 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5225 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5230 /** Return a unique name based on `base` for a new internal MIDI source */
5232 Session::new_midi_source_path (const string& base, bool need_lock)
5235 char buf[PATH_MAX+1];
5236 const uint32_t limit = 10000;
5238 string possible_path;
5239 string possible_name;
5242 legalized = legalize_for_path (base);
5244 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5245 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5247 /* - the main session folder is the first in the vector.
5248 * - after checking all locations for file-name uniqueness,
5249 * we keep the one from the last iteration as new file name
5250 * - midi files are small and should just be kept in the main session-folder
5252 * -> reverse the array, check main session folder last and use that as location
5255 std::reverse(sdirs.begin(), sdirs.end());
5257 for (cnt = 1; cnt <= limit; ++cnt) {
5259 vector<space_and_path>::iterator i;
5260 uint32_t existing = 0;
5262 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5264 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5265 possible_name = buf;
5267 possible_path = Glib::build_filename (*i, possible_name);
5269 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5273 if (midi_source_by_path (possible_path, need_lock)) {
5278 if (existing == 0) {
5283 error << string_compose(
5284 _("There are already %1 recordings for %2, which I consider too many."),
5285 limit, base) << endmsg;
5291 /* No need to "find best location" for software/app-based RAID, because
5292 MIDI is so small that we always put it in the same place.
5295 return possible_path;
5299 /** Create a new within-session audio source */
5300 boost::shared_ptr<AudioFileSource>
5301 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5303 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5305 if (!path.empty()) {
5306 return boost::dynamic_pointer_cast<AudioFileSource> (
5307 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5309 throw failed_constructor ();
5313 /** Create a new within-session MIDI source */
5314 boost::shared_ptr<MidiSource>
5315 Session::create_midi_source_for_session (string const & basic_name)
5317 const string path = new_midi_source_path (basic_name);
5319 if (!path.empty()) {
5320 return boost::dynamic_pointer_cast<SMFSource> (
5321 SourceFactory::createWritable (
5322 DataType::MIDI, *this, path, false, frame_rate()));
5324 throw failed_constructor ();
5328 /** Create a new within-session MIDI source */
5329 boost::shared_ptr<MidiSource>
5330 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5332 /* the caller passes in the track the source will be used in,
5333 so that we can keep the numbering sane.
5335 Rationale: a track with the name "Foo" that has had N
5336 captures carried out so far will ALREADY have a write source
5337 named "Foo-N+1.mid" waiting to be used for the next capture.
5339 If we call new_midi_source_name() we will get "Foo-N+2". But
5340 there is no region corresponding to "Foo-N+1", so when
5341 "Foo-N+2" appears in the track, the gap presents the user
5342 with odd behaviour - why did it skip past Foo-N+1?
5344 We could explain this to the user in some odd way, but
5345 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5348 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5351 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5353 std::string name = track->steal_write_source_name ();
5356 return boost::shared_ptr<MidiSource>();
5359 /* MIDI files are small, just put them in the first location of the
5360 session source search path.
5363 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5365 return boost::dynamic_pointer_cast<SMFSource> (
5366 SourceFactory::createWritable (
5367 DataType::MIDI, *this, path, false, frame_rate()));
5372 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5374 if (playlist->hidden()) {
5378 playlists->add (playlist);
5381 playlist->release();
5388 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5390 if (_state_of_the_state & Deletion) {
5394 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5400 playlists->remove (playlist);
5406 Session::set_audition (boost::shared_ptr<Region> r)
5408 pending_audition_region = r;
5409 add_post_transport_work (PostTransportAudition);
5410 _butler->schedule_transport_work ();
5414 Session::audition_playlist ()
5416 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5417 ev->region.reset ();
5423 Session::register_lua_function (
5424 const std::string& name,
5425 const std::string& script,
5426 const LuaScriptParamList& args
5429 Glib::Threads::Mutex::Lock lm (lua_lock);
5431 lua_State* L = lua.getState();
5433 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5434 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5435 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5436 if ((*i)->optional && !(*i)->is_set) { continue; }
5437 tbl_arg[(*i)->name] = (*i)->value;
5439 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5442 LuaScriptsChanged (); /* EMIT SIGNAL */
5447 Session::unregister_lua_function (const std::string& name)
5449 Glib::Threads::Mutex::Lock lm (lua_lock);
5450 (*_lua_del)(name); // throws luabridge::LuaException
5451 lua.collect_garbage ();
5454 LuaScriptsChanged (); /* EMIT SIGNAL */
5458 std::vector<std::string>
5459 Session::registered_lua_functions ()
5461 Glib::Threads::Mutex::Lock lm (lua_lock);
5462 std::vector<std::string> rv;
5465 luabridge::LuaRef list ((*_lua_list)());
5466 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5467 if (!i.key ().isString ()) { assert(0); continue; }
5468 rv.push_back (i.key ().cast<std::string> ());
5470 } catch (luabridge::LuaException const& e) { }
5475 static void _lua_print (std::string s) {
5476 std::cout << "SessionLua: " << s << "\n";
5481 Session::try_run_lua (pframes_t nframes)
5483 if (_n_lua_scripts == 0) return;
5484 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5486 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5487 lua.collect_garbage_step ();
5492 Session::setup_lua ()
5495 lua.Print.connect (&_lua_print);
5499 "function ArdourSession ()"
5500 " local self = { scripts = {}, instances = {} }"
5502 " local remove = function (n)"
5503 " self.scripts[n] = nil"
5504 " self.instances[n] = nil"
5505 " Session:scripts_changed()" // call back
5508 " local addinternal = function (n, f, a)"
5509 " assert(type(n) == 'string', 'function-name must be string')"
5510 " assert(type(f) == 'function', 'Given script is a not a function')"
5511 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5512 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5513 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5514 " 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"
5515 " 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 }"
5516 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5517 " Session:scripts_changed()" // call back
5520 " local add = function (n, b, a)"
5521 " assert(type(b) == 'string', 'ByteCode must be string')"
5522 " load (b)()" // assigns f
5523 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5524 " addinternal (n, load(f), a)"
5527 " local run = function (...)"
5528 " for n, s in pairs (self.instances) do"
5529 " local status, err = pcall (s, ...)"
5530 " if not status then"
5531 " print ('fn \"'.. n .. '\": ', err)"
5538 " local cleanup = function ()"
5539 " self.scripts = nil"
5540 " self.instances = nil"
5543 " local list = function ()"
5545 " for n, _ in pairs (self.scripts) do"
5551 " local function basic_serialize (o)"
5552 " if type(o) == \"number\" then"
5553 " return tostring(o)"
5555 " return string.format(\"%q\", o)"
5559 " local function serialize (name, value)"
5560 " local rv = name .. ' = '"
5562 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5563 " return rv .. basic_serialize(value) .. ' '"
5564 " elseif type(value) == \"table\" then"
5566 " for k,v in pairs(value) do"
5567 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5568 " rv = rv .. serialize(fieldname, v) .. ' '"
5569 " collectgarbage()" // string concatenation allocates a new string :(
5572 " elseif type(value) == \"function\" then"
5573 " return rv .. string.format(\"%q\", string.dump(value, true))"
5575 " error('cannot save a ' .. type(value))"
5580 " local save = function ()"
5581 " return (serialize('scripts', self.scripts))"
5584 " local restore = function (state)"
5585 " self.scripts = {}"
5587 " for n, s in pairs (scripts) do"
5588 " addinternal (n, load(s['f']), s['a'])"
5592 " return { run = run, add = add, remove = remove,"
5593 " list = list, restore = restore, save = save, cleanup = cleanup}"
5596 " sess = ArdourSession ()"
5597 " ArdourSession = nil"
5599 "function ardour () end"
5602 lua_State* L = lua.getState();
5605 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5606 lua.do_command ("sess = nil"); // hide it.
5607 lua.do_command ("collectgarbage()");
5609 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5610 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5611 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5612 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5613 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5614 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5615 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5616 } catch (luabridge::LuaException const& e) {
5617 fatal << string_compose (_("programming error: %1"),
5618 X_("Failed to setup Lua interpreter"))
5620 abort(); /*NOTREACHED*/
5623 LuaBindings::stddef (L);
5624 LuaBindings::common (L);
5625 LuaBindings::dsp (L);
5626 luabridge::push <Session *> (L, this);
5627 lua_setglobal (L, "Session");
5631 Session::scripts_changed ()
5633 assert (!lua_lock.trylock()); // must hold lua_lock
5636 luabridge::LuaRef list ((*_lua_list)());
5638 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5639 if (!i.key ().isString ()) { assert(0); continue; }
5642 _n_lua_scripts = cnt;
5643 } catch (luabridge::LuaException const& e) {
5644 fatal << string_compose (_("programming error: %1"),
5645 X_("Indexing Lua Session Scripts failed."))
5647 abort(); /*NOTREACHED*/
5652 Session::non_realtime_set_audition ()
5654 assert (pending_audition_region);
5655 auditioner->audition_region (pending_audition_region);
5656 pending_audition_region.reset ();
5657 AuditionActive (true); /* EMIT SIGNAL */
5661 Session::audition_region (boost::shared_ptr<Region> r)
5663 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5669 Session::cancel_audition ()
5674 if (auditioner->auditioning()) {
5675 auditioner->cancel_audition ();
5676 AuditionActive (false); /* EMIT SIGNAL */
5681 Session::is_auditioning () const
5683 /* can be called before we have an auditioner object */
5685 return auditioner->auditioning();
5692 Session::graph_reordered ()
5694 /* don't do this stuff if we are setting up connections
5695 from a set_state() call or creating new tracks. Ditto for deletion.
5698 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5702 /* every track/bus asked for this to be handled but it was deferred because
5703 we were connecting. do it now.
5706 request_input_change_handling ();
5710 /* force all diskstreams to update their capture offset values to
5711 reflect any changes in latencies within the graph.
5714 boost::shared_ptr<RouteList> rl = routes.reader ();
5715 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5716 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5718 tr->set_capture_offset ();
5723 /** @return Number of frames that there is disk space available to write,
5726 boost::optional<framecnt_t>
5727 Session::available_capture_duration ()
5729 Glib::Threads::Mutex::Lock lm (space_lock);
5731 if (_total_free_4k_blocks_uncertain) {
5732 return boost::optional<framecnt_t> ();
5735 float sample_bytes_on_disk = 4.0; // keep gcc happy
5737 switch (config.get_native_file_data_format()) {
5739 sample_bytes_on_disk = 4.0;
5743 sample_bytes_on_disk = 3.0;
5747 sample_bytes_on_disk = 2.0;
5751 /* impossible, but keep some gcc versions happy */
5752 fatal << string_compose (_("programming error: %1"),
5753 X_("illegal native file data format"))
5755 abort(); /*NOTREACHED*/
5758 double scale = 4096.0 / sample_bytes_on_disk;
5760 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5761 return max_framecnt;
5764 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5768 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5771 RCUWriter<BundleList> writer (_bundles);
5772 boost::shared_ptr<BundleList> b = writer.get_copy ();
5773 b->push_back (bundle);
5777 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5784 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5786 bool removed = false;
5789 RCUWriter<BundleList> writer (_bundles);
5790 boost::shared_ptr<BundleList> b = writer.get_copy ();
5791 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5793 if (i != b->end()) {
5800 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5806 boost::shared_ptr<Bundle>
5807 Session::bundle_by_name (string name) const
5809 boost::shared_ptr<BundleList> b = _bundles.reader ();
5811 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5812 if ((*i)->name() == name) {
5817 return boost::shared_ptr<Bundle> ();
5821 Session::tempo_map_changed (const PropertyChange&)
5825 playlists->update_after_tempo_map_change ();
5827 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5833 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5835 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5836 (*i)->recompute_frames_from_beat ();
5840 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5841 * the given count with the current block size.
5844 Session::ensure_buffers (ChanCount howmany)
5846 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5850 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5852 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5853 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5858 Session::next_insert_id ()
5860 /* this doesn't really loop forever. just think about it */
5863 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5864 if (!insert_bitset[n]) {
5865 insert_bitset[n] = true;
5871 /* none available, so resize and try again */
5873 insert_bitset.resize (insert_bitset.size() + 16, false);
5878 Session::next_send_id ()
5880 /* this doesn't really loop forever. just think about it */
5883 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5884 if (!send_bitset[n]) {
5885 send_bitset[n] = true;
5891 /* none available, so resize and try again */
5893 send_bitset.resize (send_bitset.size() + 16, false);
5898 Session::next_aux_send_id ()
5900 /* this doesn't really loop forever. just think about it */
5903 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5904 if (!aux_send_bitset[n]) {
5905 aux_send_bitset[n] = true;
5911 /* none available, so resize and try again */
5913 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5918 Session::next_return_id ()
5920 /* this doesn't really loop forever. just think about it */
5923 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5924 if (!return_bitset[n]) {
5925 return_bitset[n] = true;
5931 /* none available, so resize and try again */
5933 return_bitset.resize (return_bitset.size() + 16, false);
5938 Session::mark_send_id (uint32_t id)
5940 if (id >= send_bitset.size()) {
5941 send_bitset.resize (id+16, false);
5943 if (send_bitset[id]) {
5944 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5946 send_bitset[id] = true;
5950 Session::mark_aux_send_id (uint32_t id)
5952 if (id >= aux_send_bitset.size()) {
5953 aux_send_bitset.resize (id+16, false);
5955 if (aux_send_bitset[id]) {
5956 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5958 aux_send_bitset[id] = true;
5962 Session::mark_return_id (uint32_t id)
5964 if (id >= return_bitset.size()) {
5965 return_bitset.resize (id+16, false);
5967 if (return_bitset[id]) {
5968 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5970 return_bitset[id] = true;
5974 Session::mark_insert_id (uint32_t id)
5976 if (id >= insert_bitset.size()) {
5977 insert_bitset.resize (id+16, false);
5979 if (insert_bitset[id]) {
5980 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5982 insert_bitset[id] = true;
5986 Session::unmark_send_id (uint32_t id)
5988 if (id < send_bitset.size()) {
5989 send_bitset[id] = false;
5994 Session::unmark_aux_send_id (uint32_t id)
5996 if (id < aux_send_bitset.size()) {
5997 aux_send_bitset[id] = false;
6002 Session::unmark_return_id (uint32_t id)
6004 if (_state_of_the_state & Deletion) { return; }
6005 if (id < return_bitset.size()) {
6006 return_bitset[id] = false;
6011 Session::unmark_insert_id (uint32_t id)
6013 if (id < insert_bitset.size()) {
6014 insert_bitset[id] = false;
6019 Session::reset_native_file_format ()
6021 boost::shared_ptr<RouteList> rl = routes.reader ();
6023 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6024 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6026 /* don't save state as we do this, there's no point
6028 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
6029 tr->reset_write_sources (false);
6030 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
6036 Session::route_name_unique (string n) const
6038 boost::shared_ptr<RouteList> r = routes.reader ();
6040 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6041 if ((*i)->name() == n) {
6050 Session::route_name_internal (string n) const
6052 if (auditioner && auditioner->name() == n) {
6056 if (_click_io && _click_io->name() == n) {
6064 Session::freeze_all (InterThreadInfo& itt)
6066 boost::shared_ptr<RouteList> r = routes.reader ();
6068 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6070 boost::shared_ptr<Track> t;
6072 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6073 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6083 boost::shared_ptr<Region>
6084 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
6085 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6086 InterThreadInfo& itt,
6087 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6088 bool for_export, bool for_freeze)
6090 boost::shared_ptr<Region> result;
6091 boost::shared_ptr<Playlist> playlist;
6092 boost::shared_ptr<Source> source;
6093 ChanCount diskstream_channels (track.n_channels());
6094 framepos_t position;
6095 framecnt_t this_chunk;
6097 framepos_t latency_skip;
6099 framepos_t len = end - start;
6100 bool need_block_size_reset = false;
6101 ChanCount const max_proc = track.max_processor_streams ();
6102 string legal_playlist_name;
6103 string possible_path;
6106 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
6107 end, start) << endmsg;
6111 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
6112 include_endpoint, for_export, for_freeze);
6114 if (diskstream_channels.n(track.data_type()) < 1) {
6115 error << _("Cannot write a range with no data.") << endmsg;
6119 // block all process callback handling
6121 block_processing ();
6124 // synchronize with AudioEngine::process_callback()
6125 // make sure processing is not currently running
6126 // and processing_blocked() is honored before
6127 // acquiring thread buffers
6128 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6131 _bounce_processing_active = true;
6133 /* call tree *MUST* hold route_lock */
6135 if ((playlist = track.playlist()) == 0) {
6139 legal_playlist_name = legalize_for_path (playlist->name());
6141 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
6143 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6144 string path = ((track.data_type() == DataType::AUDIO)
6145 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6146 : new_midi_source_path (legal_playlist_name));
6153 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6156 catch (failed_constructor& err) {
6157 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6161 srcs.push_back (source);
6164 /* tell redirects that care that we are about to use a much larger
6165 * blocksize. this will flush all plugins too, so that they are ready
6166 * to be used for this process.
6169 need_block_size_reset = true;
6170 track.set_block_size (bounce_chunk_size);
6171 _engine.main_thread()->get_buffers ();
6175 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6177 /* create a set of reasonably-sized buffers */
6178 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6179 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6181 buffers.set_count (max_proc);
6183 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6184 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6185 boost::shared_ptr<MidiSource> ms;
6187 afs->prepare_for_peakfile_writes ();
6188 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6189 Source::Lock lock(ms->mutex());
6190 ms->mark_streaming_write_started(lock);
6194 while (to_do && !itt.cancel) {
6196 this_chunk = min (to_do, bounce_chunk_size);
6198 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6202 start += this_chunk;
6203 to_do -= this_chunk;
6204 itt.progress = (float) (1.0 - ((double) to_do / len));
6206 if (latency_skip >= bounce_chunk_size) {
6207 latency_skip -= bounce_chunk_size;
6211 const framecnt_t current_chunk = this_chunk - latency_skip;
6214 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6215 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6216 boost::shared_ptr<MidiSource> ms;
6219 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6222 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6223 Source::Lock lock(ms->mutex());
6225 const MidiBuffer& buf = buffers.get_midi(0);
6226 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6227 Evoral::Event<framepos_t> ev = *i;
6228 ev.set_time(ev.time() - position);
6229 ms->append_event_frames(lock, ev, ms->timeline_position());
6236 /* post-roll, pick up delayed processor output */
6237 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6239 while (latency_skip && !itt.cancel) {
6240 this_chunk = min (latency_skip, bounce_chunk_size);
6241 latency_skip -= this_chunk;
6243 buffers.silence (this_chunk, 0);
6244 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6247 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6248 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6251 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6263 xnow = localtime (&now);
6265 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6266 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6267 boost::shared_ptr<MidiSource> ms;
6270 afs->update_header (position, *xnow, now);
6271 afs->flush_header ();
6272 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6273 Source::Lock lock(ms->mutex());
6274 ms->mark_streaming_write_completed(lock);
6278 /* construct a region to represent the bounced material */
6282 plist.add (Properties::start, 0);
6283 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6284 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6286 result = RegionFactory::create (srcs, plist);
6292 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6293 (*src)->mark_for_remove ();
6294 (*src)->drop_references ();
6298 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6299 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6302 afs->done_with_peakfile_writes ();
6306 _bounce_processing_active = false;
6308 if (need_block_size_reset) {
6309 _engine.main_thread()->drop_buffers ();
6310 track.set_block_size (get_block_size());
6313 unblock_processing ();
6319 Session::gain_automation_buffer() const
6321 return ProcessThread::gain_automation_buffer ();
6325 Session::trim_automation_buffer() const
6327 return ProcessThread::trim_automation_buffer ();
6331 Session::send_gain_automation_buffer() const
6333 return ProcessThread::send_gain_automation_buffer ();
6337 Session::scratch_automation_buffer() const
6339 return ProcessThread::scratch_automation_buffer ();
6343 Session::pan_automation_buffer() const
6345 return ProcessThread::pan_automation_buffer ();
6349 Session::get_silent_buffers (ChanCount count)
6351 return ProcessThread::get_silent_buffers (count);
6355 Session::get_scratch_buffers (ChanCount count, bool silence)
6357 return ProcessThread::get_scratch_buffers (count, silence);
6361 Session::get_noinplace_buffers (ChanCount count)
6363 return ProcessThread::get_noinplace_buffers (count);
6367 Session::get_route_buffers (ChanCount count, bool silence)
6369 return ProcessThread::get_route_buffers (count, silence);
6374 Session::get_mix_buffers (ChanCount count)
6376 return ProcessThread::get_mix_buffers (count);
6380 Session::ntracks () const
6383 boost::shared_ptr<RouteList> r = routes.reader ();
6385 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6386 if (boost::dynamic_pointer_cast<Track> (*i)) {
6395 Session::nbusses () const
6398 boost::shared_ptr<RouteList> r = routes.reader ();
6400 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6401 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6410 Session::nstripables (bool with_auditioner_and_monitor) const
6412 uint32_t rv = routes.reader()->size ();
6413 rv += _vca_manager->vcas ().size ();
6415 if (with_auditioner_and_monitor) {
6431 Session::add_automation_list(AutomationList *al)
6433 automation_lists[al->id()] = al;
6436 /** @return true if there is at least one record-enabled track, otherwise false */
6438 Session::have_rec_enabled_track () const
6440 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6444 Session::have_rec_disabled_track () const
6446 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6449 /** Update the state of our rec-enabled tracks flag */
6451 Session::update_route_record_state ()
6453 boost::shared_ptr<RouteList> rl = routes.reader ();
6454 RouteList::iterator i = rl->begin();
6455 while (i != rl->end ()) {
6457 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6458 if (tr && tr->rec_enable_control()->get_value()) {
6465 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6467 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6469 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6470 RecordStateChanged (); /* EMIT SIGNAL */
6473 for (i = rl->begin(); i != rl->end (); ++i) {
6474 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6475 if (tr && !tr->rec_enable_control()->get_value()) {
6480 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6482 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6484 if (record_status() == Recording && record_arm_state_changed ) {
6485 RecordArmStateChanged ();
6491 Session::listen_position_changed ()
6493 ProcessorChangeBlocker pcb (this);
6494 boost::shared_ptr<RouteList> r = routes.reader ();
6495 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6496 (*i)->listen_position_changed ();
6501 Session::solo_control_mode_changed ()
6503 if (soloing() || listening()) {
6505 /* We can't use ::clear_all_solo_state() here because during
6506 session loading at program startup, that will queue a call
6507 to rt_clear_all_solo_state() that will not execute until
6508 AFTER solo states have been established (thus throwing away
6509 the session's saved solo state). So just explicitly turn
6512 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6514 clear_all_solo_state (get_routes());
6519 /** Called when a property of one of our route groups changes */
6521 Session::route_group_property_changed (RouteGroup* rg)
6523 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6526 /** Called when a route is added to one of our route groups */
6528 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6530 RouteAddedToRouteGroup (rg, r);
6533 /** Called when a route is removed from one of our route groups */
6535 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6537 update_route_record_state ();
6538 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6540 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6541 remove_route_group (*rg);
6545 boost::shared_ptr<RouteList>
6546 Session::get_tracks () const
6548 boost::shared_ptr<RouteList> rl = routes.reader ();
6549 boost::shared_ptr<RouteList> tl (new RouteList);
6551 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6552 if (boost::dynamic_pointer_cast<Track> (*r)) {
6553 if (!(*r)->is_auditioner()) {
6561 boost::shared_ptr<RouteList>
6562 Session::get_routes_with_regions_at (framepos_t const p) const
6564 boost::shared_ptr<RouteList> r = routes.reader ();
6565 boost::shared_ptr<RouteList> rl (new RouteList);
6567 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6568 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6573 boost::shared_ptr<Playlist> pl = tr->playlist ();
6578 if (pl->has_region_at (p)) {
6587 Session::goto_end ()
6589 if (_session_range_location) {
6590 request_locate (_session_range_location->end(), false);
6592 request_locate (0, false);
6597 Session::goto_start (bool and_roll)
6599 if (_session_range_location) {
6600 request_locate (_session_range_location->start(), and_roll);
6602 request_locate (0, and_roll);
6607 Session::current_start_frame () const
6609 return _session_range_location ? _session_range_location->start() : 0;
6613 Session::current_end_frame () const
6615 return _session_range_location ? _session_range_location->end() : 0;
6619 Session::set_session_range_location (framepos_t start, framepos_t end)
6621 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6622 _locations->add (_session_range_location);
6626 Session::step_edit_status_change (bool yn)
6632 send = (_step_editors == 0);
6637 send = (_step_editors == 1);
6640 if (_step_editors > 0) {
6646 StepEditStatusChange (val);
6652 Session::start_time_changed (framepos_t old)
6654 /* Update the auto loop range to match the session range
6655 (unless the auto loop range has been changed by the user)
6658 Location* s = _locations->session_range_location ();
6663 Location* l = _locations->auto_loop_location ();
6665 if (l && l->start() == old) {
6666 l->set_start (s->start(), true);
6672 Session::end_time_changed (framepos_t old)
6674 /* Update the auto loop range to match the session range
6675 (unless the auto loop range has been changed by the user)
6678 Location* s = _locations->session_range_location ();
6683 Location* l = _locations->auto_loop_location ();
6685 if (l && l->end() == old) {
6686 l->set_end (s->end(), true);
6691 std::vector<std::string>
6692 Session::source_search_path (DataType type) const
6696 if (session_dirs.size() == 1) {
6698 case DataType::AUDIO:
6699 sp.push_back (_session_dir->sound_path());
6701 case DataType::MIDI:
6702 sp.push_back (_session_dir->midi_path());
6706 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6707 SessionDirectory sdir (i->path);
6709 case DataType::AUDIO:
6710 sp.push_back (sdir.sound_path());
6712 case DataType::MIDI:
6713 sp.push_back (sdir.midi_path());
6719 if (type == DataType::AUDIO) {
6720 const string sound_path_2X = _session_dir->sound_path_2X();
6721 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6722 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6723 sp.push_back (sound_path_2X);
6728 // now check the explicit (possibly user-specified) search path
6731 case DataType::AUDIO:
6732 sp += Searchpath(config.get_audio_search_path ());
6734 case DataType::MIDI:
6735 sp += Searchpath(config.get_midi_search_path ());
6743 Session::ensure_search_path_includes (const string& path, DataType type)
6752 case DataType::AUDIO:
6753 sp += Searchpath(config.get_audio_search_path ());
6755 case DataType::MIDI:
6756 sp += Searchpath (config.get_midi_search_path ());
6760 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6761 /* No need to add this new directory if it has the same inode as
6762 an existing one; checking inode rather than name prevents duplicated
6763 directories when we are using symlinks.
6765 On Windows, I think we could just do if (*i == path) here.
6767 if (PBD::equivalent_paths (*i, path)) {
6775 case DataType::AUDIO:
6776 config.set_audio_search_path (sp.to_string());
6778 case DataType::MIDI:
6779 config.set_midi_search_path (sp.to_string());
6785 Session::remove_dir_from_search_path (const string& dir, DataType type)
6790 case DataType::AUDIO:
6791 sp = Searchpath(config.get_audio_search_path ());
6793 case DataType::MIDI:
6794 sp = Searchpath (config.get_midi_search_path ());
6801 case DataType::AUDIO:
6802 config.set_audio_search_path (sp.to_string());
6804 case DataType::MIDI:
6805 config.set_midi_search_path (sp.to_string());
6811 boost::shared_ptr<Speakers>
6812 Session::get_speakers()
6818 Session::unknown_processors () const
6822 boost::shared_ptr<RouteList> r = routes.reader ();
6823 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6824 list<string> t = (*i)->unknown_processors ();
6825 copy (t.begin(), t.end(), back_inserter (p));
6835 Session::update_latency (bool playback)
6838 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6840 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6843 if (!_engine.running()) {
6847 boost::shared_ptr<RouteList> r = routes.reader ();
6848 framecnt_t max_latency = 0;
6851 /* reverse the list so that we work backwards from the last route to run to the first */
6852 RouteList* rl = routes.reader().get();
6853 r.reset (new RouteList (*rl));
6854 reverse (r->begin(), r->end());
6857 /* compute actual latency values for the given direction and store them all in per-port
6858 structures. this will also publish the same values (to JACK) so that computation of latency
6859 for routes can consistently use public latency values.
6862 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6863 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6866 /* because we latency compensate playback, our published playback latencies should
6867 be the same for all output ports - all material played back by ardour has
6868 the same latency, whether its caused by plugins or by latency compensation. since
6869 these may differ from the values computed above, reset all playback port latencies
6873 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6875 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6876 (*i)->set_public_port_latencies (max_latency, playback);
6881 post_playback_latency ();
6885 post_capture_latency ();
6888 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6892 Session::post_playback_latency ()
6894 set_worst_playback_latency ();
6896 boost::shared_ptr<RouteList> r = routes.reader ();
6898 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6899 if (!(*i)->is_auditioner() && ((*i)->active())) {
6900 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6904 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6905 (*i)->set_latency_compensation (_worst_track_latency);
6910 Session::post_capture_latency ()
6912 set_worst_capture_latency ();
6914 /* reflect any changes in capture latencies into capture offsets
6917 boost::shared_ptr<RouteList> rl = routes.reader();
6918 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6919 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6921 tr->set_capture_offset ();
6927 Session::initialize_latencies ()
6930 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6931 update_latency (false);
6932 update_latency (true);
6935 set_worst_io_latencies ();
6939 Session::set_worst_io_latencies ()
6941 set_worst_playback_latency ();
6942 set_worst_capture_latency ();
6946 Session::set_worst_playback_latency ()
6948 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6952 _worst_output_latency = 0;
6954 if (!_engine.connected()) {
6958 boost::shared_ptr<RouteList> r = routes.reader ();
6960 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6961 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6964 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6968 Session::set_worst_capture_latency ()
6970 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6974 _worst_input_latency = 0;
6976 if (!_engine.connected()) {
6980 boost::shared_ptr<RouteList> r = routes.reader ();
6982 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6983 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6986 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6990 Session::update_latency_compensation (bool force_whole_graph)
6992 bool some_track_latency_changed = false;
6994 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6998 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
7000 _worst_track_latency = 0;
7002 boost::shared_ptr<RouteList> r = routes.reader ();
7004 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7005 if (!(*i)->is_auditioner() && ((*i)->active())) {
7007 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
7008 some_track_latency_changed = true;
7010 _worst_track_latency = max (tl, _worst_track_latency);
7014 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
7015 (some_track_latency_changed ? "yes" : "no")));
7017 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
7019 if (some_track_latency_changed || force_whole_graph) {
7020 _engine.update_latencies ();
7024 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7025 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
7029 tr->set_capture_offset ();
7034 Session::session_name_is_legal (const string& path)
7036 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7038 for (int i = 0; illegal_chars[i]; ++i) {
7039 if (path.find (illegal_chars[i]) != string::npos) {
7040 return illegal_chars[i];
7048 Session::notify_presentation_info_change ()
7050 if (deletion_in_progress()) {
7054 reassign_track_numbers();
7056 #ifdef USE_TRACKS_CODE_FEATURES
7057 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7058 * if track order has been changed by user
7060 reconnect_existing_routes(true, true);
7066 Session::operation_in_progress (GQuark op) const
7068 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7071 boost::shared_ptr<Port>
7072 Session::ltc_input_port () const
7074 return _ltc_input->nth (0);
7077 boost::shared_ptr<Port>
7078 Session::ltc_output_port () const
7080 return _ltc_output->nth (0);
7084 Session::reconnect_ltc_input ()
7088 string src = Config->get_ltc_source_port();
7090 _ltc_input->disconnect (this);
7092 if (src != _("None") && !src.empty()) {
7093 _ltc_input->nth (0)->connect (src);
7096 if ( ARDOUR::Profile->get_trx () ) {
7097 // Tracks need this signal to update timecode_source_dropdown
7098 MtcOrLtcInputPortChanged (); //emit signal
7104 Session::reconnect_ltc_output ()
7108 string src = Config->get_ltc_output_port();
7110 _ltc_output->disconnect (this);
7112 if (src != _("None") && !src.empty()) {
7113 _ltc_output->nth (0)->connect (src);
7119 Session::set_range_selection (framepos_t start, framepos_t end)
7121 _range_selection = Evoral::Range<framepos_t> (start, end);
7122 #ifdef USE_TRACKS_CODE_FEATURES
7123 follow_playhead_priority ();
7128 Session::set_object_selection (framepos_t start, framepos_t end)
7130 _object_selection = Evoral::Range<framepos_t> (start, end);
7131 #ifdef USE_TRACKS_CODE_FEATURES
7132 follow_playhead_priority ();
7137 Session::clear_range_selection ()
7139 _range_selection = Evoral::Range<framepos_t> (-1,-1);
7140 #ifdef USE_TRACKS_CODE_FEATURES
7141 follow_playhead_priority ();
7146 Session::clear_object_selection ()
7148 _object_selection = Evoral::Range<framepos_t> (-1,-1);
7149 #ifdef USE_TRACKS_CODE_FEATURES
7150 follow_playhead_priority ();
7155 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7156 const ChanCount& input_start,
7157 const ChanCount& output_start,
7158 const ChanCount& input_offset,
7159 const ChanCount& output_offset)
7161 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7162 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7163 input_start, output_start,
7164 input_offset, output_offset));
7166 auto_connect_thread_wakeup ();
7170 Session::auto_connect_thread_wakeup ()
7172 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7173 pthread_cond_signal (&_auto_connect_cond);
7174 pthread_mutex_unlock (&_auto_connect_mutex);
7179 Session::queue_latency_recompute ()
7181 g_atomic_int_inc (&_latency_recompute_pending);
7182 auto_connect_thread_wakeup ();
7186 Session::auto_connect (const AutoConnectRequest& ar)
7188 boost::shared_ptr<Route> route = ar.route.lock();
7190 if (!route) { return; }
7192 if (!IO::connecting_legal) {
7196 /* If both inputs and outputs are auto-connected to physical ports,
7197 * use the max of input and output offsets to ensure auto-connected
7198 * port numbers always match up (e.g. the first audio input and the
7199 * first audio output of the route will have the same physical
7200 * port number). Otherwise just use the lowest input or output
7204 const bool in_out_physical =
7205 (Config->get_input_auto_connect() & AutoConnectPhysical)
7206 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7207 && ar.connect_inputs;
7209 const ChanCount in_offset = in_out_physical
7210 ? ChanCount::max(ar.input_offset, ar.output_offset)
7213 const ChanCount out_offset = in_out_physical
7214 ? ChanCount::max(ar.input_offset, ar.output_offset)
7217 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7218 vector<string> physinputs;
7219 vector<string> physoutputs;
7222 /* for connecting track inputs we only want MIDI ports marked
7226 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7228 if (!physinputs.empty() && ar.connect_inputs) {
7229 uint32_t nphysical_in = physinputs.size();
7231 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7234 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7235 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7238 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7244 if (!physoutputs.empty()) {
7245 uint32_t nphysical_out = physoutputs.size();
7246 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7250 * do not create new connections if we reached the limit of physical outputs
7253 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7254 ARDOUR::Profile->get_trx () &&
7255 ar.output_offset.get(*t) == nphysical_out ) {
7259 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7260 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7261 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7262 /* master bus is audio only */
7263 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7264 port = _master_out->input()->ports().port(*t,
7265 i % _master_out->input()->n_ports().get(*t))->name();
7269 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7278 Session::auto_connect_thread_start ()
7280 if (g_atomic_int_get (&_ac_thread_active)) {
7284 while (!_auto_connect_queue.empty ()) {
7285 _auto_connect_queue.pop ();
7288 g_atomic_int_set (&_ac_thread_active, 1);
7289 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7290 g_atomic_int_set (&_ac_thread_active, 0);
7295 Session::auto_connect_thread_terminate ()
7297 if (!g_atomic_int_get (&_ac_thread_active)) {
7302 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7303 while (!_auto_connect_queue.empty ()) {
7304 _auto_connect_queue.pop ();
7308 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7309 * fail to wakeup the thread.
7312 pthread_mutex_lock (&_auto_connect_mutex);
7313 g_atomic_int_set (&_ac_thread_active, 0);
7314 pthread_cond_signal (&_auto_connect_cond);
7315 pthread_mutex_unlock (&_auto_connect_mutex);
7318 pthread_join (_auto_connect_thread, &status);
7322 Session::auto_connect_thread (void *arg)
7324 Session *s = static_cast<Session *>(arg);
7325 s->auto_connect_thread_run ();
7331 Session::auto_connect_thread_run ()
7333 pthread_set_name (X_("autoconnect"));
7334 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7335 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7336 pthread_mutex_lock (&_auto_connect_mutex);
7337 while (g_atomic_int_get (&_ac_thread_active)) {
7339 if (!_auto_connect_queue.empty ()) {
7340 // Why would we need the process lock ??
7341 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7342 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7343 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7344 // We have control over those, but what does jack do?
7345 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7347 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7348 while (!_auto_connect_queue.empty ()) {
7349 const AutoConnectRequest ar (_auto_connect_queue.front());
7350 _auto_connect_queue.pop ();
7357 if (!actively_recording ()) { // might not be needed,
7358 /* this is only used for updating plugin latencies, the
7359 * graph does not change. so it's safe in general.
7361 * .. update_latency_compensation () entails set_capture_offset()
7362 * which calls Diskstream::set_capture_offset () which
7363 * modifies the capture offset... which can be a proplem
7364 * in "prepare_to_stop"
7366 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7367 update_latency_compensation ();
7372 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7373 // jack1 cannot cope with removing ports while processing
7374 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7375 AudioEngine::instance()->clear_pending_port_deletions ();
7378 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7380 pthread_mutex_unlock (&_auto_connect_mutex);
7384 Session::cancel_all_solo ()
7388 get_stripables (sl);
7390 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7391 clear_all_solo_state (routes.reader());