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_port.h"
55 #include "ardour/audio_track.h"
56 #include "ardour/audioengine.h"
57 #include "ardour/audiofilesource.h"
58 #include "ardour/auditioner.h"
59 #include "ardour/boost_debug.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/disk_reader.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/rt_tasklist.h"
97 #include "ardour/send.h"
98 #include "ardour/selection.h"
99 #include "ardour/session.h"
100 #include "ardour/session_directory.h"
101 #include "ardour/session_playlists.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/transport_master.h"
109 #include "ardour/track.h"
110 #include "ardour/types_convert.h"
111 #include "ardour/user_bundle.h"
112 #include "ardour/utils.h"
113 #include "ardour/vca_manager.h"
114 #include "ardour/vca.h"
116 #include "midi++/port.h"
117 #include "midi++/mmc.h"
119 #include "LuaBridge/LuaBridge.h"
121 #include "pbd/i18n.h"
123 #include <glibmm/checksum.h>
132 using namespace ARDOUR;
135 bool Session::_disable_all_loaded_plugins = false;
136 bool Session::_bypass_all_loaded_plugins = false;
137 guint Session::_name_id_counter = 0;
139 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
140 PBD::Signal1<void,std::string> Session::Dialog;
141 PBD::Signal0<int> Session::AskAboutPendingState;
142 PBD::Signal2<int, samplecnt_t, samplecnt_t> Session::AskAboutSampleRateMismatch;
143 PBD::Signal2<void, samplecnt_t, samplecnt_t> Session::NotifyAboutSampleRateMismatch;
144 PBD::Signal0<void> Session::SendFeedback;
145 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
147 PBD::Signal1<void, samplepos_t> Session::StartTimeChanged;
148 PBD::Signal1<void, samplepos_t> Session::EndTimeChanged;
149 PBD::Signal2<void,std::string, std::string> Session::Exported;
150 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
151 PBD::Signal0<void> Session::Quit;
152 PBD::Signal0<void> Session::FeedbackDetected;
153 PBD::Signal0<void> Session::SuccessfulGraphSort;
154 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
156 const samplecnt_t Session::bounce_chunk_size = 8192;
157 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
158 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
160 // seconds should be added after the region exceeds end marker
161 #ifdef USE_TRACKS_CODE_FEATURES
162 const uint32_t Session::session_end_shift = 5;
164 const uint32_t Session::session_end_shift = 0;
167 /** @param snapshot_name Snapshot name, without .ardour suffix */
168 Session::Session (AudioEngine &eng,
169 const string& fullpath,
170 const string& snapshot_name,
171 BusProfile* bus_profile,
173 : playlists (new SessionPlaylists)
175 , process_function (&Session::process_with_events)
176 , _bounce_processing_active (false)
177 , waiting_for_sync_offset (false)
178 , _base_sample_rate (0)
179 , _nominal_sample_rate (0)
180 , _current_sample_rate (0)
181 , transport_sub_state (0)
182 , _record_status (Disabled)
183 , _transport_sample (0)
185 , _session_range_location (0)
186 , _session_range_is_free (true)
188 , _remaining_latency_preroll (0)
189 , _engine_speed (1.0)
190 , _transport_speed (0)
191 , _default_transport_speed (1.0)
192 , _last_transport_speed (0)
193 , _signalled_varispeed (0)
194 , _target_transport_speed (0.0)
195 , auto_play_legal (false)
196 , _requested_return_sample (-1)
197 , current_block_size (0)
198 , _worst_output_latency (0)
199 , _worst_input_latency (0)
200 , _worst_route_latency (0)
201 , _send_latency_changes (0)
202 , _have_captured (false)
203 , _non_soloed_outs_muted (false)
206 , _solo_isolated_cnt (0)
208 , _was_seamless (Config->get_seamless_loop ())
209 , _under_nsm_control (false)
211 , transport_master_tracking_state (Stopped)
212 , master_wait_end (0)
213 , post_export_sync (false)
214 , post_export_position (0)
216 , _export_rolling (false)
217 , _realtime_export (false)
218 , _region_export (false)
219 , _export_preroll (0)
220 , _pre_export_mmc_enabled (false)
221 , _name (snapshot_name)
223 , _send_qf_mtc (false)
224 , _pframes_since_last_mtc (0)
226 , loop_changing (false)
228 , _session_dir (new SessionDirectory (fullpath))
229 , _current_snapshot_name (snapshot_name)
231 , state_was_pending (false)
232 , _state_of_the_state (StateOfTheState (CannotSave | InitialConnecting | Loading))
234 , _save_queued (false)
235 , _last_roll_location (0)
236 , _last_roll_or_reversal_location (0)
237 , _last_record_location (0)
238 , pending_auto_loop (false)
239 , _mempool ("Session", 3145728)
240 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
242 , _butler (new Butler (*this))
243 , _post_transport_work (0)
244 , _locations (new Locations (*this))
245 , _ignore_skips_updates (false)
246 , _rt_thread_active (false)
247 , _rt_emit_pending (false)
248 , _ac_thread_active (0)
249 , _latency_recompute_pending (0)
251 , outbound_mtc_timecode_frame (0)
252 , next_quarter_frame_to_send (-1)
253 , _samples_per_timecode_frame (0)
254 , _frames_per_hour (0)
255 , _timecode_frames_per_hour (0)
256 , last_timecode_valid (false)
257 , last_timecode_when (0)
258 , _send_timecode_update (false)
270 , ltc_timecode_offset (0)
271 , ltc_timecode_negative_offset (false)
272 , midi_control_ui (0)
274 , _all_route_group (new RouteGroup (*this, "all"))
275 , routes (new RouteList)
276 , _adding_routes_in_progress (false)
277 , _reconnecting_routes_in_progress (false)
278 , _route_deletion_in_progress (false)
279 , destructive_index (0)
280 , _track_number_decimals(1)
281 , default_fade_steepness (0)
282 , default_fade_msecs (0)
283 , _total_free_4k_blocks (0)
284 , _total_free_4k_blocks_uncertain (false)
285 , no_questions_about_missing_files (false)
288 , _bundles (new BundleList)
289 , _bundle_xml_node (0)
292 , _click_rec_only (false)
294 , click_emphasis_data (0)
296 , click_emphasis_length (0)
297 , _clicks_cleared (0)
298 , _count_in_samples (0)
299 , _play_range (false)
300 , _range_selection (-1,-1)
301 , _object_selection (-1,-1)
302 , _preroll_record_trim_len (0)
303 , _count_in_once (false)
305 , first_file_data_format_reset (true)
306 , first_file_header_format_reset (true)
307 , have_looped (false)
308 , _have_rec_enabled_track (false)
309 , _have_rec_disabled_track (true)
311 , _suspend_timecode_transmission (0)
312 , _speakers (new Speakers)
313 , _ignore_route_processor_changes (0)
318 , _vca_manager (new VCAManager (*this))
319 , _selection (new CoreSelection (*this))
320 , _global_locate_pending (false)
324 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
326 pthread_mutex_init (&_rt_emit_mutex, 0);
327 pthread_cond_init (&_rt_emit_cond, 0);
329 pthread_mutex_init (&_auto_connect_mutex, 0);
330 pthread_cond_init (&_auto_connect_cond, 0);
332 init_name_id_counter (1); // reset for new sessions, start at 1
333 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
335 pre_engine_init (fullpath); // sets _is_new
341 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
343 #ifdef USE_TRACKS_CODE_FEATURES
344 sr = EngineStateController::instance()->get_current_sample_rate();
346 if (ensure_engine (sr, true)) {
348 throw SessionException (_("Cannot connect to audio/midi engine"));
351 // set samplerate for plugins added early
352 // e.g from templates or MB channelstrip
353 set_block_size (_engine.samples_per_cycle());
354 set_sample_rate (_engine.sample_rate());
356 if (create (mix_template, bus_profile)) {
358 throw SessionException (_("Session initialization failed"));
361 /* if a mix template was provided, then ::create() will
362 * have copied it into the session and we need to load it
363 * so that we have the state ready for ::set_state()
364 * after the engine is started.
366 * Note that we do NOT try to get the sample rate from
367 * the template at this time, though doing so would
368 * be easy if we decided this was an appropriate part
372 if (!mix_template.empty()) {
374 if (load_state (_current_snapshot_name)) {
375 throw SessionException (_("Failed to load template/snapshot state"));
377 } catch (PBD::unknown_enumeration& e) {
378 throw SessionException (_("Failed to parse template/snapshot state"));
380 store_recent_templates (mix_template);
383 /* load default session properties - if any */
388 if (load_state (_current_snapshot_name)) {
389 throw SessionException (_("Failed to load state"));
392 /* try to get sample rate from XML state so that we
393 * can influence the SR if we set up the audio
398 XMLProperty const * prop;
399 XMLNode const * root (state_tree->root());
400 if ((prop = root->property (X_("sample-rate"))) != 0) {
401 sr = atoi (prop->value());
405 if (ensure_engine (sr, false)) {
407 throw SessionException (_("Cannot connect to audio/midi engine"));
411 int err = post_engine_init ();
416 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
420 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
423 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
426 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
429 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")));
434 store_recent_sessions (_name, _path);
436 bool was_dirty = dirty();
439 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
441 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
442 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
445 DirtyChanged (); /* EMIT SIGNAL */
448 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
449 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
451 Send::ChangedLatency.connect_same_thread (*this, boost::bind (&Session::send_latency_compensation_change, this));
453 emit_thread_start ();
454 auto_connect_thread_start ();
456 /* hook us up to the engine since we are now completely constructed */
458 BootMessage (_("Connect to engine"));
460 _engine.set_session (this);
461 _engine.reset_timebase ();
463 #ifdef USE_TRACKS_CODE_FEATURES
465 EngineStateController::instance()->set_session(this);
468 if ( ARDOUR::Profile->get_trx () ) {
470 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
471 * each available input must have corresponding track when session starts.
474 uint32_t how_many (0);
476 std::vector<std::string> inputs;
477 EngineStateController::instance()->get_physical_audio_inputs(inputs);
479 how_many = inputs.size();
481 list<boost::shared_ptr<AudioTrack> > tracks;
483 // Track names after driver
484 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
485 string track_name = "";
486 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
488 track_name = inputs[i];
489 replace_all (track_name, "system:capture", "");
491 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
492 tracks.insert(tracks.begin(), single_track.front());
494 } else { // Default track names
495 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
498 if (tracks.size() != how_many) {
500 throw failed_constructor ();
506 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
508 if (!mix_template.empty ()) {
509 /* ::create() unsets _is_new after creating the session.
510 * But for templated sessions, the sample-rate is initially unset
511 * (not read from template), so we need to save it (again).
519 BootMessage (_("Session loading complete"));
531 Session::next_name_id ()
533 return g_atomic_int_add (&_name_id_counter, 1);
537 Session::name_id_counter ()
539 return g_atomic_int_get (&_name_id_counter);
543 Session::init_name_id_counter (guint n)
545 g_atomic_int_set (&_name_id_counter, n);
549 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
551 if (_engine.current_backend() == 0) {
552 /* backend is unknown ... */
553 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
554 if (r.get_value_or (-1) != 0) {
557 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
559 } else if (_engine.setup_required()) {
560 /* backend is known, but setup is needed */
561 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
562 if (r.get_value_or (-1) != 0) {
565 } else if (!_engine.running()) {
566 if (_engine.start()) {
571 /* at this point the engine should be running */
573 if (!_engine.running()) {
577 return immediately_post_engine ();
582 Session::immediately_post_engine ()
584 /* Do various initializations that should take place directly after we
585 * know that the engine is running, but before we either create a
586 * session or set state for an existing one.
589 _rt_tasklist.reset (new RTTaskList ());
591 if (how_many_dsp_threads () > 1) {
592 /* For now, only create the graph if we are using >1 DSP threads, as
593 it is a bit slower than the old code with 1 thread.
595 _process_graph.reset (new Graph (*this));
598 /* every time we reconnect, recompute worst case output latencies */
600 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
602 if (synced_to_engine()) {
603 _engine.transport_stop ();
606 if (config.get_jack_time_master()) {
607 _engine.transport_locate (_transport_sample);
611 BootMessage (_("Set up LTC"));
613 BootMessage (_("Set up Click"));
615 BootMessage (_("Set up standard connections"));
619 catch (failed_constructor& err) {
623 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
625 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
633 vector<void*> debug_pointers;
635 /* if we got to here, leaving pending capture state around
639 remove_pending_capture_state ();
643 _state_of_the_state = StateOfTheState (CannotSave | Deletion);
646 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
650 /* disconnect from any and all signals that we are connected to */
652 Port::PortSignalDrop (); /* EMIT SIGNAL */
655 /* shutdown control surface protocols while we still have ports
656 * and the engine to move data to any devices.
659 /* remove I/O objects before unsetting the engine session */
661 _ltc_output.reset ();
663 ControlProtocolManager::instance().drop_protocols ();
665 /* stop auto dis/connecting */
666 auto_connect_thread_terminate ();
668 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
670 _engine.remove_session ();
672 #ifdef USE_TRACKS_CODE_FEATURES
673 EngineStateController::instance()->remove_session();
676 /* deregister all ports - there will be no process or any other
677 * callbacks from the engine any more.
680 Port::PortDrop (); /* EMIT SIGNAL */
682 /* clear history so that no references to objects are held any more */
686 /* clear state tree so that no references to objects are held any more */
692 /* unregister all lua functions, drop held references (if any) */
693 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
695 lua.do_command ("Session = nil");
703 lua.collect_garbage ();
706 /* reset dynamic state version back to default */
707 Stateful::loading_state_version = 0;
709 _butler->drop_references ();
713 delete _all_route_group;
715 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
716 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
720 if (click_data != default_click) {
721 delete [] click_data;
724 if (click_emphasis_data != default_click_emphasis) {
725 delete [] click_emphasis_data;
730 /* need to remove auditioner before monitoring section
731 * otherwise it is re-connected.
732 * Note: If a session was never successfully loaded, there
733 * may not yet be an auditioner.
736 auditioner->drop_references ();
740 /* drop references to routes held by the monitoring section
741 * specifically _monitor_out aux/listen references */
742 remove_monitor_section();
744 /* clear out any pending dead wood from RCU managed objects */
749 DiskReader::free_working_buffers();
751 /* tell everyone who is still standing that we're about to die */
754 /* tell everyone to drop references and delete objects as we go */
756 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
757 RegionFactory::delete_all_regions ();
759 /* Do this early so that VCAs no longer hold references to routes */
761 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
764 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
766 /* reset these three references to special routes before we do the usual route delete thing */
768 _master_out.reset ();
769 _monitor_out.reset ();
772 RCUWriter<RouteList> writer (routes);
773 boost::shared_ptr<RouteList> r = writer.get_copy ();
775 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
776 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
777 (*i)->drop_references ();
781 /* writer goes out of scope and updates master */
786 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
787 Glib::Threads::Mutex::Lock lm (source_lock);
788 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
789 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
790 i->second->drop_references ();
796 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
799 emit_thread_terminate ();
801 pthread_cond_destroy (&_rt_emit_cond);
802 pthread_mutex_destroy (&_rt_emit_mutex);
804 pthread_cond_destroy (&_auto_connect_cond);
805 pthread_mutex_destroy (&_auto_connect_mutex);
807 delete _scene_changer; _scene_changer = 0;
808 delete midi_control_ui; midi_control_ui = 0;
810 delete _mmc; _mmc = 0;
811 delete _midi_ports; _midi_ports = 0;
812 delete _locations; _locations = 0;
817 /* clear event queue, the session is gone, nobody is interested in
818 * those anymore, but they do leak memory if not removed
820 while (!immediate_events.empty ()) {
821 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
822 SessionEvent *ev = immediate_events.front ();
823 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
824 immediate_events.pop_front ();
828 case SessionEvent::AutoLoop:
829 case SessionEvent::Skip:
830 case SessionEvent::PunchIn:
831 case SessionEvent::PunchOut:
832 case SessionEvent::StopOnce:
833 case SessionEvent::RangeStop:
834 case SessionEvent::RangeLocate:
838 case SessionEvent::RealTimeOperation:
845 del = del && !_remove_event (ev);
853 /* unregister all dropped ports, process pending port deletion. */
854 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
855 // jack1 cannot cope with removing ports while processing
856 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
857 AudioEngine::instance()->clear_pending_port_deletions ();
860 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
864 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
866 BOOST_SHOW_POINTERS ();
870 Session::setup_ltc ()
874 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
876 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
877 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
880 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
881 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
882 // TODO use auto-connect thread
883 reconnect_ltc_output ();
887 /* fix up names of LTC ports because we don't want the normal
888 * IO style of NAME/TYPE-{in,out}N
891 _ltc_output->nth (0)->set_name (X_("LTC-out"));
895 Session::setup_click ()
899 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
900 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
902 _click_io.reset (new ClickIO (*this, X_("Click")));
903 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
904 _click_gain->activate ();
906 setup_click_state (state_tree->root());
908 setup_click_state (0);
913 Session::setup_click_state (const XMLNode* node)
915 const XMLNode* child = 0;
917 if (node && (child = find_named_node (*node, "Click")) != 0) {
919 /* existing state for Click */
922 if (Stateful::loading_state_version < 3000) {
923 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
925 const XMLNodeList& children (child->children());
926 XMLNodeList::const_iterator i = children.begin();
927 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
929 if (i != children.end()) {
930 c = _click_gain->set_state (**i, Stateful::loading_state_version);
936 _clicking = Config->get_clicking ();
940 error << _("could not setup Click I/O") << endmsg;
947 /* default state for Click: dual-mono to first 2 physical outputs */
950 _engine.get_physical_outputs (DataType::AUDIO, outs);
952 for (uint32_t physport = 0; physport < 2; ++physport) {
953 if (outs.size() > physport) {
954 if (_click_io->add_port (outs[physport], this)) {
955 // relax, even though its an error
960 if (_click_io->n_ports () > ChanCount::ZERO) {
961 _clicking = Config->get_clicking ();
967 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
968 MidiPortFlags include, MidiPortFlags exclude)
970 _engine.get_physical_inputs (type, inputs, include, exclude);
971 _engine.get_physical_outputs (type, outputs, include, exclude);
975 Session::setup_bundles ()
979 RCUWriter<BundleList> writer (_bundles);
980 boost::shared_ptr<BundleList> b = writer.get_copy ();
981 for (BundleList::iterator i = b->begin(); i != b->end();) {
982 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
990 vector<string> inputs[DataType::num_types];
991 vector<string> outputs[DataType::num_types];
993 for (uint32_t i = 0; i < DataType::num_types; ++i) {
994 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
995 MidiPortFlags (0), /* no specific inclusions */
996 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1000 /* Create a set of Bundle objects that map
1001 to the physical I/O currently available. We create both
1002 mono and stereo bundles, so that the common cases of mono
1003 and stereo tracks get bundles to put in their mixer strip
1004 in / out menus. There may be a nicer way of achieving that;
1005 it doesn't really scale that well to higher channel counts
1008 /* mono output bundles */
1010 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1012 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1014 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1016 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1019 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1020 c->add_channel (_("mono"), DataType::AUDIO);
1021 c->set_port (0, outputs[DataType::AUDIO][np]);
1023 add_bundle (c, false);
1026 /* stereo output bundles */
1028 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1029 if (np + 1 < outputs[DataType::AUDIO].size()) {
1031 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1032 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1033 c->add_channel (_("L"), DataType::AUDIO);
1034 c->set_port (0, outputs[DataType::AUDIO][np]);
1035 c->add_channel (_("R"), DataType::AUDIO);
1036 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1038 add_bundle (c, false);
1042 /* mono input bundles */
1044 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1046 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1048 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1050 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1053 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1054 c->add_channel (_("mono"), DataType::AUDIO);
1055 c->set_port (0, inputs[DataType::AUDIO][np]);
1057 add_bundle (c, false);
1060 /* stereo input bundles */
1062 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1063 if (np + 1 < inputs[DataType::AUDIO].size()) {
1065 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1067 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1068 c->add_channel (_("L"), DataType::AUDIO);
1069 c->set_port (0, inputs[DataType::AUDIO][np]);
1070 c->add_channel (_("R"), DataType::AUDIO);
1071 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1073 add_bundle (c, false);
1077 /* MIDI input bundles */
1079 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1080 string n = inputs[DataType::MIDI][np];
1082 std::string pn = _engine.get_pretty_name_by_name (n);
1086 boost::erase_first (n, X_("alsa_pcm:"));
1088 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1089 c->add_channel ("", DataType::MIDI);
1090 c->set_port (0, inputs[DataType::MIDI][np]);
1091 add_bundle (c, false);
1094 /* MIDI output bundles */
1096 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1097 string n = outputs[DataType::MIDI][np];
1098 std::string pn = _engine.get_pretty_name_by_name (n);
1102 boost::erase_first (n, X_("alsa_pcm:"));
1104 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1105 c->add_channel ("", DataType::MIDI);
1106 c->set_port (0, outputs[DataType::MIDI][np]);
1107 add_bundle (c, false);
1110 // we trust the backend to only calls us if there's a change
1111 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1115 Session::auto_connect_master_bus ()
1117 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1121 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1122 // In this case it means "Multi Out" output mode
1123 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1127 /* if requested auto-connect the outputs to the first N physical ports.
1130 uint32_t limit = _master_out->n_outputs().n_total();
1131 vector<string> outputs[DataType::num_types];
1133 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1134 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1137 for (uint32_t n = 0; n < limit; ++n) {
1138 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1140 if (outputs[p->type()].size() > n) {
1141 connect_to = outputs[p->type()][n];
1144 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1145 if (_master_out->output()->connect (p, connect_to, this)) {
1146 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1155 Session::remove_monitor_section ()
1157 if (!_monitor_out || Profile->get_trx()) {
1161 /* allow deletion when session is unloaded */
1162 if (!_engine.running() && !deletion_in_progress ()) {
1163 error << _("Cannot remove monitor section while the engine is offline.") << endmsg;
1167 /* force reversion to Solo-In-Place */
1168 Config->set_solo_control_is_listen_control (false);
1170 /* if we are auditioning, cancel it ... this is a workaround
1171 to a problem (auditioning does not execute the process graph,
1172 which is needed to remove routes when using >1 core for processing)
1176 if (!deletion_in_progress ()) {
1177 /* Hold process lock while doing this so that we don't hear bits and
1178 * pieces of audio as we work on each route.
1181 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1183 /* Connect tracks to monitor section. Note that in an
1184 existing session, the internal sends will already exist, but we want the
1185 routes to notice that they connect to the control out specifically.
1189 boost::shared_ptr<RouteList> r = routes.reader ();
1190 ProcessorChangeBlocker pcb (this, false);
1192 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1194 if ((*x)->is_monitor()) {
1196 } else if ((*x)->is_master()) {
1199 (*x)->remove_aux_or_listen (_monitor_out);
1204 remove_route (_monitor_out);
1205 if (deletion_in_progress ()) {
1209 auto_connect_master_bus ();
1212 auditioner->connect ();
1215 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1219 Session::add_monitor_section ()
1223 if (!_engine.running()) {
1224 error << _("Cannot create monitor section while the engine is offline.") << endmsg;
1228 if (_monitor_out || !_master_out || Profile->get_trx()) {
1232 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1238 BOOST_MARK_ROUTE(r);
1241 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1242 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1243 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1245 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1250 add_routes (rl, false, false, false, 0);
1252 assert (_monitor_out);
1254 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1255 are undefined, at best.
1258 uint32_t limit = _monitor_out->n_inputs().n_audio();
1262 /* connect the inputs to the master bus outputs. this
1263 * represents a separate data feed from the internal sends from
1264 * each route. as of jan 2011, it allows the monitor section to
1265 * conditionally ignore either the internal sends or the normal
1266 * input feed, but we should really find a better way to do
1270 _master_out->output()->disconnect (this);
1272 for (uint32_t n = 0; n < limit; ++n) {
1273 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1274 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1277 string connect_to = o->name();
1278 if (_monitor_out->input()->connect (p, connect_to, this)) {
1279 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1287 /* if monitor section is not connected, connect it to physical outs
1290 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1292 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1294 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1297 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1299 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1300 Config->get_monitor_bus_preferred_bundle())
1306 /* Monitor bus is audio only */
1308 vector<string> outputs[DataType::num_types];
1310 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1311 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1314 uint32_t mod = outputs[DataType::AUDIO].size();
1315 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1319 for (uint32_t n = 0; n < limit; ++n) {
1321 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1323 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1324 connect_to = outputs[DataType::AUDIO][n % mod];
1327 if (!connect_to.empty()) {
1328 if (_monitor_out->output()->connect (p, connect_to, this)) {
1329 error << string_compose (
1330 _("cannot connect control output %1 to %2"),
1341 /* Hold process lock while doing this so that we don't hear bits and
1342 * pieces of audio as we work on each route.
1345 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1347 /* Connect tracks to monitor section. Note that in an
1348 existing session, the internal sends will already exist, but we want the
1349 routes to notice that they connect to the control out specifically.
1353 boost::shared_ptr<RouteList> rls = routes.reader ();
1355 ProcessorChangeBlocker pcb (this, false /* XXX */);
1357 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1359 if ((*x)->is_monitor()) {
1361 } else if ((*x)->is_master()) {
1364 (*x)->enable_monitor_send ();
1369 auditioner->connect ();
1372 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1376 Session::reset_monitor_section ()
1378 /* Process lock should be held by the caller.*/
1380 if (!_monitor_out || Profile->get_trx()) {
1384 uint32_t limit = _master_out->n_outputs().n_audio();
1386 /* connect the inputs to the master bus outputs. this
1387 * represents a separate data feed from the internal sends from
1388 * each route. as of jan 2011, it allows the monitor section to
1389 * conditionally ignore either the internal sends or the normal
1390 * input feed, but we should really find a better way to do
1394 _master_out->output()->disconnect (this);
1395 _monitor_out->output()->disconnect (this);
1397 // monitor section follow master bus - except midi
1398 ChanCount mon_chn (_master_out->output()->n_ports());
1399 mon_chn.set_midi (0);
1401 _monitor_out->input()->ensure_io (mon_chn, false, this);
1402 _monitor_out->output()->ensure_io (mon_chn, false, this);
1404 for (uint32_t n = 0; n < limit; ++n) {
1405 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1406 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1409 string connect_to = o->name();
1410 if (_monitor_out->input()->connect (p, connect_to, this)) {
1411 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1418 /* connect monitor section to physical outs
1421 if (Config->get_auto_connect_standard_busses()) {
1423 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1425 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1428 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1430 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1431 Config->get_monitor_bus_preferred_bundle())
1437 /* Monitor bus is audio only */
1439 vector<string> outputs[DataType::num_types];
1441 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1442 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1445 uint32_t mod = outputs[DataType::AUDIO].size();
1446 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1450 for (uint32_t n = 0; n < limit; ++n) {
1452 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1454 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1455 connect_to = outputs[DataType::AUDIO][n % mod];
1458 if (!connect_to.empty()) {
1459 if (_monitor_out->output()->connect (p, connect_to, this)) {
1460 error << string_compose (
1461 _("cannot connect control output %1 to %2"),
1472 /* Connect tracks to monitor section. Note that in an
1473 existing session, the internal sends will already exist, but we want the
1474 routes to notice that they connect to the control out specifically.
1478 boost::shared_ptr<RouteList> rls = routes.reader ();
1480 ProcessorChangeBlocker pcb (this, false);
1482 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1484 if ((*x)->is_monitor()) {
1486 } else if ((*x)->is_master()) {
1489 (*x)->enable_monitor_send ();
1495 Session::add_master_bus (ChanCount const& count)
1497 if (master_out ()) {
1503 boost::shared_ptr<Route> r (new Route (*this, _("Master"), PresentationInfo::MasterOut, DataType::AUDIO));
1508 BOOST_MARK_ROUTE(r);
1511 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1512 r->input()->ensure_io (count, false, this);
1513 r->output()->ensure_io (count, false, this);
1517 add_routes (rl, false, false, false, PresentationInfo::max_order);
1522 Session::hookup_io ()
1524 /* stop graph reordering notifications from
1525 causing resorts, etc.
1528 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1532 /* we delay creating the auditioner till now because
1533 it makes its own connections to ports.
1537 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1539 throw failed_constructor ();
1544 catch (failed_constructor& err) {
1545 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1549 /* load bundles, which we may have postponed earlier on */
1550 if (_bundle_xml_node) {
1551 load_bundles (*_bundle_xml_node);
1552 delete _bundle_xml_node;
1555 /* Tell all IO objects to connect themselves together */
1557 IO::enable_connecting ();
1559 /* Now tell all "floating" ports to connect to whatever
1560 they should be connected to.
1563 AudioEngine::instance()->reconnect_ports ();
1565 /* Anyone who cares about input state, wake up and do something */
1567 IOConnectionsComplete (); /* EMIT SIGNAL */
1569 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1571 /* now handle the whole enchilada as if it was one
1572 graph reorder event.
1577 /* update the full solo state, which can't be
1578 correctly determined on a per-route basis, but
1579 needs the global overview that only the session
1583 update_route_solo_state ();
1587 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1589 boost::shared_ptr<Track> track = wp.lock ();
1594 boost::shared_ptr<Playlist> playlist;
1596 if ((playlist = track->playlist()) != 0) {
1597 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1598 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1599 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1604 Session::record_enabling_legal () const
1606 /* this used to be in here, but survey says.... we don't need to restrict it */
1607 // if (record_status() == Recording) {
1611 if (Config->get_all_safe()) {
1618 Session::set_track_monitor_input_status (bool yn)
1620 boost::shared_ptr<RouteList> rl = routes.reader ();
1621 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1622 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1623 if (tr && tr->rec_enable_control()->get_value()) {
1624 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1625 tr->request_input_monitoring (yn);
1631 Session::auto_punch_start_changed (Location* location)
1633 replace_event (SessionEvent::PunchIn, location->start());
1635 if (get_record_enabled() && config.get_punch_in() && !actively_recording ()) {
1636 /* capture start has been changed, so save new pending state */
1637 save_state ("", true);
1642 Session::auto_punch_end_changed (Location* location)
1644 replace_event (SessionEvent::PunchOut, location->end());
1648 Session::auto_punch_changed (Location* location)
1650 auto_punch_start_changed (location);
1651 auto_punch_end_changed (location);
1654 /** @param loc A loop location.
1655 * @param pos Filled in with the start time of the required fade-out (in session samples).
1656 * @param length Filled in with the length of the required fade-out.
1659 Session::auto_loop_declick_range (Location* loc, samplepos_t & pos, samplepos_t & length)
1661 pos = max (loc->start(), loc->end() - 64);
1662 length = loc->end() - pos;
1666 Session::auto_loop_changed (Location* location)
1668 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1671 auto_loop_declick_range (location, dcp, dcl);
1673 bool rolling = transport_rolling ();
1675 if (rolling && play_loop) {
1677 if (_transport_sample < location->start() || _transport_sample > location->end()) {
1678 // relocate to beginning of loop
1679 clear_events (SessionEvent::LocateRoll);
1680 request_locate (location->start(), true);
1684 clear_events (SessionEvent::AutoLoop);
1687 /* possibly move playhead if not rolling; if we are rolling we'll move
1688 to the loop start on stop if that is appropriate.
1693 if (!rolling && select_playhead_priority_target (pos)) {
1694 if (pos == location->start()) {
1695 request_locate (pos);
1699 last_loopend = location->end();
1704 Session::set_auto_punch_location (Location* location)
1708 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1709 punch_connections.drop_connections();
1710 existing->set_auto_punch (false, this);
1711 clear_events (SessionEvent::PunchIn);
1712 clear_events (SessionEvent::PunchOut);
1713 auto_punch_location_changed (0);
1718 if (location == 0) {
1722 if (location->end() <= location->start()) {
1723 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1727 punch_connections.drop_connections ();
1729 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1730 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1731 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1733 location->set_auto_punch (true, this);
1735 auto_punch_changed (location);
1737 auto_punch_location_changed (location);
1741 Session::set_session_extents (samplepos_t start, samplepos_t end)
1744 if ((existing = _locations->session_range_location()) == 0) {
1745 //if there is no existing session, we need to make a new session location (should never happen)
1746 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1750 error << _("Session: you can't use that location for session start/end)") << endmsg;
1754 existing->set( start, end );
1760 Session::set_auto_loop_location (Location* location)
1764 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1765 loop_connections.drop_connections ();
1766 existing->set_auto_loop (false, this);
1767 remove_event (existing->end(), SessionEvent::AutoLoop);
1770 auto_loop_declick_range (existing, dcp, dcl);
1771 auto_loop_location_changed (0);
1776 if (location == 0) {
1780 if (location->end() <= location->start()) {
1781 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1785 last_loopend = location->end();
1787 loop_connections.drop_connections ();
1789 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1790 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1791 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1792 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1794 location->set_auto_loop (true, this);
1796 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1797 // set all tracks to use internal looping
1798 boost::shared_ptr<RouteList> rl = routes.reader ();
1799 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1800 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1801 if (tr && !tr->is_private_route()) {
1802 tr->set_loop (location);
1807 /* take care of our stuff first */
1809 auto_loop_changed (location);
1811 /* now tell everyone else */
1813 auto_loop_location_changed (location);
1817 Session::update_marks (Location*)
1823 Session::update_skips (Location* loc, bool consolidate)
1825 if (_ignore_skips_updates) {
1829 Locations::LocationList skips;
1832 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1833 consolidate_skips (loc);
1836 sync_locations_to_skips ();
1842 Session::consolidate_skips (Location* loc)
1844 Locations::LocationList all_locations = _locations->list ();
1846 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1848 if (!(*l)->is_skip ()) {
1853 /* don't test against self */
1860 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1861 case Evoral::OverlapInternal:
1862 case Evoral::OverlapExternal:
1863 case Evoral::OverlapStart:
1864 case Evoral::OverlapEnd:
1865 /* adjust new location to cover existing one */
1866 loc->set_start (min (loc->start(), (*l)->start()));
1867 loc->set_end (max (loc->end(), (*l)->end()));
1868 /* we don't need this one any more */
1869 _locations->remove (*l);
1870 /* the location has been deleted, so remove reference to it in our local list */
1871 l = all_locations.erase (l);
1874 case Evoral::OverlapNone:
1882 Session::sync_locations_to_skips ()
1884 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1885 * Session::_sync_locations_to_skips() from the audioengine thread.
1887 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1891 Session::_sync_locations_to_skips ()
1893 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1895 Locations::LocationList const & locs (_locations->list());
1897 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1899 Location* location = *i;
1901 if (location->is_skip() && location->is_skipping()) {
1902 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1910 Session::location_added (Location *location)
1912 if (location->is_auto_punch()) {
1913 set_auto_punch_location (location);
1916 if (location->is_auto_loop()) {
1917 set_auto_loop_location (location);
1920 if (location->is_session_range()) {
1921 /* no need for any signal handling or event setting with the session range,
1922 because we keep a direct reference to it and use its start/end directly.
1924 _session_range_location = location;
1927 if (location->is_mark()) {
1928 /* listen for per-location signals that require us to do any * global updates for marks */
1930 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1931 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1932 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1933 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1934 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1937 if (location->is_range_marker()) {
1938 /* listen for per-location signals that require us to do any * global updates for marks */
1940 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1941 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1942 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1943 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1944 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1947 if (location->is_skip()) {
1948 /* listen for per-location signals that require us to update skip-locate events */
1950 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1951 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1952 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1953 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1954 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1956 update_skips (location, true);
1963 Session::location_removed (Location *location)
1965 if (location->is_auto_loop()) {
1966 set_auto_loop_location (0);
1968 set_track_loop (false);
1973 if (location->is_auto_punch()) {
1974 set_auto_punch_location (0);
1977 if (location->is_session_range()) {
1978 /* this is never supposed to happen */
1979 error << _("programming error: session range removed!") << endl;
1982 if (location->is_skip()) {
1984 update_skips (location, false);
1991 Session::locations_changed ()
1993 _locations->apply (*this, &Session::_locations_changed);
1997 Session::_locations_changed (const Locations::LocationList& locations)
1999 /* There was some mass-change in the Locations object.
2001 We might be re-adding a location here but it doesn't actually matter
2002 for all the locations that the Session takes an interest in.
2006 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
2007 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
2008 location_added (*i);
2012 update_skips (NULL, false);
2016 Session::enable_record ()
2018 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2019 /* no recording at anything except normal speed */
2024 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2026 if (rs == Recording) {
2030 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2032 _last_record_location = _transport_sample;
2033 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2035 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2036 set_track_monitor_input_status (true);
2039 RecordStateChanged ();
2046 Session::set_all_tracks_record_enabled (bool enable )
2048 boost::shared_ptr<RouteList> rl = routes.reader();
2049 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2053 Session::disable_record (bool rt_context, bool force)
2057 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2059 if (!Config->get_latched_record_enable () || force) {
2060 g_atomic_int_set (&_record_status, Disabled);
2061 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2063 if (rs == Recording) {
2064 g_atomic_int_set (&_record_status, Enabled);
2068 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2069 set_track_monitor_input_status (false);
2072 RecordStateChanged (); /* emit signal */
2075 remove_pending_capture_state ();
2081 Session::step_back_from_record ()
2083 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2085 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2086 set_track_monitor_input_status (false);
2089 RecordStateChanged (); /* emit signal */
2094 Session::maybe_enable_record (bool rt_context)
2096 if (_step_editors > 0) {
2100 g_atomic_int_set (&_record_status, Enabled);
2102 /* This function is currently called from somewhere other than an RT thread.
2103 * (except maybe lua scripts, which can use rt_context = true)
2104 * This save_state() call therefore doesn't impact anything. Doing it here
2105 * means that we save pending state of which sources the next record will use,
2106 * which gives us some chance of recovering from a crash during the record.
2110 save_state ("", true);
2113 if (_transport_speed) {
2114 if (!config.get_punch_in()) {
2118 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2119 RecordStateChanged (); /* EMIT SIGNAL */
2126 Session::audible_sample (bool* latent_locate) const
2128 if (latent_locate) {
2129 *latent_locate = false;
2134 if (synced_to_engine()) {
2135 /* Note: this is basically just sync-to-JACK */
2136 ret = _engine.transport_sample();
2138 ret = _transport_sample;
2143 if (!transport_rolling()) {
2147 #if 0 // TODO looping
2148 if (_transport_speed > 0.0f) {
2149 if (play_loop && have_looped) {
2150 /* the play-position wrapped at the loop-point
2151 * ardour is already playing the beginning of the loop,
2152 * but due to playback latency, the "audible frame"
2153 * is still at the end of the loop.
2155 Location *location = _locations->auto_loop_location();
2156 sampleoffset_t lo = location->start() - ret;
2158 ret = location->end () - lo;
2159 if (latent_locate) {
2160 *latent_locate = true;
2164 } else if (_transport_speed < 0.0f) {
2165 /* XXX wot? no backward looping? */
2169 return std::max ((samplepos_t)0, ret);
2173 Session::preroll_samples (samplepos_t pos) const
2175 const float pr = Config->get_preroll_seconds();
2176 if (pos >= 0 && pr < 0) {
2177 const Tempo& tempo = _tempo_map->tempo_at_sample (pos);
2178 const Meter& meter = _tempo_map->meter_at_sample (pos);
2179 return meter.samples_per_bar (tempo, sample_rate()) * -pr;
2184 return pr * sample_rate();
2188 Session::set_sample_rate (samplecnt_t frames_per_second)
2190 /** \fn void Session::set_sample_size(samplecnt_t)
2191 the AudioEngine object that calls this guarantees
2192 that it will not be called while we are also in
2193 ::process(). Its fine to do things that block
2197 if (_base_sample_rate == 0) {
2198 _base_sample_rate = frames_per_second;
2200 else if (_base_sample_rate != frames_per_second && frames_per_second != _nominal_sample_rate) {
2201 NotifyAboutSampleRateMismatch (_base_sample_rate, frames_per_second);
2203 _nominal_sample_rate = frames_per_second;
2208 reset_write_sources (false);
2210 // XXX we need some equivalent to this, somehow
2211 // SndFileSource::setup_standard_crossfades (frames_per_second);
2215 /* XXX need to reset/reinstantiate all LADSPA plugins */
2219 Session::set_block_size (pframes_t nframes)
2221 /* the AudioEngine guarantees
2222 that it will not be called while we are also in
2223 ::process(). It is therefore fine to do things that block
2228 current_block_size = nframes;
2232 boost::shared_ptr<RouteList> r = routes.reader ();
2234 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2235 (*i)->set_block_size (nframes);
2238 boost::shared_ptr<RouteList> rl = routes.reader ();
2239 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2240 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2242 tr->set_block_size (nframes);
2246 set_worst_io_latencies ();
2252 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2254 boost::shared_ptr<Route> r2;
2256 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2257 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2261 /* make a copy of the existing list of routes that feed r1 */
2263 Route::FedBy existing (r1->fed_by());
2265 /* for each route that feeds r1, recurse, marking it as feeding
2269 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2270 if (!(r2 = i->r.lock ())) {
2271 /* (*i) went away, ignore it */
2275 /* r2 is a route that feeds r1 which somehow feeds base. mark
2276 base as being fed by r2
2279 rbase->add_fed_by (r2, i->sends_only);
2283 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2287 if (r1->feeds (r2) && r2->feeds (r1)) {
2291 /* now recurse, so that we can mark base as being fed by
2292 all routes that feed r2
2295 trace_terminal (r2, rbase);
2302 Session::resort_routes ()
2304 /* don't do anything here with signals emitted
2305 by Routes during initial setup or while we
2306 are being destroyed.
2309 if (inital_connect_or_deletion_in_progress ()) {
2313 if (_route_deletion_in_progress) {
2318 RCUWriter<RouteList> writer (routes);
2319 boost::shared_ptr<RouteList> r = writer.get_copy ();
2320 resort_routes_using (r);
2321 /* writer goes out of scope and forces update */
2325 if (DEBUG_ENABLED(DEBUG::Graph)) {
2326 boost::shared_ptr<RouteList> rl = routes.reader ();
2327 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2328 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2330 const Route::FedBy& fb ((*i)->fed_by());
2332 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2333 boost::shared_ptr<Route> sf = f->r.lock();
2335 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2344 /** This is called whenever we need to rebuild the graph of how we will process
2346 * @param r List of routes, in any order.
2350 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2352 /* We are going to build a directed graph of our routes;
2353 this is where the edges of that graph are put.
2358 /* Go through all routes doing two things:
2360 * 1. Collect the edges of the route graph. Each of these edges
2361 * is a pair of routes, one of which directly feeds the other
2362 * either by a JACK connection or by an internal send.
2364 * 2. Begin the process of making routes aware of which other
2365 * routes directly or indirectly feed them. This information
2366 * is used by the solo code.
2369 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371 /* Clear out the route's list of direct or indirect feeds */
2372 (*i)->clear_fed_by ();
2374 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2376 bool via_sends_only;
2378 /* See if this *j feeds *i according to the current state of the JACK
2379 connections and internal sends.
2381 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2382 /* add the edge to the graph (part #1) */
2383 edges.add (*j, *i, via_sends_only);
2384 /* tell the route (for part #2) */
2385 (*i)->add_fed_by (*j, via_sends_only);
2390 /* Attempt a topological sort of the route graph */
2391 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2393 if (sorted_routes) {
2394 /* We got a satisfactory topological sort, so there is no feedback;
2397 Note: the process graph rechain does not require a
2398 topologically-sorted list, but hey ho.
2400 if (_process_graph) {
2401 _process_graph->rechain (sorted_routes, edges);
2404 _current_route_graph = edges;
2406 /* Complete the building of the routes' lists of what directly
2407 or indirectly feeds them.
2409 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2410 trace_terminal (*i, *i);
2413 *r = *sorted_routes;
2416 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2417 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2418 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2422 SuccessfulGraphSort (); /* EMIT SIGNAL */
2425 /* The topological sort failed, so we have a problem. Tell everyone
2426 and stick to the old graph; this will continue to be processed, so
2427 until the feedback is fixed, what is played back will not quite
2428 reflect what is actually connected. Note also that we do not
2429 do trace_terminal here, as it would fail due to an endless recursion,
2430 so the solo code will think that everything is still connected
2434 FeedbackDetected (); /* EMIT SIGNAL */
2439 /** Find a route name starting with \a base, maybe followed by the
2440 * lowest \a id. \a id will always be added if \a definitely_add_number
2441 * is true on entry; otherwise it will only be added if required
2442 * to make the name unique.
2444 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2445 * The available route name with the lowest ID will be used, and \a id
2446 * will be set to the ID.
2448 * \return false if a route name could not be found, and \a track_name
2449 * and \a id do not reflect a free route name.
2452 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2454 /* the base may conflict with ports that do not belong to existing
2455 routes, but hidden objects like the click track. So check port names
2456 before anything else.
2459 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2460 if (base == reserved->first) {
2461 /* Check if this reserved name already exists, and if
2462 so, disallow it without a numeric suffix.
2464 if (!reserved->second || route_by_name (reserved->first)) {
2465 definitely_add_number = true;
2474 /* if we have "base 1" already, it doesn't make sense to add "base"
2475 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2477 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2478 /* just use the base */
2484 name = string_compose ("%1 %2", base, id);
2486 if (route_by_name (name) == 0) {
2492 } while (id < (UINT_MAX-1));
2497 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2499 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2501 in = ChanCount::ZERO;
2502 out = ChanCount::ZERO;
2504 boost::shared_ptr<RouteList> r = routes.reader ();
2506 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2507 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2511 assert (!tr->is_auditioner()); // XXX remove me
2512 in += tr->n_inputs();
2513 out += tr->n_outputs();
2518 Session::default_track_name_pattern (DataType t)
2521 case DataType::AUDIO:
2522 if (Profile->get_trx()) {
2529 case DataType::MIDI:
2536 /** Caller must not hold process lock
2537 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2538 * @param instrument plugin info for the instrument to insert pre-fader, if any
2540 list<boost::shared_ptr<MidiTrack> >
2541 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2542 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2543 RouteGroup* route_group, uint32_t how_many,
2544 string name_template, PresentationInfo::order_t order,
2548 uint32_t track_id = 0;
2550 RouteList new_routes;
2551 list<boost::shared_ptr<MidiTrack> > ret;
2553 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2554 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2557 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2558 error << "cannot find name for new midi track" << endmsg;
2562 boost::shared_ptr<MidiTrack> track;
2565 track.reset (new MidiTrack (*this, track_name, mode));
2567 if (track->init ()) {
2572 track->set_strict_io (true);
2575 BOOST_MARK_TRACK (track);
2578 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2579 if (track->input()->ensure_io (input, false, this)) {
2580 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2584 if (track->output()->ensure_io (output, false, this)) {
2585 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2591 route_group->add (track);
2594 new_routes.push_back (track);
2595 ret.push_back (track);
2598 catch (failed_constructor &err) {
2599 error << _("Session: could not create new midi track.") << endmsg;
2603 catch (AudioEngine::PortRegistrationFailure& pfe) {
2605 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;
2613 if (!new_routes.empty()) {
2614 StateProtector sp (this);
2615 if (Profile->get_trx()) {
2616 add_routes (new_routes, false, false, false, order);
2618 add_routes (new_routes, true, true, false, order);
2622 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2623 PluginPtr plugin = instrument->load (*this);
2625 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2629 plugin->load_preset (*pset);
2631 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2633 pi->set_strict_io (true);
2636 (*r)->add_processor (pi, PreFader);
2638 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2639 (*r)->move_instrument_down (false);
2649 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2650 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2651 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2654 uint32_t bus_id = 0;
2658 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2661 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2662 error << "cannot find name for new midi bus" << endmsg;
2667 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2674 bus->set_strict_io (true);
2677 BOOST_MARK_ROUTE(bus);
2680 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2682 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2683 error << _("cannot configure new midi bus input") << endmsg;
2688 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2689 error << _("cannot configure new midi bus output") << endmsg;
2695 route_group->add (bus);
2698 bus->add_internal_return ();
2699 ret.push_back (bus);
2702 catch (failed_constructor &err) {
2703 error << _("Session: could not create new audio route.") << endmsg;
2707 catch (AudioEngine::PortRegistrationFailure& pfe) {
2708 error << pfe.what() << endmsg;
2718 StateProtector sp (this);
2719 add_routes (ret, false, false, false, order);
2722 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2723 PluginPtr plugin = instrument->load (*this);
2725 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2729 plugin->load_preset (*pset);
2731 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2733 pi->set_strict_io (true);
2736 (*r)->add_processor (pi, PreFader);
2738 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2739 (*r)->move_instrument_down (false);
2751 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2753 boost::shared_ptr<Route> midi_track (wmt.lock());
2759 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2761 if (change.after.n_audio() <= change.before.n_audio()) {
2765 /* new audio ports: make sure the audio goes somewhere useful,
2766 * unless the user has no-auto-connect selected.
2768 * The existing ChanCounts don't matter for this call as they are only
2769 * to do with matching input and output indices, and we are only changing
2772 auto_connect_route (midi_track, false, ChanCount(), change.before);
2776 #ifdef USE_TRACKS_CODE_FEATURES
2779 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2781 return route1->remote_control_id() < route2->remote_control_id();
2785 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2787 // it is not allowed to perform connection
2788 if (!IO::connecting_legal) {
2792 // if we are deleting routes we will call this once at the end
2793 if (_route_deletion_in_progress) {
2797 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2803 // We need to disconnect the route's inputs and outputs first
2804 // basing on autoconnect configuration
2805 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2806 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2808 ChanCount existing_inputs;
2809 ChanCount existing_outputs;
2810 count_existing_track_channels (existing_inputs, existing_outputs);
2812 //ChanCount inputs = ChanCount::ZERO;
2813 //ChanCount outputs = ChanCount::ZERO;
2815 RouteList existing_routes = *routes.reader ();
2816 existing_routes.sort (compare_routes_by_remote_id);
2819 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2821 vector<string> physinputs;
2822 vector<string> physoutputs;
2824 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2825 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2827 uint32_t input_n = 0;
2828 uint32_t output_n = 0;
2829 RouteList::iterator rIter = existing_routes.begin();
2830 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2831 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2832 for (; rIter != existing_routes.end(); ++rIter) {
2833 if (*rIter == _master_out || *rIter == _monitor_out ) {
2837 if (current_output_auto_connection == AutoConnectPhysical) {
2838 (*rIter)->amp()->deactivate();
2839 } else if (current_output_auto_connection == AutoConnectMaster) {
2840 (*rIter)->amp()->activate();
2843 if (reconnectIputs) {
2844 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2846 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2848 if (current_input_auto_connection & AutoConnectPhysical) {
2850 if ( input_n == physinputs.size() ) {
2854 string port = physinputs[input_n];
2856 if (port.empty() ) {
2857 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2860 //GZ: check this; could be heavy
2861 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2867 if (reconnectOutputs) {
2869 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2870 if (current_output_auto_connection & AutoConnectPhysical) {
2872 //GZ: check this; could be heavy
2873 (*rIter)->output()->disconnect (this);
2874 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2876 //GZ: check this; could be heavy
2877 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2879 } else if (current_output_auto_connection & AutoConnectMaster){
2881 if (!reconnect_master) {
2885 //GZ: check this; could be heavy
2886 (*rIter)->output()->disconnect (this);
2889 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2890 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2892 error << error << "Master bus is not available" << endmsg;
2897 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2898 if (current_output_auto_connection & AutoConnectPhysical) {
2900 if ( output_n == physoutputs.size() ) {
2904 string port = physoutputs[output_n];
2906 if (port.empty() ) {
2907 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2910 //GZ: check this; could be heavy
2911 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2914 } else if (current_output_auto_connection & AutoConnectMaster) {
2916 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2920 // connect to master bus
2921 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2923 if (port.empty() ) {
2924 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2928 //GZ: check this; could be heavy
2929 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2936 _master_out->output()->disconnect (this);
2937 auto_connect_master_bus ();
2942 session_routes_reconnected (); /* EMIT SIGNAL */
2946 Session::reconnect_midi_scene_ports(bool inputs)
2950 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2952 scene_in_ptr->disconnect_all ();
2954 std::vector<EngineStateController::MidiPortState> midi_port_states;
2955 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2957 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2959 for (; state_iter != midi_port_states.end(); ++state_iter) {
2960 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2961 scene_in_ptr->connect (state_iter->name);
2968 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2970 if (scene_out_ptr ) {
2971 scene_out_ptr->disconnect_all ();
2973 std::vector<EngineStateController::MidiPortState> midi_port_states;
2974 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2976 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2978 for (; state_iter != midi_port_states.end(); ++state_iter) {
2979 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2980 scene_out_ptr->connect (state_iter->name);
2988 Session::reconnect_mmc_ports(bool inputs)
2990 if (inputs ) { // get all enabled midi input ports
2992 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2994 mmc_in_ptr->disconnect_all ();
2995 std::vector<std::string> enabled_midi_inputs;
2996 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2998 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3000 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3001 mmc_in_ptr->connect (*port_iter);
3005 } else { // get all enabled midi output ports
3007 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3009 mmc_out_ptr->disconnect_all ();
3010 std::vector<std::string> enabled_midi_outputs;
3011 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3013 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3015 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3016 mmc_out_ptr->connect (*port_iter);
3025 Session::ensure_stripable_sort_order ()
3028 get_stripables (sl);
3029 sl.sort (Stripable::Sorter ());
3031 bool change = false;
3032 PresentationInfo::order_t order = 0;
3034 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3035 boost::shared_ptr<Stripable> s (*si);
3036 assert (!s->is_auditioner ()); // XXX remove me
3037 if (s->is_monitor ()) {
3040 if (order != s->presentation_info().order()) {
3041 s->set_presentation_order (order);
3050 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3052 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3054 if (first_new_order == PresentationInfo::max_order) {
3055 /* adding at end, no worries */
3059 /* create a gap in the presentation info to accomodate @param how_many
3063 get_stripables (sl);
3065 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3066 boost::shared_ptr<Stripable> s (*si);
3068 if (s->presentation_info().special (false)) {
3072 if (!s->presentation_info().order_set()) {
3076 if (s->presentation_info().order () >= first_new_order) {
3077 s->set_presentation_order (s->presentation_info().order () + how_many);
3082 /** Caller must not hold process lock
3083 * @param name_template string to use for the start of the name, or "" to use "Audio".
3085 list< boost::shared_ptr<AudioTrack> >
3086 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3087 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3091 uint32_t track_id = 0;
3093 RouteList new_routes;
3094 list<boost::shared_ptr<AudioTrack> > ret;
3096 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3097 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3101 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3102 error << "cannot find name for new audio track" << endmsg;
3106 boost::shared_ptr<AudioTrack> track;
3109 track.reset (new AudioTrack (*this, track_name, mode));
3111 if (track->init ()) {
3115 if (Profile->get_mixbus ()) {
3116 track->set_strict_io (true);
3119 if (ARDOUR::Profile->get_trx ()) {
3120 // TRACKS considers it's not a USE CASE, it's
3121 // a piece of behavior of the session model:
3123 // Gain for a newly created route depends on
3124 // the current output_auto_connect mode:
3126 // 0 for Stereo Out mode
3128 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3129 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3133 BOOST_MARK_TRACK (track);
3136 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3138 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3139 error << string_compose (
3140 _("cannot configure %1 in/%2 out configuration for new audio track"),
3141 input_channels, output_channels)
3146 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3147 error << string_compose (
3148 _("cannot configure %1 in/%2 out configuration for new audio track"),
3149 input_channels, output_channels)
3156 route_group->add (track);
3159 new_routes.push_back (track);
3160 ret.push_back (track);
3163 catch (failed_constructor &err) {
3164 error << _("Session: could not create new audio track.") << endmsg;
3168 catch (AudioEngine::PortRegistrationFailure& pfe) {
3170 error << pfe.what() << endmsg;
3178 if (!new_routes.empty()) {
3179 StateProtector sp (this);
3180 if (Profile->get_trx()) {
3181 add_routes (new_routes, false, false, false, order);
3183 add_routes (new_routes, true, true, false, order);
3190 /** Caller must not hold process lock.
3191 * @param name_template string to use for the start of the name, or "" to use "Bus".
3194 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3195 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3198 uint32_t bus_id = 0;
3202 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3205 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3206 error << "cannot find name for new audio bus" << endmsg;
3211 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3217 if (Profile->get_mixbus ()) {
3218 bus->set_strict_io (true);
3221 BOOST_MARK_ROUTE(bus);
3224 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3226 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3227 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3228 input_channels, output_channels)
3234 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3235 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3236 input_channels, output_channels)
3243 route_group->add (bus);
3246 bus->add_internal_return ();
3247 ret.push_back (bus);
3250 catch (failed_constructor &err) {
3251 error << _("Session: could not create new audio route.") << endmsg;
3255 catch (AudioEngine::PortRegistrationFailure& pfe) {
3256 error << pfe.what() << endmsg;
3266 StateProtector sp (this);
3267 if (Profile->get_trx()) {
3268 add_routes (ret, false, false, false, order);
3269 } else if (flags == PresentationInfo::FoldbackBus) {
3270 add_routes (ret, false, false, true, order); // no autoconnect
3272 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3281 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3282 PlaylistDisposition pd)
3286 if (!tree.read (template_path.c_str())) {
3290 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3294 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3297 uint32_t number = 0;
3298 const uint32_t being_added = how_many;
3299 /* This will prevent the use of any existing XML-provided PBD::ID
3302 Stateful::ForceIDRegeneration force_ids;
3303 IO::disable_connecting ();
3307 /* We're going to modify the node contents a bit so take a
3308 * copy. The node may be re-used when duplicating more than once.
3311 XMLNode node_copy (node);
3316 if (!name_base.empty()) {
3318 /* if we're adding more than one routes, force
3319 * all the names of the new routes to be
3320 * numbered, via the final parameter.
3323 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3324 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3330 string const route_name = node_copy.property(X_("name"))->value ();
3332 /* generate a new name by adding a number to the end of the template name */
3333 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3334 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3335 abort(); /*NOTREACHED*/
3339 /* set this name in the XML description that we are about to use */
3340 #warning fixme -- no more Diskstream
3341 if (pd == CopyPlaylist) {
3342 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3344 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3345 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3346 // Use same name as Route::set_name_in_state so playlist copy
3347 // is picked up when creating the Route in XMLRouteFactory below
3348 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3349 playlist->reset_shares ();
3351 } else if (pd == SharePlaylist) {
3352 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3354 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3355 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3356 playlist->share_with ((node_copy.property (X_("id")))->value());
3360 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3362 Route::set_name_in_state (node_copy, name, rename_playlist);
3364 /* trim bitslots from listen sends so that new ones are used */
3365 XMLNodeList children = node_copy.children ();
3366 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3367 if ((*i)->name() == X_("Processor")) {
3368 /* ForceIDRegeneration does not catch the following */
3369 XMLProperty const * role = (*i)->property (X_("role"));
3370 XMLProperty const * type = (*i)->property (X_("type"));
3371 if (role && role->value() == X_("Aux")) {
3372 /* check if the target bus exists.
3373 * we should not save aux-sends in templates.
3375 XMLProperty const * target = (*i)->property (X_("target"));
3377 (*i)->set_property ("type", "dangling-aux-send");
3380 boost::shared_ptr<Route> r = route_by_id (target->value());
3381 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3382 (*i)->set_property ("type", "dangling-aux-send");
3386 if (role && role->value() == X_("Listen")) {
3387 (*i)->remove_property (X_("bitslot"));
3389 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3390 Delivery::Role xrole;
3391 uint32_t bitslot = 0;
3392 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3393 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3394 (*i)->remove_property (X_("bitslot"));
3395 (*i)->remove_property (X_("name"));
3396 (*i)->set_property ("bitslot", bitslot);
3397 (*i)->set_property ("name", name);
3399 else if (type && type->value() == X_("intreturn")) {
3400 (*i)->remove_property (X_("bitslot"));
3401 (*i)->set_property ("ignore-bitslot", "1");
3403 else if (type && type->value() == X_("return")) {
3404 // Return::set_state() generates a new one
3405 (*i)->remove_property (X_("bitslot"));
3407 else if (type && type->value() == X_("port")) {
3408 IOProcessor::prepare_for_reset (**i, name);
3413 /* new routes start off unsoloed to avoid issues related to
3414 upstream / downstream buses. */
3415 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3417 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3420 error << _("Session: cannot create track/bus from template description") << endmsg;
3424 if (boost::dynamic_pointer_cast<Track>(route)) {
3425 /* force input/output change signals so that the new diskstream
3426 picks up the configuration of the route. During session
3427 loading this normally happens in a different way.
3430 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3432 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3433 change.after = route->input()->n_ports();
3434 route->input()->changed (change, this);
3435 change.after = route->output()->n_ports();
3436 route->output()->changed (change, this);
3439 ret.push_back (route);
3442 catch (failed_constructor &err) {
3443 error << _("Session: could not create new route from template") << endmsg;
3447 catch (AudioEngine::PortRegistrationFailure& pfe) {
3448 error << pfe.what() << endmsg;
3453 IO::enable_connecting ();
3462 StateProtector sp (this);
3463 if (Profile->get_trx()) {
3464 add_routes (ret, false, false, false, insert_at);
3466 add_routes (ret, true, true, false, insert_at);
3470 IO::enable_connecting ();
3476 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3479 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3480 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3483 error << _("Adding new tracks/busses failed") << endmsg;
3488 update_latency (false);
3489 update_latency (true);
3494 save_state (_current_snapshot_name);
3497 update_route_record_state ();
3499 RouteAdded (new_routes); /* EMIT SIGNAL */
3503 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3505 ChanCount existing_inputs;
3506 ChanCount existing_outputs;
3510 count_existing_track_channels (existing_inputs, existing_outputs);
3513 RCUWriter<RouteList> writer (routes);
3514 boost::shared_ptr<RouteList> r = writer.get_copy ();
3515 n_routes = r->size();
3516 r->insert (r->end(), new_routes.begin(), new_routes.end());
3518 /* if there is no control out and we're not in the middle of loading,
3519 * resort the graph here. if there is a control out, we will resort
3520 * toward the end of this method. if we are in the middle of loading,
3521 * we will resort when done.
3524 if (!_monitor_out && IO::connecting_legal) {
3525 resort_routes_using (r);
3529 /* monitor is not part of the order */
3531 assert (n_routes > 0);
3536 PresentationInfo::ChangeSuspender cs;
3537 ensure_route_presentation_info_gap (order, new_routes.size());
3539 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3541 boost::weak_ptr<Route> wpr (*x);
3542 boost::shared_ptr<Route> r (*x);
3544 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3545 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3546 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3548 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3549 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3550 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3552 if (r->is_master()) {
3556 if (r->is_monitor()) {
3560 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3562 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3563 track_playlist_changed (boost::weak_ptr<Track> (tr));
3564 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3566 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3568 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3569 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3570 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3574 if (!r->presentation_info().special (false)) {
3576 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3578 /* presentation info order may already have been set from XML */
3580 if (!r->presentation_info().order_set()) {
3581 if (order == PresentationInfo::max_order) {
3582 /* just add to the end */
3583 r->set_presentation_order (n_routes + added);
3584 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3586 r->set_presentation_order (order + added);
3587 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3590 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3594 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3595 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3596 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3598 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3600 r->presentation_info().order(),
3601 enum_2_string (r->presentation_info().flags()),
3602 r->presentation_info()));
3606 if (input_auto_connect || output_auto_connect) {
3607 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3608 existing_inputs += r->n_inputs();
3609 existing_outputs += r->n_outputs();
3614 ensure_stripable_sort_order ();
3617 if (_monitor_out && IO::connecting_legal) {
3618 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3620 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3621 if ((*x)->is_monitor()) {
3623 } else if ((*x)->is_master()) {
3626 (*x)->enable_monitor_send ();
3631 reassign_track_numbers ();
3635 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3637 boost::shared_ptr<RouteList> r = routes.reader ();
3638 boost::shared_ptr<Send> s;
3640 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3641 if ((s = (*i)->internal_send_for (dest)) != 0) {
3642 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3648 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3650 boost::shared_ptr<RouteList> r = routes.reader ();
3651 boost::shared_ptr<Send> s;
3653 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3654 if ((s = (*i)->internal_send_for (dest)) != 0) {
3655 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3661 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3663 boost::shared_ptr<RouteList> r = routes.reader ();
3664 boost::shared_ptr<Send> s;
3666 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3667 if ((s = (*i)->internal_send_for (dest)) != 0) {
3668 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3673 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3675 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3677 boost::shared_ptr<RouteList> r = routes.reader ();
3678 boost::shared_ptr<RouteList> t (new RouteList);
3680 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3681 /* no MIDI sends because there are no MIDI busses yet */
3682 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3687 add_internal_sends (dest, p, t);
3691 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3693 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3694 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3699 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3701 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3705 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3707 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3711 if (!dest->internal_return()) {
3712 dest->add_internal_return ();
3715 sender->add_aux_send (dest, before);
3721 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3723 bool mute_changed = false;
3724 bool send_selected = false;
3726 { // RCU Writer scope
3727 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3728 RCUWriter<RouteList> writer (routes);
3729 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3731 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3733 if (_selection->selected (*iter)) {
3734 send_selected = true;
3737 if (*iter == _master_out) {
3741 /* speed up session deletion, don't do the solo dance */
3742 if (!deletion_in_progress ()) {
3743 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3746 if ((*iter)->mute_control()->muted ()) {
3747 mute_changed = true;
3752 /* deleting the master out seems like a dumb
3753 idea, but its more of a UI policy issue
3757 if (*iter == _master_out) {
3758 _master_out = boost::shared_ptr<Route> ();
3761 if (*iter == _monitor_out) {
3762 _monitor_out.reset ();
3765 // We need to disconnect the route's inputs and outputs
3767 (*iter)->input()->disconnect (0);
3768 (*iter)->output()->disconnect (0);
3770 /* if the route had internal sends sending to it, remove them */
3772 if (!deletion_in_progress () && (*iter)->internal_return()) {
3774 boost::shared_ptr<RouteList> r = routes.reader ();
3775 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3776 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3778 (*i)->remove_processor (s);
3783 /* if the monitoring section had a pointer to this route, remove it */
3784 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3785 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3786 ProcessorChangeBlocker pcb (this, false);
3787 (*iter)->remove_aux_or_listen (_monitor_out);
3790 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3791 if (mt && mt->step_editing()) {
3792 if (_step_editors > 0) {
3798 /* writer goes out of scope, forces route list update */
3800 } // end of RCU Writer scope
3803 MuteChanged (); /* EMIT SIGNAL */
3806 update_route_solo_state ();
3807 update_latency_compensation ();
3810 /* Re-sort routes to remove the graph's current references to the one that is
3811 * going away, then flush old references out of the graph.
3812 * Wave Tracks: reconnect routes
3815 #ifdef USE_TRACKS_CODE_FEATURES
3816 reconnect_existing_routes(true, false);
3818 routes.flush (); // maybe unsafe, see below.
3822 if (_process_graph && !deletion_in_progress() && _engine.running()) {
3823 _process_graph->clear_other_chain ();
3826 /* get rid of it from the dead wood collection in the route list manager */
3827 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3831 /* remove these routes from the selection if appropriate, and signal
3832 * the change *before* we call DropReferences for them.
3835 if (send_selected && !deletion_in_progress()) {
3836 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3837 _selection->remove_stripable_by_id ((*iter)->id());
3840 pc.add (Properties::selected);
3841 PresentationInfo::Change (pc);
3844 /* try to cause everyone to drop their references
3845 * and unregister ports from the backend
3848 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3849 (*iter)->drop_references ();
3852 if (deletion_in_progress()) {
3857 pc.add (Properties::order);
3858 PresentationInfo::Change (pc);
3860 /* save the new state of the world */
3862 if (save_state (_current_snapshot_name)) {
3863 save_history (_current_snapshot_name);
3866 update_route_record_state ();
3870 Session::remove_route (boost::shared_ptr<Route> route)
3872 boost::shared_ptr<RouteList> rl (new RouteList);
3873 rl->push_back (route);
3878 Session::route_mute_changed ()
3880 MuteChanged (); /* EMIT SIGNAL */
3885 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3887 boost::shared_ptr<Route> route (wpr.lock());
3893 assert (Config->get_solo_control_is_listen_control());
3895 if (route->solo_control()->soloed_by_self_or_masters()) {
3897 if (Config->get_exclusive_solo()) {
3899 RouteGroup* rg = route->route_group ();
3900 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3902 boost::shared_ptr<RouteList> r = routes.reader ();
3904 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3905 if ((*i) == route) {
3906 /* already changed */
3910 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3911 /* route does not get solo propagated to it */
3915 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3916 /* this route is a part of the same solo group as the route
3917 * that was changed. Changing that route did change or will
3918 * change all group members appropriately, so we can ignore it
3923 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3929 } else if (_listen_cnt > 0) {
3936 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3938 boost::shared_ptr<Route> route (wpr.lock());
3944 bool send_changed = false;
3946 if (route->solo_isolate_control()->solo_isolated()) {
3947 if (_solo_isolated_cnt == 0) {
3948 send_changed = true;
3950 _solo_isolated_cnt++;
3951 } else if (_solo_isolated_cnt > 0) {
3952 _solo_isolated_cnt--;
3953 if (_solo_isolated_cnt == 0) {
3954 send_changed = true;
3959 IsolatedChanged (); /* EMIT SIGNAL */
3964 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3966 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3968 boost::shared_ptr<Route> route (wpr.lock());
3974 if (Config->get_solo_control_is_listen_control()) {
3975 route_listen_changed (group_override, wpr);
3979 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()));
3981 if (route->solo_control()->transitioned_into_solo() == 0) {
3982 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3985 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()));
3989 boost::shared_ptr<RouteList> r = routes.reader ();
3990 int32_t delta = route->solo_control()->transitioned_into_solo ();
3992 /* the route may be a member of a group that has shared-solo
3993 * semantics. If so, then all members of that group should follow the
3994 * solo of the changed route. But ... this is optional, controlled by a
3995 * Controllable::GroupControlDisposition.
3997 * The first argument to the signal that this method is connected to is the
3998 * GroupControlDisposition value that was used to change solo.
4000 * If the solo change was done with group semantics (either InverseGroup
4001 * (force the entire group to change even if the group shared solo is
4002 * disabled) or UseGroup (use the group, which may or may not have the
4003 * shared solo property enabled)) then as we propagate the change to
4004 * the entire session we should IGNORE THE GROUP that the changed route
4008 RouteGroup* rg = route->route_group ();
4009 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4011 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4013 if (delta == 1 && Config->get_exclusive_solo()) {
4015 /* new solo: disable all other solos, but not the group if its solo-enabled */
4017 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4019 if ((*i) == route) {
4020 /* already changed */
4024 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4025 /* route does not get solo propagated to it */
4029 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4030 /* this route is a part of the same solo group as the route
4031 * that was changed. Changing that route did change or will
4032 * change all group members appropriately, so we can ignore it
4038 (*i)->solo_control()->set_value (0.0, group_override);
4042 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4044 RouteList uninvolved;
4046 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4048 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4049 bool via_sends_only;
4050 bool in_signal_flow;
4052 if ((*i) == route) {
4053 /* already changed */
4057 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4058 /* route does not get solo propagated to it */
4059 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(),
4064 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4065 /* this route is a part of the same solo group as the route
4066 * that was changed. Changing that route did change or will
4067 * change all group members appropriately, so we can ignore it
4073 in_signal_flow = false;
4075 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4077 if ((*i)->feeds (route, &via_sends_only)) {
4078 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4079 if (!via_sends_only) {
4080 if (!route->soloed_by_others_upstream()) {
4081 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4083 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4086 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4088 in_signal_flow = true;
4090 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4093 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4095 if (route->feeds (*i, &via_sends_only)) {
4096 /* propagate solo upstream only if routing other than
4097 sends is involved, but do consider the other route
4098 (*i) to be part of the signal flow even if only
4101 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4105 route->soloed_by_others_downstream(),
4106 route->soloed_by_others_upstream()));
4107 if (!via_sends_only) {
4108 //NB. Triggers Invert Push, which handles soloed by downstream
4109 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4110 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4112 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4114 in_signal_flow = true;
4116 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4119 if (!in_signal_flow) {
4120 uninvolved.push_back (*i);
4124 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4126 /* now notify that the mute state of the routes not involved in the signal
4127 pathway of the just-solo-changed route may have altered.
4130 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4131 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4132 (*i)->act_on_mute ();
4133 /* Session will emit SoloChanged() after all solo changes are
4134 * complete, which should be used by UIs to update mute status
4140 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4142 /* now figure out if anything that matters is soloed (or is "listening")*/
4144 bool something_soloed = false;
4145 bool something_listening = false;
4146 uint32_t listeners = 0;
4147 uint32_t isolated = 0;
4150 r = routes.reader();
4153 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4154 if ((*i)->can_solo()) {
4155 if (Config->get_solo_control_is_listen_control()) {
4156 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4158 something_listening = true;
4161 (*i)->set_listen (false);
4162 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4163 something_soloed = true;
4168 if ((*i)->solo_isolate_control()->solo_isolated()) {
4173 if (something_soloed != _non_soloed_outs_muted) {
4174 _non_soloed_outs_muted = something_soloed;
4175 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4178 if (something_listening != _listening) {
4179 _listening = something_listening;
4180 SoloActive (_listening);
4183 _listen_cnt = listeners;
4185 if (isolated != _solo_isolated_cnt) {
4186 _solo_isolated_cnt = isolated;
4187 IsolatedChanged (); /* EMIT SIGNAL */
4190 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4191 something_soloed, listeners, isolated));
4194 SoloChanged (); /* EMIT SIGNAL */
4199 Session::muted () const
4201 // TODO consider caching the value on every MuteChanged signal,
4202 // Note that API users may also subscribe to MuteChanged and hence
4203 // this method needs to be called first.
4206 get_stripables (all);
4207 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4208 assert (!(*i)->is_auditioner()); // XXX remove me
4209 if ((*i)->is_monitor()) {
4212 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4213 if (r && !r->active()) {
4216 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4217 if (mc && mc->muted ()) {
4225 std::vector<boost::weak_ptr<AutomationControl> >
4226 Session::cancel_all_mute ()
4229 get_stripables (all);
4230 std::vector<boost::weak_ptr<AutomationControl> > muted;
4231 boost::shared_ptr<ControlList> cl (new ControlList);
4232 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4233 assert (!(*i)->is_auditioner());
4234 if ((*i)->is_monitor()) {
4237 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4238 if (r && !r->active()) {
4241 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4242 if (ac && ac->get_value () > 0) {
4244 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4247 if (!cl->empty ()) {
4248 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4254 Session::get_stripables (StripableList& sl, PresentationInfo::Flag fl) const
4256 boost::shared_ptr<RouteList> r = routes.reader ();
4257 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4258 if ((*it)->presentation_info ().flags () & fl) {
4263 if (fl & PresentationInfo::VCA) {
4264 VCAList v = _vca_manager->vcas ();
4265 sl.insert (sl.end(), v.begin(), v.end());
4270 Session::get_stripables () const
4272 PresentationInfo::Flag fl = PresentationInfo::AllStripables;
4274 Session::get_stripables (rv, fl);
4275 rv.sort (Stripable::Sorter ());
4280 Session::get_routelist (bool mixer_order, PresentationInfo::Flag fl) const
4282 boost::shared_ptr<RouteList> r = routes.reader ();
4284 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4285 if ((*it)->presentation_info ().flags () & fl) {
4289 rv.sort (Stripable::Sorter (mixer_order));
4293 boost::shared_ptr<RouteList>
4294 Session::get_routes_with_internal_returns() const
4296 boost::shared_ptr<RouteList> r = routes.reader ();
4297 boost::shared_ptr<RouteList> rl (new RouteList);
4299 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4300 if ((*i)->internal_return ()) {
4308 Session::io_name_is_legal (const std::string& name) const
4310 boost::shared_ptr<RouteList> r = routes.reader ();
4312 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4313 if (name == reserved->first) {
4314 if (!route_by_name (reserved->first)) {
4315 /* first instance of a reserved name is allowed for some */
4316 return reserved->second;
4318 /* all other instances of a reserved name are not allowed */
4323 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4324 if ((*i)->name() == name) {
4328 if ((*i)->has_io_processor_named (name)) {
4337 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4340 vector<string> connections;
4342 /* if we are passed only a single route and we're not told to turn
4343 * others off, then just do the simple thing.
4346 if (flip_others == false && rl->size() == 1) {
4347 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4349 mt->set_input_active (onoff);
4354 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4356 PortSet& ps ((*rt)->input()->ports());
4358 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4359 p->get_connections (connections);
4362 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4363 routes_using_input_from (*s, rl2);
4366 /* scan all relevant routes to see if others are on or off */
4368 bool others_are_already_on = false;
4370 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4372 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4378 if ((*r) != (*rt)) {
4379 if (mt->input_active()) {
4380 others_are_already_on = true;
4383 /* this one needs changing */
4384 mt->set_input_active (onoff);
4390 /* globally reverse other routes */
4392 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4393 if ((*r) != (*rt)) {
4394 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4396 mt->set_input_active (!others_are_already_on);
4405 Session::routes_using_input_from (const string& str, RouteList& rl)
4407 boost::shared_ptr<RouteList> r = routes.reader();
4409 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4410 if ((*i)->input()->connected_to (str)) {
4416 boost::shared_ptr<Route>
4417 Session::route_by_name (string name) const
4419 boost::shared_ptr<RouteList> r = routes.reader ();
4421 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4422 if ((*i)->name() == name) {
4427 return boost::shared_ptr<Route> ((Route*) 0);
4430 boost::shared_ptr<Route>
4431 Session::route_by_id (PBD::ID id) const
4433 boost::shared_ptr<RouteList> r = routes.reader ();
4435 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4436 if ((*i)->id() == id) {
4441 return boost::shared_ptr<Route> ((Route*) 0);
4445 boost::shared_ptr<Stripable>
4446 Session::stripable_by_id (PBD::ID id) const
4449 get_stripables (sl);
4451 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4452 if ((*s)->id() == id) {
4457 return boost::shared_ptr<Stripable>();
4460 boost::shared_ptr<Processor>
4461 Session::processor_by_id (PBD::ID id) const
4463 boost::shared_ptr<RouteList> r = routes.reader ();
4465 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4466 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4472 return boost::shared_ptr<Processor> ();
4475 boost::shared_ptr<Route>
4476 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4478 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4481 boost::shared_ptr<Stripable>
4482 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4485 PresentationInfo::order_t match_cnt = 0;
4487 get_stripables (sl);
4488 sl.sort (Stripable::Sorter());
4490 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4492 if ((*s)->presentation_info().hidden()) {
4493 /* if the caller didn't explicitly ask for hidden
4494 stripables, ignore hidden ones. This matches
4495 the semantics of the pre-PresentationOrder
4496 "get by RID" logic of Ardour 4.x and earlier.
4498 XXX at some point we should likely reverse
4499 the logic of the flags, because asking for "the
4500 hidden stripables" is not going to be common,
4501 whereas asking for visible ones is normal.
4504 if (! (flags & PresentationInfo::Hidden)) {
4509 if ((*s)->presentation_info().flag_match (flags)) {
4510 if (match_cnt++ == n) {
4516 /* there is no nth stripable that matches the given flags */
4517 return boost::shared_ptr<Stripable>();
4520 boost::shared_ptr<Route>
4521 Session::route_by_selected_count (uint32_t id) const
4523 RouteList r (*(routes.reader ()));
4524 r.sort (Stripable::Sorter());
4526 RouteList::iterator i;
4528 for (i = r.begin(); i != r.end(); ++i) {
4529 if ((*i)->is_selected()) {
4537 return boost::shared_ptr<Route> ();
4541 Session::reassign_track_numbers ()
4545 RouteList r (*(routes.reader ()));
4546 r.sort (Stripable::Sorter());
4548 StateProtector sp (this);
4550 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4551 assert (!(*i)->is_auditioner());
4552 if (boost::dynamic_pointer_cast<Track> (*i)) {
4553 (*i)->set_track_number(++tn);
4555 else if (!(*i)->is_master() && !(*i)->is_monitor()) {
4556 (*i)->set_track_number(--bn);
4559 const uint32_t decimals = ceilf (log10f (tn + 1));
4560 const bool decimals_changed = _track_number_decimals != decimals;
4561 _track_number_decimals = decimals;
4563 if (decimals_changed && config.get_track_name_number ()) {
4564 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4565 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4567 t->resync_track_name();
4570 // trigger GUI re-layout
4571 config.ParameterChanged("track-name-number");
4575 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4576 boost::shared_ptr<RouteList> rl = routes.reader ();
4577 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4578 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4586 Session::playlist_region_added (boost::weak_ptr<Region> w)
4588 boost::shared_ptr<Region> r = w.lock ();
4593 /* These are the operations that are currently in progress... */
4594 list<GQuark> curr = _current_trans_quarks;
4597 /* ...and these are the operations during which we want to update
4598 the session range location markers.
4601 ops.push_back (Operations::capture);
4602 ops.push_back (Operations::paste);
4603 ops.push_back (Operations::duplicate_region);
4604 ops.push_back (Operations::insert_file);
4605 ops.push_back (Operations::insert_region);
4606 ops.push_back (Operations::drag_region_brush);
4607 ops.push_back (Operations::region_drag);
4608 ops.push_back (Operations::selection_grab);
4609 ops.push_back (Operations::region_fill);
4610 ops.push_back (Operations::fill_selection);
4611 ops.push_back (Operations::create_region);
4612 ops.push_back (Operations::region_copy);
4613 ops.push_back (Operations::fixed_time_region_copy);
4616 /* See if any of the current operations match the ones that we want */
4618 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4620 /* If so, update the session range markers */
4622 maybe_update_session_range (r->position (), r->last_sample ());
4626 /** Update the session range markers if a is before the current start or
4627 * b is after the current end.
4630 Session::maybe_update_session_range (samplepos_t a, samplepos_t b)
4636 samplepos_t session_end_marker_shift_samples = session_end_shift * _nominal_sample_rate;
4638 if (_session_range_location == 0) {
4640 set_session_range_location (a, b + session_end_marker_shift_samples);
4644 if (_session_range_is_free && (a < _session_range_location->start())) {
4645 _session_range_location->set_start (a);
4648 if (_session_range_is_free && (b > _session_range_location->end())) {
4649 _session_range_location->set_end (b);
4655 Session::set_session_range_is_free (bool yn)
4657 _session_range_is_free = yn;
4661 Session::playlist_ranges_moved (list<Evoral::RangeMove<samplepos_t> > const & ranges)
4663 for (list<Evoral::RangeMove<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4664 maybe_update_session_range (i->to, i->to + i->length);
4669 Session::playlist_regions_extended (list<Evoral::Range<samplepos_t> > const & ranges)
4671 for (list<Evoral::Range<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4672 maybe_update_session_range (i->from, i->to);
4676 /* Region management */
4678 boost::shared_ptr<Region>
4679 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4681 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4682 RegionFactory::RegionMap::const_iterator i;
4683 boost::shared_ptr<Region> region;
4685 Glib::Threads::Mutex::Lock lm (region_lock);
4687 for (i = regions.begin(); i != regions.end(); ++i) {
4691 if (region->whole_file()) {
4693 if (child->source_equivalent (region)) {
4699 return boost::shared_ptr<Region> ();
4703 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4705 set<boost::shared_ptr<Region> > relevant_regions;
4707 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4708 RegionFactory::get_regions_using_source (*s, relevant_regions);
4711 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4712 set<boost::shared_ptr<Region> >::iterator tmp;
4717 playlists->destroy_region (*r);
4718 RegionFactory::map_remove (*r);
4720 (*r)->drop_sources ();
4721 (*r)->drop_references ();
4723 relevant_regions.erase (r);
4728 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4731 Glib::Threads::Mutex::Lock ls (source_lock);
4732 /* remove from the main source list */
4733 sources.erase ((*s)->id());
4736 (*s)->mark_for_remove ();
4737 (*s)->drop_references ();
4746 Session::remove_last_capture ()
4748 list<boost::shared_ptr<Source> > srcs;
4750 boost::shared_ptr<RouteList> rl = routes.reader ();
4751 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4752 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4757 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4760 srcs.insert (srcs.end(), l.begin(), l.end());
4765 destroy_sources (srcs);
4767 save_state (_current_snapshot_name);
4772 /* Source Management */
4775 Session::add_source (boost::shared_ptr<Source> source)
4777 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4778 pair<SourceMap::iterator,bool> result;
4780 entry.first = source->id();
4781 entry.second = source;
4784 Glib::Threads::Mutex::Lock lm (source_lock);
4785 result = sources.insert (entry);
4788 if (result.second) {
4790 /* yay, new source */
4792 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4795 if (!fs->within_session()) {
4796 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4802 boost::shared_ptr<AudioFileSource> afs;
4804 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4805 if (Config->get_auto_analyse_audio()) {
4806 Analyser::queue_source_for_analysis (source, false);
4810 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4815 Session::remove_source (boost::weak_ptr<Source> src)
4817 if (deletion_in_progress ()) {
4821 SourceMap::iterator i;
4822 boost::shared_ptr<Source> source = src.lock();
4829 Glib::Threads::Mutex::Lock lm (source_lock);
4831 if ((i = sources.find (source->id())) != sources.end()) {
4836 if (!in_cleanup () && !loading ()) {
4838 /* save state so we don't end up with a session file
4839 * referring to non-existent sources.
4842 save_state (_current_snapshot_name);
4846 boost::shared_ptr<Source>
4847 Session::source_by_id (const PBD::ID& id)
4849 Glib::Threads::Mutex::Lock lm (source_lock);
4850 SourceMap::iterator i;
4851 boost::shared_ptr<Source> source;
4853 if ((i = sources.find (id)) != sources.end()) {
4860 boost::shared_ptr<AudioFileSource>
4861 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4863 /* Restricted to audio files because only audio sources have channel
4867 Glib::Threads::Mutex::Lock lm (source_lock);
4869 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4870 boost::shared_ptr<AudioFileSource> afs
4871 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4873 if (afs && afs->path() == path && chn == afs->channel()) {
4878 return boost::shared_ptr<AudioFileSource>();
4881 boost::shared_ptr<MidiSource>
4882 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4884 /* Restricted to MIDI files because audio sources require a channel
4885 for unique identification, in addition to a path.
4888 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4889 if (need_source_lock) {
4893 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4894 boost::shared_ptr<MidiSource> ms
4895 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4896 boost::shared_ptr<FileSource> fs
4897 = boost::dynamic_pointer_cast<FileSource>(s->second);
4899 if (ms && fs && fs->path() == path) {
4904 return boost::shared_ptr<MidiSource>();
4908 Session::count_sources_by_origin (const string& path)
4911 Glib::Threads::Mutex::Lock lm (source_lock);
4913 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4914 boost::shared_ptr<FileSource> fs
4915 = boost::dynamic_pointer_cast<FileSource>(i->second);
4917 if (fs && fs->origin() == path) {
4926 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4928 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4929 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4931 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4936 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4938 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4940 if (Glib::path_is_absolute (filepath)) {
4942 /* rip the session dir from the audiofile source */
4944 string session_path;
4945 bool in_another_session = true;
4947 if (filepath.find (interchange_dir_string) != string::npos) {
4949 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4950 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4951 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4952 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4954 /* see if it is within our session */
4956 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4957 if (i->path == session_path) {
4958 in_another_session = false;
4963 in_another_session = false;
4967 if (in_another_session) {
4968 SessionDirectory sd (session_path);
4969 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4973 /* 1) if file belongs to this session
4974 * it may be a relative path (interchange/...)
4975 * or just basename (session_state, remove source)
4976 * -> just use the basename
4978 std::string filename = Glib::path_get_basename (filepath);
4981 /* 2) if the file is outside our session dir:
4982 * (imported but not copied) add the path for check-summming */
4984 path = Glib::path_get_dirname (filepath);
4987 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4991 Session::new_audio_source_path_for_embedded (const std::string& path)
4995 * we know that the filename is already unique because it exists
4996 * out in the filesystem.
4998 * However, when we bring it into the session, we could get a
5001 * Eg. two embedded files:
5006 * When merged into session, these collide.
5008 * There will not be a conflict with in-memory sources
5009 * because when the source was created we already picked
5010 * a unique name for it.
5012 * This collision is not likely to be common, but we have to guard
5013 * against it. So, if there is a collision, take the md5 hash of the
5014 * the path, and use that as the filename instead.
5017 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5018 string base = Glib::path_get_basename (path);
5019 string newpath = Glib::build_filename (sdir.sound_path(), base);
5021 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5025 md5.digestString (path.c_str());
5026 md5.writeToString ();
5027 base = md5.digestChars;
5029 string ext = get_suffix (path);
5036 newpath = Glib::build_filename (sdir.sound_path(), base);
5038 /* if this collides, we're screwed */
5040 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5041 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5050 /** Return true if there are no audio file sources that use @param name as
5051 * the filename component of their path.
5053 * Return false otherwise.
5055 * This method MUST ONLY be used to check in-session, mono files since it
5056 * hard-codes the channel of the audio file source we are looking for as zero.
5058 * If/when Ardour supports native files in non-mono formats, the logic here
5059 * will need to be revisited.
5062 Session::audio_source_name_is_unique (const string& name)
5064 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5065 vector<space_and_path>::iterator i;
5066 uint32_t existing = 0;
5068 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5070 /* note that we search *without* the extension so that
5071 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5072 in the event that this new name is required for
5073 a file format change.
5076 const string spath = *i;
5078 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5083 /* it is possible that we have the path already
5084 * assigned to a source that has not yet been written
5085 * (ie. the write source for a diskstream). we have to
5086 * check this in order to make sure that our candidate
5087 * path isn't used again, because that can lead to
5088 * two Sources point to the same file with different
5089 * notions of their removability.
5093 string possible_path = Glib::build_filename (spath, name);
5095 if (audio_source_by_path_and_channel (possible_path, 0)) {
5101 return (existing == 0);
5105 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)
5108 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5110 if (Profile->get_trx() && destructive) {
5112 sstr << setfill ('0') << setw (4) << cnt;
5113 sstr << legalized_base;
5115 sstr << legalized_base;
5117 if (take_required || related_exists) {
5129 } else if (nchan > 2) {
5134 /* XXX what? more than 26 channels! */
5145 /** Return a unique name based on \a base for a new internal audio source */
5147 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5150 string possible_name;
5151 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5153 bool some_related_source_name_exists = false;
5155 legalized = legalize_for_path (base);
5157 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5159 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5161 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5163 if (audio_source_name_is_unique (possible_name)) {
5167 some_related_source_name_exists = true;
5170 error << string_compose(
5171 _("There are already %1 recordings for %2, which I consider too many."),
5172 limit, base) << endmsg;
5174 throw failed_constructor();
5178 /* We've established that the new name does not exist in any session
5179 * directory, so now find out which one we should use for this new
5183 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5185 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5190 /** Return a unique name based on `base` for a new internal MIDI source */
5192 Session::new_midi_source_path (const string& base, bool need_lock)
5194 string possible_path;
5195 string possible_name;
5197 possible_name = legalize_for_path (base);
5199 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5200 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5202 /* - the main session folder is the first in the vector.
5203 * - after checking all locations for file-name uniqueness,
5204 * we keep the one from the last iteration as new file name
5205 * - midi files are small and should just be kept in the main session-folder
5207 * -> reverse the array, check main session folder last and use that as location
5210 std::reverse(sdirs.begin(), sdirs.end());
5213 possible_name = bump_name_once (possible_name, '-');
5215 vector<space_and_path>::iterator i;
5216 uint32_t existing = 0;
5218 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5220 possible_path = Glib::build_filename (*i, possible_name + ".mid");
5222 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5226 if (midi_source_by_path (possible_path, need_lock)) {
5231 if (possible_path.size () >= PATH_MAX) {
5232 error << string_compose(
5233 _("There are already many recordings for %1, resulting in a too long file-path %2."),
5234 base, possible_path) << endmsg;
5239 if (existing == 0) {
5244 /* No need to "find best location" for software/app-based RAID, because
5245 MIDI is so small that we always put it in the same place.
5248 return possible_path;
5252 /** Create a new within-session audio source */
5253 boost::shared_ptr<AudioFileSource>
5254 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5256 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5258 if (!path.empty()) {
5259 return boost::dynamic_pointer_cast<AudioFileSource> (
5260 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, sample_rate(), true, true));
5262 throw failed_constructor ();
5266 /** Create a new within-session MIDI source */
5267 boost::shared_ptr<MidiSource>
5268 Session::create_midi_source_for_session (string const & basic_name)
5270 const string path = new_midi_source_path (basic_name);
5272 if (!path.empty()) {
5273 return boost::dynamic_pointer_cast<SMFSource> (
5274 SourceFactory::createWritable (
5275 DataType::MIDI, *this, path, false, sample_rate()));
5277 throw failed_constructor ();
5281 /** Create a new within-session MIDI source */
5282 boost::shared_ptr<MidiSource>
5283 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5285 /* the caller passes in the track the source will be used in,
5286 so that we can keep the numbering sane.
5288 Rationale: a track with the name "Foo" that has had N
5289 captures carried out so far will ALREADY have a write source
5290 named "Foo-N+1.mid" waiting to be used for the next capture.
5292 If we call new_midi_source_name() we will get "Foo-N+2". But
5293 there is no region corresponding to "Foo-N+1", so when
5294 "Foo-N+2" appears in the track, the gap presents the user
5295 with odd behaviour - why did it skip past Foo-N+1?
5297 We could explain this to the user in some odd way, but
5298 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5301 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5304 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5306 std::string name = track->steal_write_source_name ();
5309 return boost::shared_ptr<MidiSource>();
5312 /* MIDI files are small, just put them in the first location of the
5313 session source search path.
5316 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5318 return boost::dynamic_pointer_cast<SMFSource> (
5319 SourceFactory::createWritable (
5320 DataType::MIDI, *this, path, false, sample_rate()));
5325 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5327 if (playlist->hidden()) {
5331 playlists->add (playlist);
5334 playlist->release();
5341 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5343 if (deletion_in_progress ()) {
5347 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5353 playlists->remove (playlist);
5359 Session::set_audition (boost::shared_ptr<Region> r)
5361 pending_audition_region = r;
5362 add_post_transport_work (PostTransportAudition);
5363 _butler->schedule_transport_work ();
5367 Session::audition_playlist ()
5369 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5370 ev->region.reset ();
5376 Session::register_lua_function (
5377 const std::string& name,
5378 const std::string& script,
5379 const LuaScriptParamList& args
5382 Glib::Threads::Mutex::Lock lm (lua_lock);
5384 lua_State* L = lua.getState();
5386 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5387 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5388 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5389 if ((*i)->optional && !(*i)->is_set) { continue; }
5390 tbl_arg[(*i)->name] = (*i)->value;
5392 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5395 LuaScriptsChanged (); /* EMIT SIGNAL */
5400 Session::unregister_lua_function (const std::string& name)
5402 Glib::Threads::Mutex::Lock lm (lua_lock);
5403 (*_lua_del)(name); // throws luabridge::LuaException
5404 lua.collect_garbage ();
5407 LuaScriptsChanged (); /* EMIT SIGNAL */
5411 std::vector<std::string>
5412 Session::registered_lua_functions ()
5414 Glib::Threads::Mutex::Lock lm (lua_lock);
5415 std::vector<std::string> rv;
5418 luabridge::LuaRef list ((*_lua_list)());
5419 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5420 if (!i.key ().isString ()) { assert(0); continue; }
5421 rv.push_back (i.key ().cast<std::string> ());
5428 static void _lua_print (std::string s) {
5429 std::cout << "SessionLua: " << s << "\n";
5434 Session::try_run_lua (pframes_t nframes)
5436 if (_n_lua_scripts == 0) return;
5437 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5439 try { (*_lua_run)(nframes); } catch (...) { }
5440 lua.collect_garbage_step ();
5445 Session::setup_lua ()
5448 lua.Print.connect (&_lua_print);
5452 "function ArdourSession ()"
5453 " local self = { scripts = {}, instances = {} }"
5455 " local remove = function (n)"
5456 " self.scripts[n] = nil"
5457 " self.instances[n] = nil"
5458 " Session:scripts_changed()" // call back
5461 " local addinternal = function (n, f, a)"
5462 " assert(type(n) == 'string', 'function-name must be string')"
5463 " assert(type(f) == 'function', 'Given script is a not a function')"
5464 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5465 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5466 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5467 " 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 }"
5468 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5469 " Session:scripts_changed()" // call back
5472 " local add = function (n, b, a)"
5473 " assert(type(b) == 'string', 'ByteCode must be string')"
5474 " load (b)()" // assigns f
5475 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5476 " addinternal (n, load(f), a)"
5479 " local run = function (...)"
5480 " for n, s in pairs (self.instances) do"
5481 " local status, err = pcall (s, ...)"
5482 " if not status then"
5483 " print ('fn \"'.. n .. '\": ', err)"
5490 " local cleanup = function ()"
5491 " self.scripts = nil"
5492 " self.instances = nil"
5495 " local list = function ()"
5497 " for n, _ in pairs (self.scripts) do"
5503 " local function basic_serialize (o)"
5504 " if type(o) == \"number\" then"
5505 " return tostring(o)"
5507 " return string.format(\"%q\", o)"
5511 " local function serialize (name, value)"
5512 " local rv = name .. ' = '"
5514 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5515 " return rv .. basic_serialize(value) .. ' '"
5516 " elseif type(value) == \"table\" then"
5518 " for k,v in pairs(value) do"
5519 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5520 " rv = rv .. serialize(fieldname, v) .. ' '"
5521 " collectgarbage()" // string concatenation allocates a new string :(
5524 " elseif type(value) == \"function\" then"
5525 " return rv .. string.format(\"%q\", string.dump(value, true))"
5527 " error('cannot save a ' .. type(value))"
5532 " local save = function ()"
5533 " return (serialize('scripts', self.scripts))"
5536 " local restore = function (state)"
5537 " self.scripts = {}"
5539 " for n, s in pairs (scripts) do"
5540 " addinternal (n, load(s['f']), s['a'])"
5544 " return { run = run, add = add, remove = remove,"
5545 " list = list, restore = restore, save = save, cleanup = cleanup}"
5548 " sess = ArdourSession ()"
5549 " ArdourSession = nil"
5551 "function ardour () end"
5554 lua_State* L = lua.getState();
5557 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5558 lua.do_command ("sess = nil"); // hide it.
5559 lua.do_command ("collectgarbage()");
5561 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5562 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5563 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5564 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5565 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5566 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5567 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5568 } catch (luabridge::LuaException const& e) {
5569 fatal << string_compose (_("programming error: %1"),
5570 std::string ("Failed to setup session Lua interpreter") + e.what ())
5572 abort(); /*NOTREACHED*/
5574 fatal << string_compose (_("programming error: %1"),
5575 X_("Failed to setup session Lua interpreter"))
5577 abort(); /*NOTREACHED*/
5581 LuaBindings::stddef (L);
5582 LuaBindings::common (L);
5583 LuaBindings::dsp (L);
5585 luabridge::push <Session *> (L, this);
5586 lua_setglobal (L, "Session");
5590 Session::scripts_changed ()
5592 assert (!lua_lock.trylock()); // must hold lua_lock
5595 luabridge::LuaRef list ((*_lua_list)());
5597 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5598 if (!i.key ().isString ()) { assert(0); continue; }
5601 _n_lua_scripts = cnt;
5602 } catch (luabridge::LuaException const& e) {
5603 fatal << string_compose (_("programming error: %1"),
5604 std::string ("Indexing Lua Session Scripts failed.") + e.what ())
5606 abort(); /*NOTREACHED*/
5608 fatal << string_compose (_("programming error: %1"),
5609 X_("Indexing Lua Session Scripts failed."))
5611 abort(); /*NOTREACHED*/
5616 Session::non_realtime_set_audition ()
5618 assert (pending_audition_region);
5619 auditioner->audition_region (pending_audition_region);
5620 pending_audition_region.reset ();
5621 AuditionActive (true); /* EMIT SIGNAL */
5625 Session::audition_region (boost::shared_ptr<Region> r)
5627 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5633 Session::cancel_audition ()
5638 if (auditioner->auditioning()) {
5639 auditioner->cancel_audition ();
5640 AuditionActive (false); /* EMIT SIGNAL */
5645 Session::is_auditioning () const
5647 /* can be called before we have an auditioner object */
5649 return auditioner->auditioning();
5656 Session::graph_reordered ()
5658 /* don't do this stuff if we are setting up connections
5659 from a set_state() call or creating new tracks. Ditto for deletion.
5662 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5668 /* force all diskstreams to update their capture offset values to
5669 * reflect any changes in latencies within the graph.
5671 update_route_latency (false, true);
5674 /** @return Number of samples that there is disk space available to write,
5677 boost::optional<samplecnt_t>
5678 Session::available_capture_duration ()
5680 Glib::Threads::Mutex::Lock lm (space_lock);
5682 if (_total_free_4k_blocks_uncertain) {
5683 return boost::optional<samplecnt_t> ();
5686 float sample_bytes_on_disk = 4.0; // keep gcc happy
5688 switch (config.get_native_file_data_format()) {
5690 sample_bytes_on_disk = 4.0;
5694 sample_bytes_on_disk = 3.0;
5698 sample_bytes_on_disk = 2.0;
5702 /* impossible, but keep some gcc versions happy */
5703 fatal << string_compose (_("programming error: %1"),
5704 X_("illegal native file data format"))
5706 abort(); /*NOTREACHED*/
5709 double scale = 4096.0 / sample_bytes_on_disk;
5711 if (_total_free_4k_blocks * scale > (double) max_samplecnt) {
5712 return max_samplecnt;
5715 return (samplecnt_t) floor (_total_free_4k_blocks * scale);
5719 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5722 RCUWriter<BundleList> writer (_bundles);
5723 boost::shared_ptr<BundleList> b = writer.get_copy ();
5724 b->push_back (bundle);
5728 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5735 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5737 bool removed = false;
5740 RCUWriter<BundleList> writer (_bundles);
5741 boost::shared_ptr<BundleList> b = writer.get_copy ();
5742 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5744 if (i != b->end()) {
5751 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5757 boost::shared_ptr<Bundle>
5758 Session::bundle_by_name (string name) const
5760 boost::shared_ptr<BundleList> b = _bundles.reader ();
5762 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5763 if ((*i)->name() == name) {
5768 return boost::shared_ptr<Bundle> ();
5772 Session::tempo_map_changed (const PropertyChange&)
5776 playlists->update_after_tempo_map_change ();
5778 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5784 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5786 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5787 (*i)->recompute_samples_from_beat ();
5791 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5792 * the given count with the current block size.
5795 Session::ensure_buffers (ChanCount howmany)
5797 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5801 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5803 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5804 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5809 Session::next_insert_id ()
5811 /* this doesn't really loop forever. just think about it */
5814 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5815 if (!insert_bitset[n]) {
5816 insert_bitset[n] = true;
5822 /* none available, so resize and try again */
5824 insert_bitset.resize (insert_bitset.size() + 16, false);
5829 Session::next_send_id ()
5831 /* this doesn't really loop forever. just think about it */
5834 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5835 if (!send_bitset[n]) {
5836 send_bitset[n] = true;
5842 /* none available, so resize and try again */
5844 send_bitset.resize (send_bitset.size() + 16, false);
5849 Session::next_aux_send_id ()
5851 /* this doesn't really loop forever. just think about it */
5854 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5855 if (!aux_send_bitset[n]) {
5856 aux_send_bitset[n] = true;
5862 /* none available, so resize and try again */
5864 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5869 Session::next_return_id ()
5871 /* this doesn't really loop forever. just think about it */
5874 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5875 if (!return_bitset[n]) {
5876 return_bitset[n] = true;
5882 /* none available, so resize and try again */
5884 return_bitset.resize (return_bitset.size() + 16, false);
5889 Session::mark_send_id (uint32_t id)
5891 if (id >= send_bitset.size()) {
5892 send_bitset.resize (id+16, false);
5894 if (send_bitset[id]) {
5895 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5897 send_bitset[id] = true;
5901 Session::mark_aux_send_id (uint32_t id)
5903 if (id >= aux_send_bitset.size()) {
5904 aux_send_bitset.resize (id+16, false);
5906 if (aux_send_bitset[id]) {
5907 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5909 aux_send_bitset[id] = true;
5913 Session::mark_return_id (uint32_t id)
5915 if (id >= return_bitset.size()) {
5916 return_bitset.resize (id+16, false);
5918 if (return_bitset[id]) {
5919 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5921 return_bitset[id] = true;
5925 Session::mark_insert_id (uint32_t id)
5927 if (id >= insert_bitset.size()) {
5928 insert_bitset.resize (id+16, false);
5930 if (insert_bitset[id]) {
5931 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5933 insert_bitset[id] = true;
5937 Session::unmark_send_id (uint32_t id)
5939 if (id < send_bitset.size()) {
5940 send_bitset[id] = false;
5945 Session::unmark_aux_send_id (uint32_t id)
5947 if (id < aux_send_bitset.size()) {
5948 aux_send_bitset[id] = false;
5953 Session::unmark_return_id (uint32_t id)
5955 if (deletion_in_progress ()) {
5958 if (id < return_bitset.size()) {
5959 return_bitset[id] = false;
5964 Session::unmark_insert_id (uint32_t id)
5966 if (id < insert_bitset.size()) {
5967 insert_bitset[id] = false;
5972 Session::reset_native_file_format ()
5974 boost::shared_ptr<RouteList> rl = routes.reader ();
5976 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5977 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5979 /* don't save state as we do this, there's no point */
5980 _state_of_the_state = StateOfTheState (_state_of_the_state | InCleanup);
5981 tr->reset_write_sources (false);
5982 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5988 Session::route_name_unique (string n) const
5990 boost::shared_ptr<RouteList> r = routes.reader ();
5992 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5993 if ((*i)->name() == n) {
6002 Session::route_name_internal (string n) const
6004 if (auditioner && auditioner->name() == n) {
6008 if (_click_io && _click_io->name() == n) {
6016 Session::freeze_all (InterThreadInfo& itt)
6018 boost::shared_ptr<RouteList> r = routes.reader ();
6020 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6022 boost::shared_ptr<Track> t;
6024 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6025 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6035 boost::shared_ptr<Region>
6036 Session::write_one_track (Track& track, samplepos_t start, samplepos_t end,
6037 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6038 InterThreadInfo& itt,
6039 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6040 bool for_export, bool for_freeze)
6042 boost::shared_ptr<Region> result;
6043 boost::shared_ptr<Playlist> playlist;
6044 boost::shared_ptr<Source> source;
6045 ChanCount diskstream_channels (track.n_channels());
6046 samplepos_t position;
6047 samplecnt_t this_chunk;
6049 samplepos_t latency_skip;
6051 samplepos_t len = end - start;
6052 bool need_block_size_reset = false;
6053 ChanCount const max_proc = track.max_processor_streams ();
6054 string legal_playlist_name;
6055 string possible_path;
6058 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
6059 end, start) << endmsg;
6063 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
6064 include_endpoint, for_export, for_freeze);
6066 if (diskstream_channels.n(track.data_type()) < 1) {
6067 error << _("Cannot write a range with no data.") << endmsg;
6071 // block all process callback handling
6073 block_processing ();
6076 // synchronize with AudioEngine::process_callback()
6077 // make sure processing is not currently running
6078 // and processing_blocked() is honored before
6079 // acquiring thread buffers
6080 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6083 _bounce_processing_active = true;
6085 /* call tree *MUST* hold route_lock */
6087 if ((playlist = track.playlist()) == 0) {
6091 legal_playlist_name = legalize_for_path (playlist->name());
6093 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
6095 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6096 string path = ((track.data_type() == DataType::AUDIO)
6097 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6098 : new_midi_source_path (legal_playlist_name));
6105 source = SourceFactory::createWritable (track.data_type(), *this, path, false, sample_rate());
6108 catch (failed_constructor& err) {
6109 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6113 srcs.push_back (source);
6116 /* tell redirects that care that we are about to use a much larger
6117 * blocksize. this will flush all plugins too, so that they are ready
6118 * to be used for this process.
6121 need_block_size_reset = true;
6122 track.set_block_size (bounce_chunk_size);
6123 _engine.main_thread()->get_buffers ();
6127 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6129 /* create a set of reasonably-sized buffers */
6130 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6131 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6133 buffers.set_count (max_proc);
6135 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6136 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6137 boost::shared_ptr<MidiSource> ms;
6139 afs->prepare_for_peakfile_writes ();
6140 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6141 Source::Lock lock(ms->mutex());
6142 ms->mark_streaming_write_started(lock);
6146 while (to_do && !itt.cancel) {
6148 this_chunk = min (to_do, bounce_chunk_size);
6150 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6154 start += this_chunk;
6155 to_do -= this_chunk;
6156 itt.progress = (float) (1.0 - ((double) to_do / len));
6158 if (latency_skip >= bounce_chunk_size) {
6159 latency_skip -= bounce_chunk_size;
6163 const samplecnt_t current_chunk = this_chunk - latency_skip;
6166 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6167 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6168 boost::shared_ptr<MidiSource> ms;
6171 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6174 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6175 Source::Lock lock(ms->mutex());
6177 const MidiBuffer& buf = buffers.get_midi(0);
6178 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6179 Evoral::Event<samplepos_t> ev = *i;
6180 ev.set_time(ev.time() - position);
6181 ms->append_event_samples(lock, ev, ms->timeline_position());
6188 /* post-roll, pick up delayed processor output */
6189 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6191 while (latency_skip && !itt.cancel) {
6192 this_chunk = min (latency_skip, bounce_chunk_size);
6193 latency_skip -= this_chunk;
6195 buffers.silence (this_chunk, 0);
6196 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6199 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6200 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6203 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6215 xnow = localtime (&now);
6217 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6218 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6219 boost::shared_ptr<MidiSource> ms;
6222 afs->update_header (position, *xnow, now);
6223 afs->flush_header ();
6224 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6225 Source::Lock lock(ms->mutex());
6226 ms->mark_streaming_write_completed(lock);
6230 /* construct a region to represent the bounced material */
6234 plist.add (Properties::start, 0);
6235 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6236 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6238 result = RegionFactory::create (srcs, plist);
6244 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6245 (*src)->mark_for_remove ();
6246 (*src)->drop_references ();
6250 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6251 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6254 afs->done_with_peakfile_writes ();
6258 _bounce_processing_active = false;
6260 if (need_block_size_reset) {
6261 _engine.main_thread()->drop_buffers ();
6262 track.set_block_size (get_block_size());
6265 unblock_processing ();
6271 Session::gain_automation_buffer() const
6273 return ProcessThread::gain_automation_buffer ();
6277 Session::trim_automation_buffer() const
6279 return ProcessThread::trim_automation_buffer ();
6283 Session::send_gain_automation_buffer() const
6285 return ProcessThread::send_gain_automation_buffer ();
6289 Session::scratch_automation_buffer() const
6291 return ProcessThread::scratch_automation_buffer ();
6295 Session::pan_automation_buffer() const
6297 return ProcessThread::pan_automation_buffer ();
6301 Session::get_silent_buffers (ChanCount count)
6303 return ProcessThread::get_silent_buffers (count);
6307 Session::get_scratch_buffers (ChanCount count, bool silence)
6309 return ProcessThread::get_scratch_buffers (count, silence);
6313 Session::get_noinplace_buffers (ChanCount count)
6315 return ProcessThread::get_noinplace_buffers (count);
6319 Session::get_route_buffers (ChanCount count, bool silence)
6321 return ProcessThread::get_route_buffers (count, silence);
6326 Session::get_mix_buffers (ChanCount count)
6328 return ProcessThread::get_mix_buffers (count);
6332 Session::ntracks () const
6335 boost::shared_ptr<RouteList> r = routes.reader ();
6337 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6338 if (boost::dynamic_pointer_cast<Track> (*i)) {
6347 Session::nbusses () const
6350 boost::shared_ptr<RouteList> r = routes.reader ();
6352 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6353 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6362 Session::nstripables (bool with_monitor) const
6364 uint32_t rv = routes.reader()->size ();
6365 rv += _vca_manager->vcas ().size ();
6379 Session::add_automation_list(AutomationList *al)
6381 automation_lists[al->id()] = al;
6384 /** @return true if there is at least one record-enabled track, otherwise false */
6386 Session::have_rec_enabled_track () const
6388 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6392 Session::have_rec_disabled_track () const
6394 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6397 /** Update the state of our rec-enabled tracks flag */
6399 Session::update_route_record_state ()
6401 boost::shared_ptr<RouteList> rl = routes.reader ();
6402 RouteList::iterator i = rl->begin();
6403 while (i != rl->end ()) {
6405 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6406 if (tr && tr->rec_enable_control()->get_value()) {
6413 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6415 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6417 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6418 RecordStateChanged (); /* EMIT SIGNAL */
6421 for (i = rl->begin(); i != rl->end (); ++i) {
6422 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6423 if (tr && !tr->rec_enable_control()->get_value()) {
6428 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6430 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6432 if (record_status() == Recording && record_arm_state_changed ) {
6433 RecordArmStateChanged ();
6439 Session::listen_position_changed ()
6442 /* skip duing session restore (already taken care of) */
6445 ProcessorChangeBlocker pcb (this);
6446 boost::shared_ptr<RouteList> r = routes.reader ();
6447 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6448 (*i)->listen_position_changed ();
6453 Session::solo_control_mode_changed ()
6455 if (soloing() || listening()) {
6457 /* We can't use ::clear_all_solo_state() here because during
6458 session loading at program startup, that will queue a call
6459 to rt_clear_all_solo_state() that will not execute until
6460 AFTER solo states have been established (thus throwing away
6461 the session's saved solo state). So just explicitly turn
6464 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6466 clear_all_solo_state (get_routes());
6471 /** Called when a property of one of our route groups changes */
6473 Session::route_group_property_changed (RouteGroup* rg)
6475 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6478 /** Called when a route is added to one of our route groups */
6480 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6482 RouteAddedToRouteGroup (rg, r);
6485 /** Called when a route is removed from one of our route groups */
6487 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6489 update_route_record_state ();
6490 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6492 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6493 remove_route_group (*rg);
6497 boost::shared_ptr<AudioTrack>
6498 Session::get_nth_audio_track (int nth) const
6500 boost::shared_ptr<RouteList> rl = routes.reader ();
6501 rl->sort (Stripable::Sorter ());
6503 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6504 if (!boost::dynamic_pointer_cast<AudioTrack> (*r)) {
6511 return boost::dynamic_pointer_cast<AudioTrack> (*r);
6513 return boost::shared_ptr<AudioTrack> ();
6516 boost::shared_ptr<RouteList>
6517 Session::get_tracks () const
6519 boost::shared_ptr<RouteList> rl = routes.reader ();
6520 boost::shared_ptr<RouteList> tl (new RouteList);
6522 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6523 if (boost::dynamic_pointer_cast<Track> (*r)) {
6524 assert (!(*r)->is_auditioner()); // XXX remove me
6531 boost::shared_ptr<RouteList>
6532 Session::get_routes_with_regions_at (samplepos_t const p) const
6534 boost::shared_ptr<RouteList> r = routes.reader ();
6535 boost::shared_ptr<RouteList> rl (new RouteList);
6537 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6538 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6543 boost::shared_ptr<Playlist> pl = tr->playlist ();
6548 if (pl->has_region_at (p)) {
6557 Session::goto_end ()
6559 if (_session_range_location) {
6560 request_locate (_session_range_location->end(), false);
6562 request_locate (0, false);
6567 Session::goto_start (bool and_roll)
6569 if (_session_range_location) {
6570 request_locate (_session_range_location->start(), and_roll);
6572 request_locate (0, and_roll);
6577 Session::current_start_sample () const
6579 return _session_range_location ? _session_range_location->start() : 0;
6583 Session::current_end_sample () const
6585 return _session_range_location ? _session_range_location->end() : 0;
6589 Session::set_session_range_location (samplepos_t start, samplepos_t end)
6591 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6592 _locations->add (_session_range_location);
6596 Session::step_edit_status_change (bool yn)
6602 send = (_step_editors == 0);
6607 send = (_step_editors == 1);
6610 if (_step_editors > 0) {
6616 StepEditStatusChange (val);
6622 Session::start_time_changed (samplepos_t old)
6624 /* Update the auto loop range to match the session range
6625 (unless the auto loop range has been changed by the user)
6628 Location* s = _locations->session_range_location ();
6633 Location* l = _locations->auto_loop_location ();
6635 if (l && l->start() == old) {
6636 l->set_start (s->start(), true);
6642 Session::end_time_changed (samplepos_t old)
6644 /* Update the auto loop range to match the session range
6645 (unless the auto loop range has been changed by the user)
6648 Location* s = _locations->session_range_location ();
6653 Location* l = _locations->auto_loop_location ();
6655 if (l && l->end() == old) {
6656 l->set_end (s->end(), true);
6661 std::vector<std::string>
6662 Session::source_search_path (DataType type) const
6666 if (session_dirs.size() == 1) {
6668 case DataType::AUDIO:
6669 sp.push_back (_session_dir->sound_path());
6671 case DataType::MIDI:
6672 sp.push_back (_session_dir->midi_path());
6676 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6677 SessionDirectory sdir (i->path);
6679 case DataType::AUDIO:
6680 sp.push_back (sdir.sound_path());
6682 case DataType::MIDI:
6683 sp.push_back (sdir.midi_path());
6689 if (type == DataType::AUDIO) {
6690 const string sound_path_2X = _session_dir->sound_path_2X();
6691 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6692 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6693 sp.push_back (sound_path_2X);
6698 // now check the explicit (possibly user-specified) search path
6701 case DataType::AUDIO:
6702 sp += Searchpath(config.get_audio_search_path ());
6704 case DataType::MIDI:
6705 sp += Searchpath(config.get_midi_search_path ());
6713 Session::ensure_search_path_includes (const string& path, DataType type)
6722 case DataType::AUDIO:
6723 sp += Searchpath(config.get_audio_search_path ());
6725 case DataType::MIDI:
6726 sp += Searchpath (config.get_midi_search_path ());
6730 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6731 /* No need to add this new directory if it has the same inode as
6732 an existing one; checking inode rather than name prevents duplicated
6733 directories when we are using symlinks.
6735 On Windows, I think we could just do if (*i == path) here.
6737 if (PBD::equivalent_paths (*i, path)) {
6745 case DataType::AUDIO:
6746 config.set_audio_search_path (sp.to_string());
6748 case DataType::MIDI:
6749 config.set_midi_search_path (sp.to_string());
6755 Session::remove_dir_from_search_path (const string& dir, DataType type)
6760 case DataType::AUDIO:
6761 sp = Searchpath(config.get_audio_search_path ());
6763 case DataType::MIDI:
6764 sp = Searchpath (config.get_midi_search_path ());
6771 case DataType::AUDIO:
6772 config.set_audio_search_path (sp.to_string());
6774 case DataType::MIDI:
6775 config.set_midi_search_path (sp.to_string());
6781 boost::shared_ptr<Speakers>
6782 Session::get_speakers()
6788 Session::unknown_processors () const
6792 boost::shared_ptr<RouteList> r = routes.reader ();
6793 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6794 list<string> t = (*i)->unknown_processors ();
6795 copy (t.begin(), t.end(), back_inserter (p));
6805 Session::set_worst_io_latencies_x (IOChange, void *)
6807 set_worst_io_latencies ();
6811 Session::send_latency_compensation_change ()
6813 /* As a result of Send::set_output_latency()
6814 * or InternalReturn::set_playback_offset ()
6815 * the send's own latency can change (source track
6816 * is aligned with target bus).
6818 * This can only happen be triggered by
6819 * Route::update_signal_latency ()
6820 * when updating the processor latency.
6822 * We need to walk the graph again to take those changes into account
6823 * (we should probably recurse or process the graph in a 2 step process).
6825 ++_send_latency_changes;
6829 Session::update_route_latency (bool playback, bool apply_to_delayline)
6831 /* Note: RouteList is process-graph sorted */
6832 boost::shared_ptr<RouteList> r = routes.reader ();
6835 /* reverse the list so that we work backwards from the last route to run to the first,
6836 * this is not needed, but can help to reduce the iterations for aux-sends.
6838 RouteList* rl = routes.reader().get();
6839 r.reset (new RouteList (*rl));
6840 reverse (r->begin(), r->end());
6843 bool changed = false;
6846 _send_latency_changes = 0;
6847 _worst_route_latency = 0;
6849 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6850 // if (!(*i)->active()) { continue ; } // TODO
6852 if ((*i)->signal_latency () != (l = (*i)->update_signal_latency (apply_to_delayline))) {
6855 _worst_route_latency = std::max (l, _worst_route_latency);
6858 if (_send_latency_changes > 0) {
6859 // only 1 extra iteration is needed (we allow only 1 level of aux-sends)
6860 // BUT.. jack'n'sends'n'bugs
6861 if (++bailout < 5) {
6862 cerr << "restarting Session::update_latency. # of send changes: " << _send_latency_changes << " iteration: " << bailout << endl;
6867 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_route_latency, (changed ? "yes" : "no")));
6873 Session::update_latency (bool playback)
6875 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6877 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _route_deletion_in_progress) {
6880 if (!_engine.running()) {
6884 /* Note; RouteList is sorted as process-graph */
6885 boost::shared_ptr<RouteList> r = routes.reader ();
6888 /* reverse the list so that we work backwards from the last route to run to the first */
6889 RouteList* rl = routes.reader().get();
6890 r.reset (new RouteList (*rl));
6891 reverse (r->begin(), r->end());
6894 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6895 samplecnt_t latency = (*i)->set_private_port_latencies (playback);
6896 (*i)->set_public_port_latencies (latency, playback);
6900 set_worst_output_latency ();
6901 update_route_latency (true, true);
6903 set_worst_input_latency ();
6904 update_route_latency (false, false);
6907 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6911 Session::initialize_latencies ()
6914 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6915 update_latency (false);
6916 update_latency (true);
6919 set_worst_io_latencies ();
6923 Session::set_worst_io_latencies ()
6925 set_worst_output_latency ();
6926 set_worst_input_latency ();
6930 Session::set_worst_output_latency ()
6932 if (inital_connect_or_deletion_in_progress ()) {
6936 _worst_output_latency = 0;
6938 if (!_engine.running()) {
6942 boost::shared_ptr<RouteList> r = routes.reader ();
6944 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6945 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6948 _worst_output_latency = max (_worst_output_latency, _click_io->latency());
6950 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6954 Session::set_worst_input_latency ()
6956 if (inital_connect_or_deletion_in_progress ()) {
6960 _worst_input_latency = 0;
6962 if (!_engine.running()) {
6966 boost::shared_ptr<RouteList> r = routes.reader ();
6968 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6969 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6972 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6976 Session::update_latency_compensation (bool force_whole_graph)
6978 if (inital_connect_or_deletion_in_progress ()) {
6981 /* this lock is not usually contended, but under certain conditions,
6982 * update_latency_compensation may be called concurrently.
6983 * e.g. drag/drop copy a latent plugin while rolling.
6984 * GUI thread (via route_processors_changed) and
6985 * auto_connect_thread_run may race.
6987 Glib::Threads::Mutex::Lock lx (_update_latency_lock, Glib::Threads::TRY_LOCK);
6989 /* no need to do this twice */
6993 bool some_track_latency_changed = update_route_latency (false, false);
6995 if (some_track_latency_changed || force_whole_graph) {
6996 _engine.update_latencies ();
6997 /* above call will ask the backend up update its latencies, which
6998 * eventually will trigger AudioEngine::latency_callback () and
6999 * call Session::update_latency ()
7002 boost::shared_ptr<RouteList> r = routes.reader ();
7003 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7004 (*i)->apply_latency_compensation ();
7010 Session::session_name_is_legal (const string& path)
7012 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7014 for (int i = 0; illegal_chars[i]; ++i) {
7015 if (path.find (illegal_chars[i]) != string::npos) {
7016 return illegal_chars[i];
7024 Session::notify_presentation_info_change ()
7026 if (deletion_in_progress()) {
7030 reassign_track_numbers();
7032 #ifdef USE_TRACKS_CODE_FEATURES
7033 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7034 * if track order has been changed by user
7036 reconnect_existing_routes(true, true);
7042 Session::operation_in_progress (GQuark op) const
7044 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7047 boost::shared_ptr<Port>
7048 Session::ltc_output_port () const
7050 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
7054 Session::reconnect_ltc_output ()
7058 string src = Config->get_ltc_output_port();
7060 _ltc_output->disconnect (this);
7062 if (src != _("None") && !src.empty()) {
7063 _ltc_output->nth (0)->connect (src);
7069 Session::set_range_selection (samplepos_t start, samplepos_t end)
7071 _range_selection = Evoral::Range<samplepos_t> (start, end);
7072 #ifdef USE_TRACKS_CODE_FEATURES
7073 follow_playhead_priority ();
7078 Session::set_object_selection (samplepos_t start, samplepos_t end)
7080 _object_selection = Evoral::Range<samplepos_t> (start, end);
7081 #ifdef USE_TRACKS_CODE_FEATURES
7082 follow_playhead_priority ();
7087 Session::clear_range_selection ()
7089 _range_selection = Evoral::Range<samplepos_t> (-1,-1);
7090 #ifdef USE_TRACKS_CODE_FEATURES
7091 follow_playhead_priority ();
7096 Session::clear_object_selection ()
7098 _object_selection = Evoral::Range<samplepos_t> (-1,-1);
7099 #ifdef USE_TRACKS_CODE_FEATURES
7100 follow_playhead_priority ();
7105 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7106 const ChanCount& input_start,
7107 const ChanCount& output_start,
7108 const ChanCount& input_offset,
7109 const ChanCount& output_offset)
7111 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7112 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7113 input_start, output_start,
7114 input_offset, output_offset));
7116 auto_connect_thread_wakeup ();
7120 Session::auto_connect_thread_wakeup ()
7122 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7123 pthread_cond_signal (&_auto_connect_cond);
7124 pthread_mutex_unlock (&_auto_connect_mutex);
7129 Session::queue_latency_recompute ()
7131 g_atomic_int_inc (&_latency_recompute_pending);
7132 auto_connect_thread_wakeup ();
7136 Session::auto_connect (const AutoConnectRequest& ar)
7138 boost::shared_ptr<Route> route = ar.route.lock();
7140 if (!route) { return; }
7142 if (!IO::connecting_legal) {
7146 /* If both inputs and outputs are auto-connected to physical ports,
7147 * use the max of input and output offsets to ensure auto-connected
7148 * port numbers always match up (e.g. the first audio input and the
7149 * first audio output of the route will have the same physical
7150 * port number). Otherwise just use the lowest input or output
7154 const bool in_out_physical =
7155 (Config->get_input_auto_connect() & AutoConnectPhysical)
7156 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7157 && ar.connect_inputs;
7159 const ChanCount in_offset = in_out_physical
7160 ? ChanCount::max(ar.input_offset, ar.output_offset)
7163 const ChanCount out_offset = in_out_physical
7164 ? ChanCount::max(ar.input_offset, ar.output_offset)
7167 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7168 vector<string> physinputs;
7169 vector<string> physoutputs;
7172 /* for connecting track inputs we only want MIDI ports marked
7176 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7178 if (!physinputs.empty() && ar.connect_inputs) {
7179 uint32_t nphysical_in = physinputs.size();
7181 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7184 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7185 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7188 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7194 if (!physoutputs.empty()) {
7195 uint32_t nphysical_out = physoutputs.size();
7196 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7200 * do not create new connections if we reached the limit of physical outputs
7203 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7204 ARDOUR::Profile->get_trx () &&
7205 ar.output_offset.get(*t) == nphysical_out ) {
7209 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7210 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7211 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7212 /* master bus is audio only */
7213 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7214 port = _master_out->input()->ports().port(*t,
7215 i % _master_out->input()->n_ports().get(*t))->name();
7219 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7228 Session::auto_connect_thread_start ()
7230 if (g_atomic_int_get (&_ac_thread_active)) {
7234 while (!_auto_connect_queue.empty ()) {
7235 _auto_connect_queue.pop ();
7238 g_atomic_int_set (&_ac_thread_active, 1);
7239 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7240 g_atomic_int_set (&_ac_thread_active, 0);
7245 Session::auto_connect_thread_terminate ()
7247 if (!g_atomic_int_get (&_ac_thread_active)) {
7252 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7253 while (!_auto_connect_queue.empty ()) {
7254 _auto_connect_queue.pop ();
7258 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7259 * fail to wakeup the thread.
7262 pthread_mutex_lock (&_auto_connect_mutex);
7263 g_atomic_int_set (&_ac_thread_active, 0);
7264 pthread_cond_signal (&_auto_connect_cond);
7265 pthread_mutex_unlock (&_auto_connect_mutex);
7268 pthread_join (_auto_connect_thread, &status);
7272 Session::auto_connect_thread (void *arg)
7274 Session *s = static_cast<Session *>(arg);
7275 s->auto_connect_thread_run ();
7281 Session::auto_connect_thread_run ()
7283 pthread_set_name (X_("autoconnect"));
7284 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7285 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7286 pthread_mutex_lock (&_auto_connect_mutex);
7287 while (g_atomic_int_get (&_ac_thread_active)) {
7289 if (!_auto_connect_queue.empty ()) {
7290 // Why would we need the process lock ??
7291 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7292 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7293 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7294 // We have control over those, but what does jack do?
7295 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7297 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7298 while (!_auto_connect_queue.empty ()) {
7299 const AutoConnectRequest ar (_auto_connect_queue.front());
7300 _auto_connect_queue.pop ();
7307 if (!actively_recording ()) { // might not be needed,
7308 /* this is only used for updating plugin latencies, the
7309 * graph does not change. so it's safe in general.
7311 * update_latency_compensation ()
7312 * calls DiskWriter::set_capture_offset () which
7313 * modifies the capture-offset, which can be a problem.
7315 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7316 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7317 update_latency_compensation ();
7322 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7323 // jack1 cannot cope with removing ports while processing
7324 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7325 AudioEngine::instance()->clear_pending_port_deletions ();
7328 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7330 pthread_mutex_unlock (&_auto_connect_mutex);
7334 Session::cancel_all_solo ()
7338 get_stripables (sl);
7340 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7341 clear_all_solo_state (routes.reader());
7345 Session::maybe_update_tempo_from_midiclock_tempo (float bpm)
7347 if (_tempo_map->n_tempos() == 1) {
7348 TempoSection& ts (_tempo_map->tempo_section_at_sample (0));
7349 if (fabs (ts.note_types_per_minute() - bpm) > (0.01 * ts.note_types_per_minute())) {
7350 const Tempo tempo (bpm, 4.0, bpm);
7351 std::cerr << "new tempo " << bpm << " old " << ts.note_types_per_minute() << std::endl;
7352 _tempo_map->replace_tempo (ts, tempo, 0.0, 0.0, AudioTime);