2 Copyright (C) 1999-2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
36 #include <boost/algorithm/string/erase.hpp>
38 #include "pbd/basename.h"
39 #include "pbd/convert.h"
40 #include "pbd/error.h"
41 #include "pbd/file_utils.h"
43 #include "pbd/pthread_utils.h"
44 #include "pbd/search_path.h"
45 #include "pbd/stacktrace.h"
46 #include "pbd/stl_delete.h"
47 #include "pbd/replace_all.h"
48 #include "pbd/types_convert.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/boost_debug.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/disk_reader.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
74 #include "ardour/filename_extensions.h"
75 #include "ardour/gain_control.h"
76 #include "ardour/graph.h"
77 #include "ardour/luabindings.h"
78 #include "ardour/midiport_manager.h"
79 #include "ardour/scene_changer.h"
80 #include "ardour/midi_patch_manager.h"
81 #include "ardour/midi_track.h"
82 #include "ardour/midi_ui.h"
83 #include "ardour/operations.h"
84 #include "ardour/playlist.h"
85 #include "ardour/playlist_factory.h"
86 #include "ardour/plugin.h"
87 #include "ardour/plugin_insert.h"
88 #include "ardour/process_thread.h"
89 #include "ardour/profile.h"
90 #include "ardour/rc_configuration.h"
91 #include "ardour/recent_sessions.h"
92 #include "ardour/region.h"
93 #include "ardour/region_factory.h"
94 #include "ardour/revision.h"
95 #include "ardour/route_graph.h"
96 #include "ardour/route_group.h"
97 #include "ardour/rt_tasklist.h"
98 #include "ardour/send.h"
99 #include "ardour/selection.h"
100 #include "ardour/session.h"
101 #include "ardour/session_directory.h"
102 #include "ardour/session_playlists.h"
103 #include "ardour/smf_source.h"
104 #include "ardour/solo_isolate_control.h"
105 #include "ardour/source_factory.h"
106 #include "ardour/speakers.h"
107 #include "ardour/tempo.h"
108 #include "ardour/ticker.h"
109 #include "ardour/transport_master.h"
110 #include "ardour/track.h"
111 #include "ardour/types_convert.h"
112 #include "ardour/user_bundle.h"
113 #include "ardour/utils.h"
114 #include "ardour/vca_manager.h"
115 #include "ardour/vca.h"
117 #include "midi++/port.h"
118 #include "midi++/mmc.h"
120 #include "LuaBridge/LuaBridge.h"
122 #include "pbd/i18n.h"
124 #include <glibmm/checksum.h>
133 using namespace ARDOUR;
136 bool Session::_disable_all_loaded_plugins = false;
137 bool Session::_bypass_all_loaded_plugins = false;
138 guint Session::_name_id_counter = 0;
140 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
141 PBD::Signal1<void,std::string> Session::Dialog;
142 PBD::Signal0<int> Session::AskAboutPendingState;
143 PBD::Signal2<int, samplecnt_t, samplecnt_t> Session::AskAboutSampleRateMismatch;
144 PBD::Signal2<void, samplecnt_t, samplecnt_t> Session::NotifyAboutSampleRateMismatch;
145 PBD::Signal0<void> Session::SendFeedback;
146 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
148 PBD::Signal1<void, samplepos_t> Session::StartTimeChanged;
149 PBD::Signal1<void, samplepos_t> Session::EndTimeChanged;
150 PBD::Signal2<void,std::string, std::string> Session::Exported;
151 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
152 PBD::Signal0<void> Session::Quit;
153 PBD::Signal0<void> Session::FeedbackDetected;
154 PBD::Signal0<void> Session::SuccessfulGraphSort;
155 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
157 const samplecnt_t Session::bounce_chunk_size = 8192;
158 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
159 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
161 // seconds should be added after the region exceeds end marker
162 #ifdef USE_TRACKS_CODE_FEATURES
163 const uint32_t Session::session_end_shift = 5;
165 const uint32_t Session::session_end_shift = 0;
168 /** @param snapshot_name Snapshot name, without .ardour suffix */
169 Session::Session (AudioEngine &eng,
170 const string& fullpath,
171 const string& snapshot_name,
172 BusProfile* bus_profile,
174 : _playlists (new SessionPlaylists)
176 , process_function (&Session::process_with_events)
177 , _bounce_processing_active (false)
178 , waiting_for_sync_offset (false)
179 , _base_sample_rate (0)
180 , _nominal_sample_rate (0)
181 , _current_sample_rate (0)
182 , transport_sub_state (0)
183 , _record_status (Disabled)
184 , _transport_sample (0)
186 , _session_range_location (0)
187 , _session_range_is_free (true)
189 , _remaining_latency_preroll (0)
190 , _engine_speed (1.0)
191 , _transport_speed (0)
192 , _default_transport_speed (1.0)
193 , _last_transport_speed (0)
194 , _signalled_varispeed (0)
195 , _target_transport_speed (0.0)
196 , auto_play_legal (false)
197 , _requested_return_sample (-1)
198 , current_block_size (0)
199 , _worst_output_latency (0)
200 , _worst_input_latency (0)
201 , _worst_route_latency (0)
202 , _send_latency_changes (0)
203 , _have_captured (false)
204 , _non_soloed_outs_muted (false)
207 , _solo_isolated_cnt (0)
209 , _was_seamless (Config->get_seamless_loop ())
210 , _under_nsm_control (false)
212 , transport_master_tracking_state (Stopped)
213 , master_wait_end (0)
214 , post_export_sync (false)
215 , post_export_position (0)
217 , _export_rolling (false)
218 , _realtime_export (false)
219 , _region_export (false)
220 , _export_preroll (0)
221 , _pre_export_mmc_enabled (false)
222 , _name (snapshot_name)
224 , _send_qf_mtc (false)
225 , _pframes_since_last_mtc (0)
227 , loop_changing (false)
229 , _session_dir (new SessionDirectory (fullpath))
230 , _current_snapshot_name (snapshot_name)
232 , state_was_pending (false)
233 , _state_of_the_state (StateOfTheState (CannotSave | InitialConnecting | Loading))
235 , _save_queued (false)
236 , _last_roll_location (0)
237 , _last_roll_or_reversal_location (0)
238 , _last_record_location (0)
239 , pending_auto_loop (false)
240 , _mempool ("Session", 3145728)
241 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
243 , _butler (new Butler (*this))
244 , _post_transport_work (0)
245 , _locations (new Locations (*this))
246 , _ignore_skips_updates (false)
247 , _rt_thread_active (false)
248 , _rt_emit_pending (false)
249 , _ac_thread_active (0)
250 , _latency_recompute_pending (0)
252 , outbound_mtc_timecode_frame (0)
253 , next_quarter_frame_to_send (-1)
254 , _samples_per_timecode_frame (0)
255 , _frames_per_hour (0)
256 , _timecode_frames_per_hour (0)
257 , last_timecode_valid (false)
258 , last_timecode_when (0)
259 , _send_timecode_update (false)
271 , ltc_timecode_offset (0)
272 , ltc_timecode_negative_offset (false)
273 , midi_control_ui (0)
275 , _all_route_group (new RouteGroup (*this, "all"))
276 , routes (new RouteList)
277 , _adding_routes_in_progress (false)
278 , _reconnecting_routes_in_progress (false)
279 , _route_deletion_in_progress (false)
280 , destructive_index (0)
281 , _track_number_decimals(1)
282 , default_fade_steepness (0)
283 , default_fade_msecs (0)
284 , _total_free_4k_blocks (0)
285 , _total_free_4k_blocks_uncertain (false)
286 , no_questions_about_missing_files (false)
289 , _bundles (new BundleList)
290 , _bundle_xml_node (0)
293 , _click_rec_only (false)
295 , click_emphasis_data (0)
297 , click_emphasis_length (0)
298 , _clicks_cleared (0)
299 , _count_in_samples (0)
300 , _play_range (false)
301 , _range_selection (-1,-1)
302 , _object_selection (-1,-1)
303 , _preroll_record_trim_len (0)
304 , _count_in_once (false)
306 , first_file_data_format_reset (true)
307 , first_file_header_format_reset (true)
308 , have_looped (false)
309 , _have_rec_enabled_track (false)
310 , _have_rec_disabled_track (true)
312 , _suspend_timecode_transmission (0)
313 , _speakers (new Speakers)
314 , _ignore_route_processor_changes (0)
319 , _vca_manager (new VCAManager (*this))
320 , _selection (new CoreSelection (*this))
321 , _global_locate_pending (false)
325 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
327 pthread_mutex_init (&_rt_emit_mutex, 0);
328 pthread_cond_init (&_rt_emit_cond, 0);
330 pthread_mutex_init (&_auto_connect_mutex, 0);
331 pthread_cond_init (&_auto_connect_cond, 0);
333 init_name_id_counter (1); // reset for new sessions, start at 1
334 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
336 pre_engine_init (fullpath); // sets _is_new
342 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
344 #ifdef USE_TRACKS_CODE_FEATURES
345 sr = EngineStateController::instance()->get_current_sample_rate();
347 if (ensure_engine (sr, true)) {
349 throw SessionException (_("Cannot connect to audio/midi engine"));
352 // set samplerate for plugins added early
353 // e.g from templates or MB channelstrip
354 set_block_size (_engine.samples_per_cycle());
355 set_sample_rate (_engine.sample_rate());
357 if (create (mix_template, bus_profile)) {
359 throw SessionException (_("Session initialization failed"));
362 /* if a mix template was provided, then ::create() will
363 * have copied it into the session and we need to load it
364 * so that we have the state ready for ::set_state()
365 * after the engine is started.
367 * Note that we do NOT try to get the sample rate from
368 * the template at this time, though doing so would
369 * be easy if we decided this was an appropriate part
373 if (!mix_template.empty()) {
375 if (load_state (_current_snapshot_name)) {
376 throw SessionException (_("Failed to load template/snapshot state"));
378 } catch (PBD::unknown_enumeration& e) {
379 throw SessionException (_("Failed to parse template/snapshot state"));
381 store_recent_templates (mix_template);
384 /* load default session properties - if any */
389 if (load_state (_current_snapshot_name)) {
390 throw SessionException (_("Failed to load state"));
393 /* try to get sample rate from XML state so that we
394 * can influence the SR if we set up the audio
399 XMLProperty const * prop;
400 XMLNode const * root (state_tree->root());
401 if ((prop = root->property (X_("sample-rate"))) != 0) {
402 sr = atoi (prop->value());
406 if (ensure_engine (sr, false)) {
408 throw SessionException (_("Cannot connect to audio/midi engine"));
412 int err = post_engine_init ();
417 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
421 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
424 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
427 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
430 throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Unexpected exception during session setup, possibly invalid audio/midi engine parameters. Please see stdout/stderr for details")));
435 store_recent_sessions (_name, _path);
437 bool was_dirty = dirty();
440 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
442 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
443 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
446 DirtyChanged (); /* EMIT SIGNAL */
449 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
450 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
452 Send::ChangedLatency.connect_same_thread (*this, boost::bind (&Session::send_latency_compensation_change, this));
454 emit_thread_start ();
455 auto_connect_thread_start ();
457 /* hook us up to the engine since we are now completely constructed */
459 BootMessage (_("Connect to engine"));
461 _engine.set_session (this);
462 _engine.reset_timebase ();
464 #ifdef USE_TRACKS_CODE_FEATURES
466 EngineStateController::instance()->set_session(this);
469 if ( ARDOUR::Profile->get_trx () ) {
471 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
472 * each available input must have corresponding track when session starts.
475 uint32_t how_many (0);
477 std::vector<std::string> inputs;
478 EngineStateController::instance()->get_physical_audio_inputs(inputs);
480 how_many = inputs.size();
482 list<boost::shared_ptr<AudioTrack> > tracks;
484 // Track names after driver
485 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
486 string track_name = "";
487 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
489 track_name = inputs[i];
490 replace_all (track_name, "system:capture", "");
492 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
493 tracks.insert(tracks.begin(), single_track.front());
495 } else { // Default track names
496 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
499 if (tracks.size() != how_many) {
501 throw failed_constructor ();
507 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
509 if (!mix_template.empty ()) {
510 /* ::create() unsets _is_new after creating the session.
511 * But for templated sessions, the sample-rate is initially unset
512 * (not read from template), so we need to save it (again).
520 BootMessage (_("Session loading complete"));
532 Session::next_name_id ()
534 return g_atomic_int_add (&_name_id_counter, 1);
538 Session::name_id_counter ()
540 return g_atomic_int_get (&_name_id_counter);
544 Session::init_name_id_counter (guint n)
546 g_atomic_int_set (&_name_id_counter, n);
550 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
552 if (_engine.current_backend() == 0) {
553 /* backend is unknown ... */
554 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
555 if (r.get_value_or (-1) != 0) {
558 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
560 } else if (_engine.setup_required()) {
561 /* backend is known, but setup is needed */
562 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
563 if (r.get_value_or (-1) != 0) {
566 } else if (!_engine.running()) {
567 if (_engine.start()) {
572 /* at this point the engine should be running */
574 if (!_engine.running()) {
578 return immediately_post_engine ();
583 Session::immediately_post_engine ()
585 /* Do various initializations that should take place directly after we
586 * know that the engine is running, but before we either create a
587 * session or set state for an existing one.
590 _rt_tasklist.reset (new RTTaskList ());
592 if (how_many_dsp_threads () > 1) {
593 /* For now, only create the graph if we are using >1 DSP threads, as
594 it is a bit slower than the old code with 1 thread.
596 _process_graph.reset (new Graph (*this));
599 /* every time we reconnect, recompute worst case output latencies */
601 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
603 if (synced_to_engine()) {
604 _engine.transport_stop ();
607 if (config.get_jack_time_master()) {
608 _engine.transport_locate (_transport_sample);
612 BootMessage (_("Set up LTC"));
614 BootMessage (_("Set up Click"));
616 BootMessage (_("Set up standard connections"));
620 catch (failed_constructor& err) {
624 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
626 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
634 vector<void*> debug_pointers;
636 /* if we got to here, leaving pending capture state around
640 remove_pending_capture_state ();
644 _state_of_the_state = StateOfTheState (CannotSave | Deletion);
647 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
651 /* disconnect from any and all signals that we are connected to */
653 Port::PortSignalDrop (); /* EMIT SIGNAL */
656 /* shutdown control surface protocols while we still have ports
657 * and the engine to move data to any devices.
660 /* remove I/O objects before unsetting the engine session */
662 _ltc_output.reset ();
664 ControlProtocolManager::instance().drop_protocols ();
666 /* stop auto dis/connecting */
667 auto_connect_thread_terminate ();
669 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
671 _engine.remove_session ();
673 #ifdef USE_TRACKS_CODE_FEATURES
674 EngineStateController::instance()->remove_session();
677 /* deregister all ports - there will be no process or any other
678 * callbacks from the engine any more.
681 Port::PortDrop (); /* EMIT SIGNAL */
684 Glib::Threads::Mutex::Lock lm (controllables_lock);
685 for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
686 (*i)->DropReferences (); /* EMIT SIGNAL */
688 controllables.clear ();
691 /* clear history so that no references to objects are held any more */
695 /* clear state tree so that no references to objects are held any more */
701 /* unregister all lua functions, drop held references (if any) */
702 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
704 lua.do_command ("Session = nil");
712 lua.collect_garbage ();
715 /* reset dynamic state version back to default */
716 Stateful::loading_state_version = 0;
718 _butler->drop_references ();
722 delete _all_route_group;
724 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
725 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
729 if (click_data != default_click) {
730 delete [] click_data;
733 if (click_emphasis_data != default_click_emphasis) {
734 delete [] click_emphasis_data;
739 /* need to remove auditioner before monitoring section
740 * otherwise it is re-connected.
741 * Note: If a session was never successfully loaded, there
742 * may not yet be an auditioner.
745 auditioner->drop_references ();
749 /* drop references to routes held by the monitoring section
750 * specifically _monitor_out aux/listen references */
751 remove_monitor_section();
753 /* clear out any pending dead wood from RCU managed objects */
758 DiskReader::free_working_buffers();
760 /* tell everyone who is still standing that we're about to die */
763 /* tell everyone to drop references and delete objects as we go */
765 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
766 RegionFactory::delete_all_regions ();
768 /* Do this early so that VCAs no longer hold references to routes */
770 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
773 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
775 /* reset these three references to special routes before we do the usual route delete thing */
777 _master_out.reset ();
778 _monitor_out.reset ();
781 RCUWriter<RouteList> writer (routes);
782 boost::shared_ptr<RouteList> r = writer.get_copy ();
784 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
785 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
786 (*i)->drop_references ();
790 /* writer goes out of scope and updates master */
795 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
796 Glib::Threads::Mutex::Lock lm (source_lock);
797 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
798 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
799 i->second->drop_references ();
805 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
808 emit_thread_terminate ();
810 pthread_cond_destroy (&_rt_emit_cond);
811 pthread_mutex_destroy (&_rt_emit_mutex);
813 pthread_cond_destroy (&_auto_connect_cond);
814 pthread_mutex_destroy (&_auto_connect_mutex);
816 delete _scene_changer; _scene_changer = 0;
817 delete midi_control_ui; midi_control_ui = 0;
819 delete _mmc; _mmc = 0;
820 delete _midi_ports; _midi_ports = 0;
821 delete _locations; _locations = 0;
826 /* clear event queue, the session is gone, nobody is interested in
827 * those anymore, but they do leak memory if not removed
829 while (!immediate_events.empty ()) {
830 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
831 SessionEvent *ev = immediate_events.front ();
832 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
833 immediate_events.pop_front ();
837 case SessionEvent::AutoLoop:
838 case SessionEvent::Skip:
839 case SessionEvent::PunchIn:
840 case SessionEvent::PunchOut:
841 case SessionEvent::StopOnce:
842 case SessionEvent::RangeStop:
843 case SessionEvent::RangeLocate:
847 case SessionEvent::RealTimeOperation:
854 del = del && !_remove_event (ev);
862 /* unregister all dropped ports, process pending port deletion. */
863 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
864 // jack1 cannot cope with removing ports while processing
865 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
866 AudioEngine::instance()->clear_pending_port_deletions ();
869 DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
873 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
876 Controllable::dump_registry ();
879 BOOST_SHOW_POINTERS ();
883 Session::setup_ltc ()
887 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
889 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
890 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
893 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
894 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
895 // TODO use auto-connect thread
896 reconnect_ltc_output ();
900 /* fix up names of LTC ports because we don't want the normal
901 * IO style of NAME/TYPE-{in,out}N
904 _ltc_output->nth (0)->set_name (X_("LTC-out"));
908 Session::setup_click ()
912 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
913 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
915 _click_io.reset (new ClickIO (*this, X_("Click")));
916 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
917 _click_gain->activate ();
919 setup_click_state (state_tree->root());
921 setup_click_state (0);
926 Session::setup_click_state (const XMLNode* node)
928 const XMLNode* child = 0;
930 if (node && (child = find_named_node (*node, "Click")) != 0) {
932 /* existing state for Click */
935 if (Stateful::loading_state_version < 3000) {
936 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
938 const XMLNodeList& children (child->children());
939 XMLNodeList::const_iterator i = children.begin();
940 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
942 if (i != children.end()) {
943 c = _click_gain->set_state (**i, Stateful::loading_state_version);
949 _clicking = Config->get_clicking ();
953 error << _("could not setup Click I/O") << endmsg;
960 /* default state for Click: dual-mono to first 2 physical outputs */
963 _engine.get_physical_outputs (DataType::AUDIO, outs);
965 for (uint32_t physport = 0; physport < 2; ++physport) {
966 if (outs.size() > physport) {
967 if (_click_io->add_port (outs[physport], this)) {
968 // relax, even though its an error
973 if (_click_io->n_ports () > ChanCount::ZERO) {
974 _clicking = Config->get_clicking ();
980 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
981 MidiPortFlags include, MidiPortFlags exclude)
983 _engine.get_physical_inputs (type, inputs, include, exclude);
984 _engine.get_physical_outputs (type, outputs, include, exclude);
988 Session::setup_bundles ()
992 RCUWriter<BundleList> writer (_bundles);
993 boost::shared_ptr<BundleList> b = writer.get_copy ();
994 for (BundleList::iterator i = b->begin(); i != b->end();) {
995 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
1003 vector<string> inputs[DataType::num_types];
1004 vector<string> outputs[DataType::num_types];
1006 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1007 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
1008 MidiPortFlags (0), /* no specific inclusions */
1009 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
1013 /* Create a set of Bundle objects that map
1014 to the physical I/O currently available. We create both
1015 mono and stereo bundles, so that the common cases of mono
1016 and stereo tracks get bundles to put in their mixer strip
1017 in / out menus. There may be a nicer way of achieving that;
1018 it doesn't really scale that well to higher channel counts
1021 /* mono output bundles */
1023 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
1025 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
1027 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
1029 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
1032 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1033 c->add_channel (_("mono"), DataType::AUDIO);
1034 c->set_port (0, outputs[DataType::AUDIO][np]);
1036 add_bundle (c, false);
1039 /* stereo output bundles */
1041 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
1042 if (np + 1 < outputs[DataType::AUDIO].size()) {
1044 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1045 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
1046 c->add_channel (_("L"), DataType::AUDIO);
1047 c->set_port (0, outputs[DataType::AUDIO][np]);
1048 c->add_channel (_("R"), DataType::AUDIO);
1049 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
1051 add_bundle (c, false);
1055 /* mono input bundles */
1057 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1059 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1061 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1063 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1066 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1067 c->add_channel (_("mono"), DataType::AUDIO);
1068 c->set_port (0, inputs[DataType::AUDIO][np]);
1070 add_bundle (c, false);
1073 /* stereo input bundles */
1075 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1076 if (np + 1 < inputs[DataType::AUDIO].size()) {
1078 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1080 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1081 c->add_channel (_("L"), DataType::AUDIO);
1082 c->set_port (0, inputs[DataType::AUDIO][np]);
1083 c->add_channel (_("R"), DataType::AUDIO);
1084 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1086 add_bundle (c, false);
1090 /* MIDI input bundles */
1092 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1093 string n = inputs[DataType::MIDI][np];
1095 std::string pn = _engine.get_pretty_name_by_name (n);
1099 boost::erase_first (n, X_("alsa_pcm:"));
1101 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1102 c->add_channel ("", DataType::MIDI);
1103 c->set_port (0, inputs[DataType::MIDI][np]);
1104 add_bundle (c, false);
1107 /* MIDI output bundles */
1109 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1110 string n = outputs[DataType::MIDI][np];
1111 std::string pn = _engine.get_pretty_name_by_name (n);
1115 boost::erase_first (n, X_("alsa_pcm:"));
1117 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1118 c->add_channel ("", DataType::MIDI);
1119 c->set_port (0, outputs[DataType::MIDI][np]);
1120 add_bundle (c, false);
1123 // we trust the backend to only calls us if there's a change
1124 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1128 Session::auto_connect_master_bus ()
1130 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1134 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1135 // In this case it means "Multi Out" output mode
1136 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1140 /* if requested auto-connect the outputs to the first N physical ports.
1143 uint32_t limit = _master_out->n_outputs().n_total();
1144 vector<string> outputs[DataType::num_types];
1146 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1147 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1150 for (uint32_t n = 0; n < limit; ++n) {
1151 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1153 if (outputs[p->type()].size() > n) {
1154 connect_to = outputs[p->type()][n];
1157 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1158 if (_master_out->output()->connect (p, connect_to, this)) {
1159 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1168 Session::remove_monitor_section ()
1170 if (!_monitor_out || Profile->get_trx()) {
1174 /* allow deletion when session is unloaded */
1175 if (!_engine.running() && !deletion_in_progress ()) {
1176 error << _("Cannot remove monitor section while the engine is offline.") << endmsg;
1180 /* force reversion to Solo-In-Place */
1181 Config->set_solo_control_is_listen_control (false);
1183 /* if we are auditioning, cancel it ... this is a workaround
1184 to a problem (auditioning does not execute the process graph,
1185 which is needed to remove routes when using >1 core for processing)
1189 if (!deletion_in_progress ()) {
1190 /* Hold process lock while doing this so that we don't hear bits and
1191 * pieces of audio as we work on each route.
1194 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1196 /* Connect tracks to monitor section. Note that in an
1197 existing session, the internal sends will already exist, but we want the
1198 routes to notice that they connect to the control out specifically.
1202 boost::shared_ptr<RouteList> r = routes.reader ();
1203 ProcessorChangeBlocker pcb (this, false);
1205 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1207 if ((*x)->is_monitor()) {
1209 } else if ((*x)->is_master()) {
1212 (*x)->remove_aux_or_listen (_monitor_out);
1217 remove_route (_monitor_out);
1218 if (deletion_in_progress ()) {
1222 auto_connect_master_bus ();
1225 auditioner->connect ();
1228 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1232 Session::add_monitor_section ()
1236 if (!_engine.running()) {
1237 error << _("Cannot create monitor section while the engine is offline.") << endmsg;
1241 if (_monitor_out || !_master_out || Profile->get_trx()) {
1245 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1251 BOOST_MARK_ROUTE(r);
1254 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1255 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1256 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1258 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1263 add_routes (rl, false, false, false, 0);
1265 assert (_monitor_out);
1267 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1268 are undefined, at best.
1271 uint32_t limit = _monitor_out->n_inputs().n_audio();
1275 /* connect the inputs to the master bus outputs. this
1276 * represents a separate data feed from the internal sends from
1277 * each route. as of jan 2011, it allows the monitor section to
1278 * conditionally ignore either the internal sends or the normal
1279 * input feed, but we should really find a better way to do
1283 _master_out->output()->disconnect (this);
1285 for (uint32_t n = 0; n < limit; ++n) {
1286 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1287 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1290 string connect_to = o->name();
1291 if (_monitor_out->input()->connect (p, connect_to, this)) {
1292 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1300 /* if monitor section is not connected, connect it to physical outs
1303 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1305 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1307 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1310 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1312 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1313 Config->get_monitor_bus_preferred_bundle())
1319 /* Monitor bus is audio only */
1321 vector<string> outputs[DataType::num_types];
1323 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1324 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1327 uint32_t mod = outputs[DataType::AUDIO].size();
1328 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1332 for (uint32_t n = 0; n < limit; ++n) {
1334 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1336 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1337 connect_to = outputs[DataType::AUDIO][n % mod];
1340 if (!connect_to.empty()) {
1341 if (_monitor_out->output()->connect (p, connect_to, this)) {
1342 error << string_compose (
1343 _("cannot connect control output %1 to %2"),
1354 /* Hold process lock while doing this so that we don't hear bits and
1355 * pieces of audio as we work on each route.
1358 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1360 /* Connect tracks to monitor section. Note that in an
1361 existing session, the internal sends will already exist, but we want the
1362 routes to notice that they connect to the control out specifically.
1366 boost::shared_ptr<RouteList> rls = routes.reader ();
1368 ProcessorChangeBlocker pcb (this, false /* XXX */);
1370 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1372 if ((*x)->is_monitor()) {
1374 } else if ((*x)->is_master()) {
1377 (*x)->enable_monitor_send ();
1382 auditioner->connect ();
1385 MonitorBusAddedOrRemoved (); /* EMIT SIGNAL */
1389 Session::reset_monitor_section ()
1391 /* Process lock should be held by the caller.*/
1393 if (!_monitor_out || Profile->get_trx()) {
1397 uint32_t limit = _master_out->n_outputs().n_audio();
1399 /* connect the inputs to the master bus outputs. this
1400 * represents a separate data feed from the internal sends from
1401 * each route. as of jan 2011, it allows the monitor section to
1402 * conditionally ignore either the internal sends or the normal
1403 * input feed, but we should really find a better way to do
1407 _master_out->output()->disconnect (this);
1408 _monitor_out->output()->disconnect (this);
1410 // monitor section follow master bus - except midi
1411 ChanCount mon_chn (_master_out->output()->n_ports());
1412 mon_chn.set_midi (0);
1414 _monitor_out->input()->ensure_io (mon_chn, false, this);
1415 _monitor_out->output()->ensure_io (mon_chn, false, this);
1417 for (uint32_t n = 0; n < limit; ++n) {
1418 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1419 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1422 string connect_to = o->name();
1423 if (_monitor_out->input()->connect (p, connect_to, this)) {
1424 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1431 /* connect monitor section to physical outs
1434 if (Config->get_auto_connect_standard_busses()) {
1436 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1438 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1441 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1443 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1444 Config->get_monitor_bus_preferred_bundle())
1450 /* Monitor bus is audio only */
1452 vector<string> outputs[DataType::num_types];
1454 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1455 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1458 uint32_t mod = outputs[DataType::AUDIO].size();
1459 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1463 for (uint32_t n = 0; n < limit; ++n) {
1465 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1467 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1468 connect_to = outputs[DataType::AUDIO][n % mod];
1471 if (!connect_to.empty()) {
1472 if (_monitor_out->output()->connect (p, connect_to, this)) {
1473 error << string_compose (
1474 _("cannot connect control output %1 to %2"),
1485 /* Connect tracks to monitor section. Note that in an
1486 existing session, the internal sends will already exist, but we want the
1487 routes to notice that they connect to the control out specifically.
1491 boost::shared_ptr<RouteList> rls = routes.reader ();
1493 ProcessorChangeBlocker pcb (this, false);
1495 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1497 if ((*x)->is_monitor()) {
1499 } else if ((*x)->is_master()) {
1502 (*x)->enable_monitor_send ();
1508 Session::add_master_bus (ChanCount const& count)
1510 if (master_out ()) {
1516 boost::shared_ptr<Route> r (new Route (*this, _("Master"), PresentationInfo::MasterOut, DataType::AUDIO));
1521 BOOST_MARK_ROUTE(r);
1524 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1525 r->input()->ensure_io (count, false, this);
1526 r->output()->ensure_io (count, false, this);
1530 add_routes (rl, false, false, false, PresentationInfo::max_order);
1535 Session::hookup_io ()
1537 /* stop graph reordering notifications from
1538 causing resorts, etc.
1541 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1545 /* we delay creating the auditioner till now because
1546 it makes its own connections to ports.
1550 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1552 throw failed_constructor ();
1557 catch (failed_constructor& err) {
1558 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1562 /* load bundles, which we may have postponed earlier on */
1563 if (_bundle_xml_node) {
1564 load_bundles (*_bundle_xml_node);
1565 delete _bundle_xml_node;
1568 /* Tell all IO objects to connect themselves together */
1570 IO::enable_connecting ();
1572 /* Now tell all "floating" ports to connect to whatever
1573 they should be connected to.
1576 AudioEngine::instance()->reconnect_ports ();
1578 /* Anyone who cares about input state, wake up and do something */
1580 IOConnectionsComplete (); /* EMIT SIGNAL */
1582 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1584 /* now handle the whole enchilada as if it was one
1585 graph reorder event.
1590 /* update the full solo state, which can't be
1591 correctly determined on a per-route basis, but
1592 needs the global overview that only the session
1596 update_route_solo_state ();
1600 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1602 boost::shared_ptr<Track> track = wp.lock ();
1607 boost::shared_ptr<Playlist> playlist;
1609 if ((playlist = track->playlist()) != 0) {
1610 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1611 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1612 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1617 Session::record_enabling_legal () const
1619 if (Config->get_all_safe()) {
1626 Session::set_track_monitor_input_status (bool yn)
1628 boost::shared_ptr<RouteList> rl = routes.reader ();
1629 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1630 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1631 if (tr && tr->rec_enable_control()->get_value()) {
1632 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1633 tr->request_input_monitoring (yn);
1639 Session::auto_punch_start_changed (Location* location)
1641 replace_event (SessionEvent::PunchIn, location->start());
1643 if (get_record_enabled() && config.get_punch_in() && !actively_recording ()) {
1644 /* capture start has been changed, so save new pending state */
1645 save_state ("", true);
1650 Session::auto_punch_end_changed (Location* location)
1652 replace_event (SessionEvent::PunchOut, location->end());
1656 Session::auto_punch_changed (Location* location)
1658 auto_punch_start_changed (location);
1659 auto_punch_end_changed (location);
1662 /** @param loc A loop location.
1663 * @param pos Filled in with the start time of the required fade-out (in session samples).
1664 * @param length Filled in with the length of the required fade-out.
1667 Session::auto_loop_declick_range (Location* loc, samplepos_t & pos, samplepos_t & length)
1669 pos = max (loc->start(), loc->end() - 64);
1670 length = loc->end() - pos;
1674 Session::auto_loop_changed (Location* location)
1676 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1679 auto_loop_declick_range (location, dcp, dcl);
1681 bool rolling = transport_rolling ();
1683 if (rolling && play_loop) {
1685 if (_transport_sample < location->start() || _transport_sample > location->end()) {
1686 // relocate to beginning of loop
1687 clear_events (SessionEvent::LocateRoll);
1688 request_locate (location->start(), true);
1692 clear_events (SessionEvent::AutoLoop);
1695 /* possibly move playhead if not rolling; if we are rolling we'll move
1696 to the loop start on stop if that is appropriate.
1701 if (!rolling && select_playhead_priority_target (pos)) {
1702 if (pos == location->start()) {
1703 request_locate (pos);
1707 last_loopend = location->end();
1712 Session::set_auto_punch_location (Location* location)
1716 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1717 punch_connections.drop_connections();
1718 existing->set_auto_punch (false, this);
1719 clear_events (SessionEvent::PunchIn);
1720 clear_events (SessionEvent::PunchOut);
1721 auto_punch_location_changed (0);
1726 if (location == 0) {
1730 if (location->end() <= location->start()) {
1731 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1735 punch_connections.drop_connections ();
1737 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1738 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1739 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1741 location->set_auto_punch (true, this);
1743 auto_punch_changed (location);
1745 auto_punch_location_changed (location);
1749 Session::set_session_extents (samplepos_t start, samplepos_t end)
1752 if ((existing = _locations->session_range_location()) == 0) {
1753 //if there is no existing session, we need to make a new session location (should never happen)
1754 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1758 error << _("Session: you can't use that location for session start/end)") << endmsg;
1762 existing->set( start, end );
1768 Session::set_auto_loop_location (Location* location)
1772 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1773 loop_connections.drop_connections ();
1774 existing->set_auto_loop (false, this);
1775 remove_event (existing->end(), SessionEvent::AutoLoop);
1778 auto_loop_declick_range (existing, dcp, dcl);
1779 auto_loop_location_changed (0);
1784 if (location == 0) {
1788 if (location->end() <= location->start()) {
1789 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1793 last_loopend = location->end();
1795 loop_connections.drop_connections ();
1797 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1798 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1799 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1800 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1802 location->set_auto_loop (true, this);
1804 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1805 // set all tracks to use internal looping
1806 boost::shared_ptr<RouteList> rl = routes.reader ();
1807 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1808 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1809 if (tr && !tr->is_private_route()) {
1810 tr->set_loop (location);
1815 /* take care of our stuff first */
1817 auto_loop_changed (location);
1819 /* now tell everyone else */
1821 auto_loop_location_changed (location);
1825 Session::update_marks (Location*)
1831 Session::update_skips (Location* loc, bool consolidate)
1833 if (_ignore_skips_updates) {
1837 Locations::LocationList skips;
1840 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1841 consolidate_skips (loc);
1844 sync_locations_to_skips ();
1850 Session::consolidate_skips (Location* loc)
1852 Locations::LocationList all_locations = _locations->list ();
1854 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1856 if (!(*l)->is_skip ()) {
1861 /* don't test against self */
1868 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1869 case Evoral::OverlapInternal:
1870 case Evoral::OverlapExternal:
1871 case Evoral::OverlapStart:
1872 case Evoral::OverlapEnd:
1873 /* adjust new location to cover existing one */
1874 loc->set_start (min (loc->start(), (*l)->start()));
1875 loc->set_end (max (loc->end(), (*l)->end()));
1876 /* we don't need this one any more */
1877 _locations->remove (*l);
1878 /* the location has been deleted, so remove reference to it in our local list */
1879 l = all_locations.erase (l);
1882 case Evoral::OverlapNone:
1890 Session::sync_locations_to_skips ()
1892 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1893 * Session::_sync_locations_to_skips() from the audioengine thread.
1895 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1899 Session::_sync_locations_to_skips ()
1901 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1903 Locations::LocationList const & locs (_locations->list());
1905 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1907 Location* location = *i;
1909 if (location->is_skip() && location->is_skipping()) {
1910 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1918 Session::location_added (Location *location)
1920 if (location->is_auto_punch()) {
1921 set_auto_punch_location (location);
1924 if (location->is_auto_loop()) {
1925 set_auto_loop_location (location);
1928 if (location->is_session_range()) {
1929 /* no need for any signal handling or event setting with the session range,
1930 because we keep a direct reference to it and use its start/end directly.
1932 _session_range_location = location;
1935 if (location->is_mark()) {
1936 /* listen for per-location signals that require us to do any * global updates for marks */
1938 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1939 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1940 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1941 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1942 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1945 if (location->is_range_marker()) {
1946 /* listen for per-location signals that require us to do any * global updates for marks */
1948 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1949 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1950 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1951 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1952 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1955 if (location->is_skip()) {
1956 /* listen for per-location signals that require us to update skip-locate events */
1958 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1959 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1960 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1961 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1962 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1964 update_skips (location, true);
1971 Session::location_removed (Location *location)
1973 if (location->is_auto_loop()) {
1974 set_auto_loop_location (0);
1976 set_track_loop (false);
1981 if (location->is_auto_punch()) {
1982 set_auto_punch_location (0);
1985 if (location->is_session_range()) {
1986 /* this is never supposed to happen */
1987 error << _("programming error: session range removed!") << endl;
1990 if (location->is_skip()) {
1992 update_skips (location, false);
1999 Session::locations_changed ()
2001 _locations->apply (*this, &Session::_locations_changed);
2005 Session::_locations_changed (const Locations::LocationList& locations)
2007 /* There was some mass-change in the Locations object.
2009 * We might be re-adding a location here but it doesn't actually matter
2010 * for all the locations that the Session takes an interest in.
2014 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
2015 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
2016 location_added (*i);
2020 update_skips (NULL, false);
2024 Session::enable_record ()
2026 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
2027 /* no recording at anything except normal speed */
2032 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
2034 if (rs == Recording) {
2038 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
2040 _last_record_location = _transport_sample;
2041 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
2043 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2044 set_track_monitor_input_status (true);
2047 RecordStateChanged ();
2054 Session::set_all_tracks_record_enabled (bool enable )
2056 boost::shared_ptr<RouteList> rl = routes.reader();
2057 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
2061 Session::disable_record (bool rt_context, bool force)
2065 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2067 if (!Config->get_latched_record_enable () || force) {
2068 g_atomic_int_set (&_record_status, Disabled);
2069 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2071 if (rs == Recording) {
2072 g_atomic_int_set (&_record_status, Enabled);
2076 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2077 set_track_monitor_input_status (false);
2080 RecordStateChanged (); /* emit signal */
2083 remove_pending_capture_state ();
2089 Session::step_back_from_record ()
2091 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2093 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2094 set_track_monitor_input_status (false);
2097 RecordStateChanged (); /* emit signal */
2102 Session::maybe_enable_record (bool rt_context)
2104 if (_step_editors > 0) {
2108 g_atomic_int_set (&_record_status, Enabled);
2110 /* This function is currently called from somewhere other than an RT thread.
2111 * (except maybe lua scripts, which can use rt_context = true)
2112 * This save_state() call therefore doesn't impact anything. Doing it here
2113 * means that we save pending state of which sources the next record will use,
2114 * which gives us some chance of recovering from a crash during the record.
2118 save_state ("", true);
2121 if (_transport_speed) {
2122 if (!config.get_punch_in()) {
2126 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2127 RecordStateChanged (); /* EMIT SIGNAL */
2134 Session::audible_sample (bool* latent_locate) const
2136 if (latent_locate) {
2137 *latent_locate = false;
2142 if (synced_to_engine()) {
2143 /* Note: this is basically just sync-to-JACK */
2144 ret = _engine.transport_sample();
2146 ret = _transport_sample;
2151 if (!transport_rolling()) {
2155 #if 0 // TODO looping
2156 if (_transport_speed > 0.0f) {
2157 if (play_loop && have_looped) {
2158 /* the play-position wrapped at the loop-point
2159 * ardour is already playing the beginning of the loop,
2160 * but due to playback latency, the "audible frame"
2161 * is still at the end of the loop.
2163 Location *location = _locations->auto_loop_location();
2164 sampleoffset_t lo = location->start() - ret;
2166 ret = location->end () - lo;
2167 if (latent_locate) {
2168 *latent_locate = true;
2172 } else if (_transport_speed < 0.0f) {
2173 /* XXX wot? no backward looping? */
2177 return std::max ((samplepos_t)0, ret);
2181 Session::preroll_samples (samplepos_t pos) const
2183 const float pr = Config->get_preroll_seconds();
2184 if (pos >= 0 && pr < 0) {
2185 const Tempo& tempo = _tempo_map->tempo_at_sample (pos);
2186 const Meter& meter = _tempo_map->meter_at_sample (pos);
2187 return meter.samples_per_bar (tempo, sample_rate()) * -pr;
2192 return pr * sample_rate();
2196 Session::set_sample_rate (samplecnt_t frames_per_second)
2198 /** \fn void Session::set_sample_size(samplecnt_t)
2199 the AudioEngine object that calls this guarantees
2200 that it will not be called while we are also in
2201 ::process(). Its fine to do things that block
2205 if (_base_sample_rate == 0) {
2206 _base_sample_rate = frames_per_second;
2208 else if (_base_sample_rate != frames_per_second && frames_per_second != _nominal_sample_rate) {
2209 NotifyAboutSampleRateMismatch (_base_sample_rate, frames_per_second);
2211 _nominal_sample_rate = frames_per_second;
2216 reset_write_sources (false);
2218 // XXX we need some equivalent to this, somehow
2219 // SndFileSource::setup_standard_crossfades (frames_per_second);
2223 /* XXX need to reset/reinstantiate all LADSPA plugins */
2227 Session::set_block_size (pframes_t nframes)
2229 /* the AudioEngine guarantees
2230 that it will not be called while we are also in
2231 ::process(). It is therefore fine to do things that block
2236 current_block_size = nframes;
2240 boost::shared_ptr<RouteList> r = routes.reader ();
2242 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2243 (*i)->set_block_size (nframes);
2246 boost::shared_ptr<RouteList> rl = routes.reader ();
2247 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2248 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2250 tr->set_block_size (nframes);
2254 set_worst_io_latencies ();
2260 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase, bool sends_only)
2262 boost::shared_ptr<Route> r2;
2264 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2265 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2269 /* make a copy of the existing list of routes that feed r1 */
2271 Route::FedBy existing (r1->fed_by());
2273 /* for each route that feeds r1, recurse, marking it as feeding
2277 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2278 if (!(r2 = i->r.lock ())) {
2279 /* (*i) went away, ignore it */
2283 /* r2 is a route that feeds r1 which somehow feeds base. mark
2284 base as being fed by r2
2287 rbase->add_fed_by (r2, i->sends_only || sends_only);
2291 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2295 if (r1->feeds (r2) && r2->feeds (r1)) {
2299 /* now recurse, so that we can mark base as being fed by
2300 all routes that feed r2
2303 trace_terminal (r2, rbase, i->sends_only || sends_only);
2310 Session::resort_routes ()
2312 /* don't do anything here with signals emitted
2313 by Routes during initial setup or while we
2314 are being destroyed.
2317 if (inital_connect_or_deletion_in_progress ()) {
2321 if (_route_deletion_in_progress) {
2326 RCUWriter<RouteList> writer (routes);
2327 boost::shared_ptr<RouteList> r = writer.get_copy ();
2328 resort_routes_using (r);
2329 /* writer goes out of scope and forces update */
2333 if (DEBUG_ENABLED(DEBUG::Graph)) {
2334 boost::shared_ptr<RouteList> rl = routes.reader ();
2335 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2336 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2338 const Route::FedBy& fb ((*i)->fed_by());
2340 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2341 boost::shared_ptr<Route> sf = f->r.lock();
2343 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2352 /** This is called whenever we need to rebuild the graph of how we will process
2354 * @param r List of routes, in any order.
2358 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2360 /* We are going to build a directed graph of our routes;
2361 this is where the edges of that graph are put.
2366 /* Go through all routes doing two things:
2368 * 1. Collect the edges of the route graph. Each of these edges
2369 * is a pair of routes, one of which directly feeds the other
2370 * either by a JACK connection or by an internal send.
2372 * 2. Begin the process of making routes aware of which other
2373 * routes directly or indirectly feed them. This information
2374 * is used by the solo code.
2377 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2379 /* Clear out the route's list of direct or indirect feeds */
2380 (*i)->clear_fed_by ();
2382 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2384 bool via_sends_only;
2386 /* See if this *j feeds *i according to the current state of the JACK
2387 connections and internal sends.
2389 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2390 /* add the edge to the graph (part #1) */
2391 edges.add (*j, *i, via_sends_only);
2392 /* tell the route (for part #2) */
2393 (*i)->add_fed_by (*j, via_sends_only);
2398 /* Attempt a topological sort of the route graph */
2399 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2401 if (sorted_routes) {
2402 /* We got a satisfactory topological sort, so there is no feedback;
2405 Note: the process graph rechain does not require a
2406 topologically-sorted list, but hey ho.
2408 if (_process_graph) {
2409 _process_graph->rechain (sorted_routes, edges);
2412 _current_route_graph = edges;
2414 /* Complete the building of the routes' lists of what directly
2415 or indirectly feeds them.
2417 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2418 trace_terminal (*i, *i, false);
2421 *r = *sorted_routes;
2424 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2425 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2426 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2430 SuccessfulGraphSort (); /* EMIT SIGNAL */
2433 /* The topological sort failed, so we have a problem. Tell everyone
2434 and stick to the old graph; this will continue to be processed, so
2435 until the feedback is fixed, what is played back will not quite
2436 reflect what is actually connected. Note also that we do not
2437 do trace_terminal here, as it would fail due to an endless recursion,
2438 so the solo code will think that everything is still connected
2442 FeedbackDetected (); /* EMIT SIGNAL */
2447 /** Find a route name starting with \a base, maybe followed by the
2448 * lowest \a id. \a id will always be added if \a definitely_add_number
2449 * is true on entry; otherwise it will only be added if required
2450 * to make the name unique.
2452 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2453 * The available route name with the lowest ID will be used, and \a id
2454 * will be set to the ID.
2456 * \return false if a route name could not be found, and \a track_name
2457 * and \a id do not reflect a free route name.
2460 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2462 /* the base may conflict with ports that do not belong to existing
2463 routes, but hidden objects like the click track. So check port names
2464 before anything else.
2467 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2468 if (base == reserved->first) {
2469 /* Check if this reserved name already exists, and if
2470 so, disallow it without a numeric suffix.
2472 if (!reserved->second || route_by_name (reserved->first)) {
2473 definitely_add_number = true;
2482 /* if we have "base 1" already, it doesn't make sense to add "base"
2483 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2485 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2486 /* just use the base */
2492 name = string_compose ("%1 %2", base, id);
2494 if (route_by_name (name) == 0) {
2500 } while (id < (UINT_MAX-1));
2505 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2507 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2509 in = ChanCount::ZERO;
2510 out = ChanCount::ZERO;
2512 boost::shared_ptr<RouteList> r = routes.reader ();
2514 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2515 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2519 assert (!tr->is_auditioner()); // XXX remove me
2520 in += tr->n_inputs();
2521 out += tr->n_outputs();
2526 Session::default_track_name_pattern (DataType t)
2529 case DataType::AUDIO:
2530 if (Profile->get_trx()) {
2537 case DataType::MIDI:
2544 /** Caller must not hold process lock
2545 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2546 * @param instrument plugin info for the instrument to insert pre-fader, if any
2548 list<boost::shared_ptr<MidiTrack> >
2549 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2550 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2551 RouteGroup* route_group, uint32_t how_many,
2552 string name_template, PresentationInfo::order_t order,
2556 uint32_t track_id = 0;
2558 RouteList new_routes;
2559 list<boost::shared_ptr<MidiTrack> > ret;
2561 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2562 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2565 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2566 error << "cannot find name for new midi track" << endmsg;
2570 boost::shared_ptr<MidiTrack> track;
2573 track.reset (new MidiTrack (*this, track_name, mode));
2575 if (track->init ()) {
2580 track->set_strict_io (true);
2583 BOOST_MARK_TRACK (track);
2586 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2587 if (track->input()->ensure_io (input, false, this)) {
2588 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2592 if (track->output()->ensure_io (output, false, this)) {
2593 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2599 route_group->add (track);
2602 new_routes.push_back (track);
2603 ret.push_back (track);
2606 catch (failed_constructor &err) {
2607 error << _("Session: could not create new midi track.") << endmsg;
2611 catch (AudioEngine::PortRegistrationFailure& pfe) {
2613 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;
2621 if (!new_routes.empty()) {
2622 StateProtector sp (this);
2623 if (Profile->get_trx()) {
2624 add_routes (new_routes, false, false, false, order);
2626 add_routes (new_routes, true, true, false, order);
2630 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2631 PluginPtr plugin = instrument->load (*this);
2633 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2637 plugin->load_preset (*pset);
2639 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2641 pi->set_strict_io (true);
2644 (*r)->add_processor (pi, PreFader);
2646 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2647 (*r)->move_instrument_down (false);
2657 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2658 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2659 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2662 uint32_t bus_id = 0;
2666 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2669 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2670 error << "cannot find name for new midi bus" << endmsg;
2675 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2682 bus->set_strict_io (true);
2685 BOOST_MARK_ROUTE(bus);
2688 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2690 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2691 error << _("cannot configure new midi bus input") << endmsg;
2696 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2697 error << _("cannot configure new midi bus output") << endmsg;
2703 route_group->add (bus);
2706 bus->add_internal_return ();
2707 ret.push_back (bus);
2710 catch (failed_constructor &err) {
2711 error << _("Session: could not create new audio route.") << endmsg;
2715 catch (AudioEngine::PortRegistrationFailure& pfe) {
2716 error << pfe.what() << endmsg;
2726 StateProtector sp (this);
2727 add_routes (ret, false, false, false, order);
2730 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2731 PluginPtr plugin = instrument->load (*this);
2733 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2737 plugin->load_preset (*pset);
2739 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2741 pi->set_strict_io (true);
2744 (*r)->add_processor (pi, PreFader);
2746 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2747 (*r)->move_instrument_down (false);
2759 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2761 boost::shared_ptr<Route> midi_track (wmt.lock());
2767 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2769 if (change.after.n_audio() <= change.before.n_audio()) {
2773 /* new audio ports: make sure the audio goes somewhere useful,
2774 * unless the user has no-auto-connect selected.
2776 * The existing ChanCounts don't matter for this call as they are only
2777 * to do with matching input and output indices, and we are only changing
2780 auto_connect_route (midi_track, false, ChanCount(), change.before);
2784 #ifdef USE_TRACKS_CODE_FEATURES
2787 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2789 return route1->remote_control_id() < route2->remote_control_id();
2793 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2795 // it is not allowed to perform connection
2796 if (!IO::connecting_legal) {
2800 // if we are deleting routes we will call this once at the end
2801 if (_route_deletion_in_progress) {
2805 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2811 // We need to disconnect the route's inputs and outputs first
2812 // basing on autoconnect configuration
2813 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2814 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2816 ChanCount existing_inputs;
2817 ChanCount existing_outputs;
2818 count_existing_track_channels (existing_inputs, existing_outputs);
2820 //ChanCount inputs = ChanCount::ZERO;
2821 //ChanCount outputs = ChanCount::ZERO;
2823 RouteList existing_routes = *routes.reader ();
2824 existing_routes.sort (compare_routes_by_remote_id);
2827 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2829 vector<string> physinputs;
2830 vector<string> physoutputs;
2832 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2833 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2835 uint32_t input_n = 0;
2836 uint32_t output_n = 0;
2837 RouteList::iterator rIter = existing_routes.begin();
2838 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2839 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2840 for (; rIter != existing_routes.end(); ++rIter) {
2841 if (*rIter == _master_out || *rIter == _monitor_out ) {
2845 if (current_output_auto_connection == AutoConnectPhysical) {
2846 (*rIter)->amp()->deactivate();
2847 } else if (current_output_auto_connection == AutoConnectMaster) {
2848 (*rIter)->amp()->activate();
2851 if (reconnectIputs) {
2852 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2854 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2856 if (current_input_auto_connection & AutoConnectPhysical) {
2858 if ( input_n == physinputs.size() ) {
2862 string port = physinputs[input_n];
2864 if (port.empty() ) {
2865 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2868 //GZ: check this; could be heavy
2869 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2875 if (reconnectOutputs) {
2877 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2878 if (current_output_auto_connection & AutoConnectPhysical) {
2880 //GZ: check this; could be heavy
2881 (*rIter)->output()->disconnect (this);
2882 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2884 //GZ: check this; could be heavy
2885 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2887 } else if (current_output_auto_connection & AutoConnectMaster){
2889 if (!reconnect_master) {
2893 //GZ: check this; could be heavy
2894 (*rIter)->output()->disconnect (this);
2897 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2898 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2900 error << error << "Master bus is not available" << endmsg;
2905 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2906 if (current_output_auto_connection & AutoConnectPhysical) {
2908 if ( output_n == physoutputs.size() ) {
2912 string port = physoutputs[output_n];
2914 if (port.empty() ) {
2915 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2918 //GZ: check this; could be heavy
2919 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2922 } else if (current_output_auto_connection & AutoConnectMaster) {
2924 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2928 // connect to master bus
2929 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2931 if (port.empty() ) {
2932 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2936 //GZ: check this; could be heavy
2937 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2944 _master_out->output()->disconnect (this);
2945 auto_connect_master_bus ();
2950 session_routes_reconnected (); /* EMIT SIGNAL */
2954 Session::reconnect_midi_scene_ports(bool inputs)
2958 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2960 scene_in_ptr->disconnect_all ();
2962 std::vector<EngineStateController::MidiPortState> midi_port_states;
2963 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2965 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2967 for (; state_iter != midi_port_states.end(); ++state_iter) {
2968 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2969 scene_in_ptr->connect (state_iter->name);
2976 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2978 if (scene_out_ptr ) {
2979 scene_out_ptr->disconnect_all ();
2981 std::vector<EngineStateController::MidiPortState> midi_port_states;
2982 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2984 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2986 for (; state_iter != midi_port_states.end(); ++state_iter) {
2987 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2988 scene_out_ptr->connect (state_iter->name);
2996 Session::reconnect_mmc_ports(bool inputs)
2998 if (inputs ) { // get all enabled midi input ports
3000 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
3002 mmc_in_ptr->disconnect_all ();
3003 std::vector<std::string> enabled_midi_inputs;
3004 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
3006 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
3008 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
3009 mmc_in_ptr->connect (*port_iter);
3013 } else { // get all enabled midi output ports
3015 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3017 mmc_out_ptr->disconnect_all ();
3018 std::vector<std::string> enabled_midi_outputs;
3019 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3021 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3023 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3024 mmc_out_ptr->connect (*port_iter);
3033 Session::ensure_stripable_sort_order ()
3036 get_stripables (sl);
3037 sl.sort (Stripable::Sorter ());
3039 bool change = false;
3040 PresentationInfo::order_t order = 0;
3042 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3043 boost::shared_ptr<Stripable> s (*si);
3044 assert (!s->is_auditioner ()); // XXX remove me
3045 if (s->is_monitor ()) {
3048 if (order != s->presentation_info().order()) {
3049 s->set_presentation_order (order);
3058 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3060 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", first_new_order, how_many));
3062 if (first_new_order == PresentationInfo::max_order) {
3063 /* adding at end, no worries */
3067 /* create a gap in the presentation info to accomodate @param how_many
3071 get_stripables (sl);
3073 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3074 boost::shared_ptr<Stripable> s (*si);
3076 if (s->presentation_info().special (false)) {
3080 if (!s->presentation_info().order_set()) {
3084 if (s->presentation_info().order () >= first_new_order) {
3085 s->set_presentation_order (s->presentation_info().order () + how_many);
3090 /** Caller must not hold process lock
3091 * @param name_template string to use for the start of the name, or "" to use "Audio".
3093 list< boost::shared_ptr<AudioTrack> >
3094 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3095 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3099 uint32_t track_id = 0;
3101 RouteList new_routes;
3102 list<boost::shared_ptr<AudioTrack> > ret;
3104 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3105 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3109 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3110 error << "cannot find name for new audio track" << endmsg;
3114 boost::shared_ptr<AudioTrack> track;
3117 track.reset (new AudioTrack (*this, track_name, mode));
3119 if (track->init ()) {
3123 if (Profile->get_mixbus ()) {
3124 track->set_strict_io (true);
3127 if (ARDOUR::Profile->get_trx ()) {
3128 // TRACKS considers it's not a USE CASE, it's
3129 // a piece of behavior of the session model:
3131 // Gain for a newly created route depends on
3132 // the current output_auto_connect mode:
3134 // 0 for Stereo Out mode
3136 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3137 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3141 BOOST_MARK_TRACK (track);
3144 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3146 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3147 error << string_compose (
3148 _("cannot configure %1 in/%2 out configuration for new audio track"),
3149 input_channels, output_channels)
3154 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3155 error << string_compose (
3156 _("cannot configure %1 in/%2 out configuration for new audio track"),
3157 input_channels, output_channels)
3164 route_group->add (track);
3167 new_routes.push_back (track);
3168 ret.push_back (track);
3171 catch (failed_constructor &err) {
3172 error << _("Session: could not create new audio track.") << endmsg;
3176 catch (AudioEngine::PortRegistrationFailure& pfe) {
3178 error << pfe.what() << endmsg;
3186 if (!new_routes.empty()) {
3187 StateProtector sp (this);
3188 if (Profile->get_trx()) {
3189 add_routes (new_routes, false, false, false, order);
3191 add_routes (new_routes, true, true, false, order);
3198 /** Caller must not hold process lock.
3199 * @param name_template string to use for the start of the name, or "" to use "Bus".
3202 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3203 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3206 uint32_t bus_id = 0;
3210 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3213 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3214 error << "cannot find name for new audio bus" << endmsg;
3219 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3225 if (Profile->get_mixbus ()) {
3226 bus->set_strict_io (true);
3229 BOOST_MARK_ROUTE(bus);
3232 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3234 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3235 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3236 input_channels, output_channels)
3242 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3243 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3244 input_channels, output_channels)
3251 route_group->add (bus);
3254 bus->add_internal_return ();
3255 ret.push_back (bus);
3258 catch (failed_constructor &err) {
3259 error << _("Session: could not create new audio route.") << endmsg;
3263 catch (AudioEngine::PortRegistrationFailure& pfe) {
3264 error << pfe.what() << endmsg;
3274 StateProtector sp (this);
3275 if (Profile->get_trx()) {
3276 add_routes (ret, false, false, false, order);
3277 } else if (flags == PresentationInfo::FoldbackBus) {
3278 add_routes (ret, false, false, true, order); // no autoconnect
3280 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3289 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3290 PlaylistDisposition pd)
3294 if (!tree.read (template_path.c_str())) {
3298 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3302 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3305 uint32_t number = 0;
3306 const uint32_t being_added = how_many;
3307 /* This will prevent the use of any existing XML-provided PBD::ID
3310 Stateful::ForceIDRegeneration force_ids;
3311 IO::disable_connecting ();
3315 /* We're going to modify the node contents a bit so take a
3316 * copy. The node may be re-used when duplicating more than once.
3319 XMLNode node_copy (node);
3320 std::vector<boost::shared_ptr<Playlist> > shared_playlists;
3325 if (!name_base.empty()) {
3327 /* if we're adding more than one routes, force
3328 * all the names of the new routes to be
3329 * numbered, via the final parameter.
3332 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3333 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3339 string const route_name = node_copy.property(X_("name"))->value ();
3341 /* generate a new name by adding a number to the end of the template name */
3342 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3343 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3344 abort(); /*NOTREACHED*/
3348 /* figure out the appropriate playlist setup. The track
3349 * (if the Route we're creating is a track) will find
3353 if (pd == CopyPlaylist) {
3355 PBD::ID playlist_id;
3357 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
3358 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3359 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3360 playlist->reset_shares ();
3361 node_copy.set_property (X_("audio-playlist"), playlist->id());
3364 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
3365 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3366 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3367 playlist->reset_shares ();
3368 node_copy.set_property (X_("midi-playlist"), playlist->id());
3371 } else if (pd == SharePlaylist) {
3372 PBD::ID playlist_id;
3374 if (node_copy.get_property (X_("audio-playlist"), playlist_id)) {
3375 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3376 shared_playlists.push_back (playlist);
3379 if (node_copy.get_property (X_("midi-playlist"), playlist_id)) {
3380 boost::shared_ptr<Playlist> playlist = _playlists->by_id (playlist_id);
3381 shared_playlists.push_back (playlist);
3384 } else { /* NewPlaylist */
3388 if (node_copy.get_property (X_("audio-playlist"), pid)) {
3389 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::AUDIO, *this, name, false);
3390 node_copy.set_property (X_("audio-playlist"), playlist->id());
3393 if (node_copy.get_property (X_("midi-playlist"), pid)) {
3394 boost::shared_ptr<Playlist> playlist = PlaylistFactory::create (DataType::MIDI, *this, name, false);
3395 node_copy.set_property (X_("midi-playlist"), playlist->id());
3399 /* Fix up new name in the XML node */
3401 Route::set_name_in_state (node_copy, name);
3403 /* trim bitslots from listen sends so that new ones are used */
3404 XMLNodeList children = node_copy.children ();
3405 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3406 if ((*i)->name() == X_("Processor")) {
3407 /* ForceIDRegeneration does not catch the following */
3408 XMLProperty const * role = (*i)->property (X_("role"));
3409 XMLProperty const * type = (*i)->property (X_("type"));
3410 if (role && role->value() == X_("Aux")) {
3411 /* check if the target bus exists.
3412 * we should not save aux-sends in templates.
3414 XMLProperty const * target = (*i)->property (X_("target"));
3416 (*i)->set_property ("type", "dangling-aux-send");
3419 boost::shared_ptr<Route> r = route_by_id (target->value());
3420 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3421 (*i)->set_property ("type", "dangling-aux-send");
3425 if (role && role->value() == X_("Listen")) {
3426 (*i)->remove_property (X_("bitslot"));
3428 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3429 Delivery::Role xrole;
3430 uint32_t bitslot = 0;
3431 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3432 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3433 (*i)->remove_property (X_("bitslot"));
3434 (*i)->remove_property (X_("name"));
3435 (*i)->set_property ("bitslot", bitslot);
3436 (*i)->set_property ("name", name);
3437 XMLNodeList io_kids = (*i)->children ();
3438 for (XMLNodeList::iterator j = io_kids.begin(); j != io_kids.end(); ++j) {
3439 if ((*j)->name() != X_("IO")) {
3442 (*j)->remove_property (X_("name"));
3443 (*j)->set_property ("name", name);
3446 else if (type && type->value() == X_("intreturn")) {
3447 (*i)->remove_property (X_("bitslot"));
3448 (*i)->set_property ("ignore-bitslot", "1");
3450 else if (type && type->value() == X_("return")) {
3451 // Return::set_state() generates a new one
3452 (*i)->remove_property (X_("bitslot"));
3454 else if (type && type->value() == X_("port")) {
3455 IOProcessor::prepare_for_reset (**i, name);
3460 /* new routes start off unsoloed to avoid issues related to
3461 upstream / downstream buses.
3463 node_copy.remove_node_and_delete (X_("Controllable"), X_("name"), X_("solo"));
3465 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3468 error << _("Session: cannot create track/bus from template description") << endmsg;
3472 /* Fix up sharing of playlists with the new Route/Track */
3474 for (vector<boost::shared_ptr<Playlist> >::iterator sp = shared_playlists.begin(); sp != shared_playlists.end(); ++sp) {
3475 (*sp)->share_with (route->id());
3478 if (boost::dynamic_pointer_cast<Track>(route)) {
3479 /* force input/output change signals so that the new diskstream
3480 picks up the configuration of the route. During session
3481 loading this normally happens in a different way.
3484 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3486 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3487 change.after = route->input()->n_ports();
3488 route->input()->changed (change, this);
3489 change.after = route->output()->n_ports();
3490 route->output()->changed (change, this);
3493 ret.push_back (route);
3496 catch (failed_constructor &err) {
3497 error << _("Session: could not create new route from template") << endmsg;
3501 catch (AudioEngine::PortRegistrationFailure& pfe) {
3502 error << pfe.what() << endmsg;
3507 IO::enable_connecting ();
3516 StateProtector sp (this);
3517 if (Profile->get_trx()) {
3518 add_routes (ret, false, false, false, insert_at);
3520 add_routes (ret, true, true, false, insert_at);
3524 IO::enable_connecting ();
3530 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3533 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3534 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3537 error << _("Adding new tracks/busses failed") << endmsg;
3542 update_latency (false);
3543 update_latency (true);
3548 save_state (_current_snapshot_name);
3551 update_route_record_state ();
3553 RouteAdded (new_routes); /* EMIT SIGNAL */
3557 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3559 ChanCount existing_inputs;
3560 ChanCount existing_outputs;
3564 count_existing_track_channels (existing_inputs, existing_outputs);
3567 RCUWriter<RouteList> writer (routes);
3568 boost::shared_ptr<RouteList> r = writer.get_copy ();
3569 n_routes = r->size();
3570 r->insert (r->end(), new_routes.begin(), new_routes.end());
3572 /* if there is no control out and we're not in the middle of loading,
3573 * resort the graph here. if there is a control out, we will resort
3574 * toward the end of this method. if we are in the middle of loading,
3575 * we will resort when done.
3578 if (!_monitor_out && IO::connecting_legal) {
3579 resort_routes_using (r);
3583 /* monitor is not part of the order */
3585 assert (n_routes > 0);
3590 PresentationInfo::ChangeSuspender cs;
3591 ensure_route_presentation_info_gap (order, new_routes.size());
3593 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3595 boost::weak_ptr<Route> wpr (*x);
3596 boost::shared_ptr<Route> r (*x);
3598 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3599 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3600 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3602 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3603 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3604 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3606 if (r->is_master()) {
3610 if (r->is_monitor()) {
3614 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3616 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3617 track_playlist_changed (boost::weak_ptr<Track> (tr));
3618 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3620 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3622 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3623 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3624 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3628 if (!r->presentation_info().special (false)) {
3630 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3632 /* presentation info order may already have been set from XML */
3634 if (!r->presentation_info().order_set()) {
3635 if (order == PresentationInfo::max_order) {
3636 /* just add to the end */
3637 r->set_presentation_order (n_routes + added);
3638 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3640 r->set_presentation_order (order + added);
3641 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3644 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3648 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3649 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3650 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3652 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3654 r->presentation_info().order(),
3655 enum_2_string (r->presentation_info().flags()),
3656 r->presentation_info()));
3660 if (input_auto_connect || output_auto_connect) {
3661 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3662 existing_inputs += r->n_inputs();
3663 existing_outputs += r->n_outputs();
3668 ensure_stripable_sort_order ();
3671 if (_monitor_out && IO::connecting_legal) {
3672 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3674 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3675 if ((*x)->is_monitor()) {
3677 } else if ((*x)->is_master()) {
3680 (*x)->enable_monitor_send ();
3685 reassign_track_numbers ();
3689 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3691 boost::shared_ptr<RouteList> r = routes.reader ();
3692 boost::shared_ptr<Send> s;
3694 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3695 if ((s = (*i)->internal_send_for (dest)) != 0) {
3696 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3702 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3704 boost::shared_ptr<RouteList> r = routes.reader ();
3705 boost::shared_ptr<Send> s;
3707 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3708 if ((s = (*i)->internal_send_for (dest)) != 0) {
3709 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3715 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3717 boost::shared_ptr<RouteList> r = routes.reader ();
3718 boost::shared_ptr<Send> s;
3720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3721 if ((s = (*i)->internal_send_for (dest)) != 0) {
3722 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3727 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3729 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3731 boost::shared_ptr<RouteList> r = routes.reader ();
3732 boost::shared_ptr<RouteList> t (new RouteList);
3734 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3735 /* no MIDI sends because there are no MIDI busses yet */
3736 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3741 add_internal_sends (dest, p, t);
3745 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3747 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3748 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3753 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3755 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3759 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3761 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3765 if (!dest->internal_return()) {
3766 dest->add_internal_return ();
3769 sender->add_aux_send (dest, before);
3775 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3777 bool mute_changed = false;
3778 bool send_selected = false;
3780 { // RCU Writer scope
3781 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3782 RCUWriter<RouteList> writer (routes);
3783 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3785 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3787 if (_selection->selected (*iter)) {
3788 send_selected = true;
3791 if (*iter == _master_out) {
3795 /* speed up session deletion, don't do the solo dance */
3796 if (!deletion_in_progress ()) {
3797 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3800 if ((*iter)->mute_control()->muted ()) {
3801 mute_changed = true;
3806 /* deleting the master out seems like a dumb
3807 idea, but its more of a UI policy issue
3811 if (*iter == _master_out) {
3812 _master_out = boost::shared_ptr<Route> ();
3815 if (*iter == _monitor_out) {
3816 _monitor_out.reset ();
3819 // We need to disconnect the route's inputs and outputs
3821 (*iter)->input()->disconnect (0);
3822 (*iter)->output()->disconnect (0);
3824 /* if the route had internal sends sending to it, remove them */
3826 if (!deletion_in_progress () && (*iter)->internal_return()) {
3828 boost::shared_ptr<RouteList> r = routes.reader ();
3829 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3830 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3832 (*i)->remove_processor (s);
3837 /* if the monitoring section had a pointer to this route, remove it */
3838 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3839 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3840 ProcessorChangeBlocker pcb (this, false);
3841 (*iter)->remove_aux_or_listen (_monitor_out);
3844 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3845 if (mt && mt->step_editing()) {
3846 if (_step_editors > 0) {
3852 /* writer goes out of scope, forces route list update */
3854 } // end of RCU Writer scope
3857 MuteChanged (); /* EMIT SIGNAL */
3860 update_route_solo_state ();
3861 update_latency_compensation ();
3864 /* Re-sort routes to remove the graph's current references to the one that is
3865 * going away, then flush old references out of the graph.
3866 * Wave Tracks: reconnect routes
3869 #ifdef USE_TRACKS_CODE_FEATURES
3870 reconnect_existing_routes(true, false);
3872 routes.flush (); // maybe unsafe, see below.
3876 if (_process_graph && !deletion_in_progress() && _engine.running()) {
3877 _process_graph->clear_other_chain ();
3880 /* get rid of it from the dead wood collection in the route list manager */
3881 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3885 /* remove these routes from the selection if appropriate, and signal
3886 * the change *before* we call DropReferences for them.
3889 if (send_selected && !deletion_in_progress()) {
3890 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3891 _selection->remove_stripable_by_id ((*iter)->id());
3894 pc.add (Properties::selected);
3895 PresentationInfo::Change (pc);
3898 /* try to cause everyone to drop their references
3899 * and unregister ports from the backend
3902 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3903 (*iter)->drop_references ();
3906 if (deletion_in_progress()) {
3911 pc.add (Properties::order);
3912 PresentationInfo::Change (pc);
3914 /* save the new state of the world */
3916 if (save_state (_current_snapshot_name)) {
3917 save_history (_current_snapshot_name);
3920 update_route_record_state ();
3924 Session::remove_route (boost::shared_ptr<Route> route)
3926 boost::shared_ptr<RouteList> rl (new RouteList);
3927 rl->push_back (route);
3932 Session::route_mute_changed ()
3934 MuteChanged (); /* EMIT SIGNAL */
3939 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3941 boost::shared_ptr<Route> route (wpr.lock());
3947 assert (Config->get_solo_control_is_listen_control());
3949 if (route->solo_control()->soloed_by_self_or_masters()) {
3951 if (Config->get_exclusive_solo()) {
3953 RouteGroup* rg = route->route_group ();
3954 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3956 boost::shared_ptr<RouteList> r = routes.reader ();
3958 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3959 if ((*i) == route) {
3960 /* already changed */
3964 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3965 /* route does not get solo propagated to it */
3969 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3970 /* this route is a part of the same solo group as the route
3971 * that was changed. Changing that route did change or will
3972 * change all group members appropriately, so we can ignore it
3977 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3983 } else if (_listen_cnt > 0) {
3990 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3992 boost::shared_ptr<Route> route (wpr.lock());
3998 bool send_changed = false;
4000 if (route->solo_isolate_control()->solo_isolated()) {
4001 if (_solo_isolated_cnt == 0) {
4002 send_changed = true;
4004 _solo_isolated_cnt++;
4005 } else if (_solo_isolated_cnt > 0) {
4006 _solo_isolated_cnt--;
4007 if (_solo_isolated_cnt == 0) {
4008 send_changed = true;
4013 IsolatedChanged (); /* EMIT SIGNAL */
4018 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
4020 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
4022 boost::shared_ptr<Route> route (wpr.lock());
4028 if (Config->get_solo_control_is_listen_control()) {
4029 route_listen_changed (group_override, wpr);
4033 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: self %2 masters %3 transition %4\n", route->name(), route->self_soloed(), route->solo_control()->get_masters_value(), route->solo_control()->transitioned_into_solo()));
4035 if (route->solo_control()->transitioned_into_solo() == 0) {
4036 /* route solo changed by upstream/downstream or clear all solo state; not interesting
4039 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 not self-soloed nor soloed by master (%2), ignoring\n", route->name(), route->solo_control()->get_masters_value()));
4043 boost::shared_ptr<RouteList> r = routes.reader ();
4044 int32_t delta = route->solo_control()->transitioned_into_solo ();
4046 /* the route may be a member of a group that has shared-solo
4047 * semantics. If so, then all members of that group should follow the
4048 * solo of the changed route. But ... this is optional, controlled by a
4049 * Controllable::GroupControlDisposition.
4051 * The first argument to the signal that this method is connected to is the
4052 * GroupControlDisposition value that was used to change solo.
4054 * If the solo change was done with group semantics (either InverseGroup
4055 * (force the entire group to change even if the group shared solo is
4056 * disabled) or UseGroup (use the group, which may or may not have the
4057 * shared solo property enabled)) then as we propagate the change to
4058 * the entire session we should IGNORE THE GROUP that the changed route
4062 RouteGroup* rg = route->route_group ();
4063 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
4065 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
4067 if (delta == 1 && Config->get_exclusive_solo()) {
4069 /* new solo: disable all other solos, but not the group if its solo-enabled */
4071 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4073 if ((*i) == route) {
4074 /* already changed */
4078 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4079 /* route does not get solo propagated to it */
4083 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4084 /* this route is a part of the same solo group as the route
4085 * that was changed. Changing that route did change or will
4086 * change all group members appropriately, so we can ignore it
4092 (*i)->solo_control()->set_value (0.0, group_override);
4096 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
4098 RouteList uninvolved;
4100 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
4102 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4103 bool via_sends_only;
4104 bool in_signal_flow;
4106 if ((*i) == route) {
4107 /* already changed */
4111 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4112 /* route does not get solo propagated to it */
4113 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 excluded from solo because iso = %2 can_solo = %3\n", (*i)->name(), (*i)->solo_isolate_control()->solo_isolated(),
4118 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4119 /* this route is a part of the same solo group as the route
4120 * that was changed. Changing that route did change or will
4121 * change all group members appropriately, so we can ignore it
4127 in_signal_flow = false;
4129 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4131 if ((*i)->feeds (route, &via_sends_only)) {
4132 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4133 if (!via_sends_only) {
4134 if (!route->soloed_by_others_upstream()) {
4135 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4137 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4140 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4142 in_signal_flow = true;
4144 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4147 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4149 if (route->feeds (*i, &via_sends_only)) {
4150 /* propagate solo upstream only if routing other than
4151 sends is involved, but do consider the other route
4152 (*i) to be part of the signal flow even if only
4155 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4159 route->soloed_by_others_downstream(),
4160 route->soloed_by_others_upstream()));
4161 if (!via_sends_only) {
4162 //NB. Triggers Invert Push, which handles soloed by downstream
4163 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4164 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4166 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4168 in_signal_flow = true;
4170 DEBUG_TRACE (DEBUG::Solo, string_compose("\tno feed to %1\n", (*i)->name()) );
4173 if (!in_signal_flow) {
4174 uninvolved.push_back (*i);
4178 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4180 /* now notify that the mute state of the routes not involved in the signal
4181 pathway of the just-solo-changed route may have altered.
4184 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4185 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4186 (*i)->act_on_mute ();
4187 /* Session will emit SoloChanged() after all solo changes are
4188 * complete, which should be used by UIs to update mute status
4194 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4196 /* now figure out if anything that matters is soloed (or is "listening")*/
4198 bool something_soloed = false;
4199 bool something_listening = false;
4200 uint32_t listeners = 0;
4201 uint32_t isolated = 0;
4204 r = routes.reader();
4207 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4208 if ((*i)->can_solo()) {
4209 if (Config->get_solo_control_is_listen_control()) {
4210 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4212 something_listening = true;
4215 (*i)->set_listen (false);
4216 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4217 something_soloed = true;
4222 if ((*i)->solo_isolate_control()->solo_isolated()) {
4227 if (something_soloed != _non_soloed_outs_muted) {
4228 _non_soloed_outs_muted = something_soloed;
4229 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4232 if (something_listening != _listening) {
4233 _listening = something_listening;
4234 SoloActive (_listening);
4237 _listen_cnt = listeners;
4239 if (isolated != _solo_isolated_cnt) {
4240 _solo_isolated_cnt = isolated;
4241 IsolatedChanged (); /* EMIT SIGNAL */
4244 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4245 something_soloed, listeners, isolated));
4248 SoloChanged (); /* EMIT SIGNAL */
4253 Session::muted () const
4255 // TODO consider caching the value on every MuteChanged signal,
4256 // Note that API users may also subscribe to MuteChanged and hence
4257 // this method needs to be called first.
4260 get_stripables (all);
4261 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4262 assert (!(*i)->is_auditioner()); // XXX remove me
4263 if ((*i)->is_monitor()) {
4266 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(*i);
4267 if (r && !r->active()) {
4270 boost::shared_ptr<MuteControl> mc = (*i)->mute_control();
4271 if (mc && mc->muted ()) {
4279 std::vector<boost::weak_ptr<AutomationControl> >
4280 Session::cancel_all_mute ()
4283 get_stripables (all);
4284 std::vector<boost::weak_ptr<AutomationControl> > muted;
4285 boost::shared_ptr<ControlList> cl (new ControlList);
4286 for (StripableList::const_iterator i = all.begin(); i != all.end(); ++i) {
4287 assert (!(*i)->is_auditioner());
4288 if ((*i)->is_monitor()) {
4291 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (*i);
4292 if (r && !r->active()) {
4295 boost::shared_ptr<AutomationControl> ac = (*i)->mute_control();
4296 if (ac && ac->get_value () > 0) {
4298 muted.push_back (boost::weak_ptr<AutomationControl>(ac));
4301 if (!cl->empty ()) {
4302 set_controls (cl, 0.0, PBD::Controllable::UseGroup);
4308 Session::get_stripables (StripableList& sl, PresentationInfo::Flag fl) const
4310 boost::shared_ptr<RouteList> r = routes.reader ();
4311 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4312 if ((*it)->presentation_info ().flags () & fl) {
4317 if (fl & PresentationInfo::VCA) {
4318 VCAList v = _vca_manager->vcas ();
4319 sl.insert (sl.end(), v.begin(), v.end());
4324 Session::get_stripables () const
4326 PresentationInfo::Flag fl = PresentationInfo::AllStripables;
4328 Session::get_stripables (rv, fl);
4329 rv.sort (Stripable::Sorter ());
4334 Session::get_routelist (bool mixer_order, PresentationInfo::Flag fl) const
4336 boost::shared_ptr<RouteList> r = routes.reader ();
4338 for (RouteList::iterator it = r->begin(); it != r->end(); ++it) {
4339 if ((*it)->presentation_info ().flags () & fl) {
4343 rv.sort (Stripable::Sorter (mixer_order));
4347 boost::shared_ptr<RouteList>
4348 Session::get_routes_with_internal_returns() const
4350 boost::shared_ptr<RouteList> r = routes.reader ();
4351 boost::shared_ptr<RouteList> rl (new RouteList);
4353 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4354 if ((*i)->internal_return ()) {
4362 Session::io_name_is_legal (const std::string& name) const
4364 boost::shared_ptr<RouteList> r = routes.reader ();
4366 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4367 if (name == reserved->first) {
4368 if (!route_by_name (reserved->first)) {
4369 /* first instance of a reserved name is allowed for some */
4370 return reserved->second;
4372 /* all other instances of a reserved name are not allowed */
4377 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4378 if ((*i)->name() == name) {
4382 if ((*i)->has_io_processor_named (name)) {
4391 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4394 vector<string> connections;
4396 /* if we are passed only a single route and we're not told to turn
4397 * others off, then just do the simple thing.
4400 if (flip_others == false && rl->size() == 1) {
4401 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4403 mt->set_input_active (onoff);
4408 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4410 PortSet& ps ((*rt)->input()->ports());
4412 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4413 p->get_connections (connections);
4416 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4417 routes_using_input_from (*s, rl2);
4420 /* scan all relevant routes to see if others are on or off */
4422 bool others_are_already_on = false;
4424 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4426 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4432 if ((*r) != (*rt)) {
4433 if (mt->input_active()) {
4434 others_are_already_on = true;
4437 /* this one needs changing */
4438 mt->set_input_active (onoff);
4444 /* globally reverse other routes */
4446 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4447 if ((*r) != (*rt)) {
4448 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4450 mt->set_input_active (!others_are_already_on);
4459 Session::routes_using_input_from (const string& str, RouteList& rl)
4461 boost::shared_ptr<RouteList> r = routes.reader();
4463 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4464 if ((*i)->input()->connected_to (str)) {
4470 boost::shared_ptr<Route>
4471 Session::route_by_name (string name) const
4473 boost::shared_ptr<RouteList> r = routes.reader ();
4475 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4476 if ((*i)->name() == name) {
4481 return boost::shared_ptr<Route> ((Route*) 0);
4484 boost::shared_ptr<Route>
4485 Session::route_by_id (PBD::ID id) const
4487 boost::shared_ptr<RouteList> r = routes.reader ();
4489 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4490 if ((*i)->id() == id) {
4495 return boost::shared_ptr<Route> ((Route*) 0);
4499 boost::shared_ptr<Stripable>
4500 Session::stripable_by_id (PBD::ID id) const
4503 get_stripables (sl);
4505 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4506 if ((*s)->id() == id) {
4511 return boost::shared_ptr<Stripable>();
4514 boost::shared_ptr<Processor>
4515 Session::processor_by_id (PBD::ID id) const
4517 boost::shared_ptr<RouteList> r = routes.reader ();
4519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4520 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4526 return boost::shared_ptr<Processor> ();
4529 boost::shared_ptr<Route>
4530 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4532 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4535 boost::shared_ptr<Stripable>
4536 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4539 PresentationInfo::order_t match_cnt = 0;
4541 get_stripables (sl);
4542 sl.sort (Stripable::Sorter());
4544 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4546 if ((*s)->presentation_info().hidden()) {
4547 /* if the caller didn't explicitly ask for hidden
4548 stripables, ignore hidden ones. This matches
4549 the semantics of the pre-PresentationOrder
4550 "get by RID" logic of Ardour 4.x and earlier.
4552 XXX at some point we should likely reverse
4553 the logic of the flags, because asking for "the
4554 hidden stripables" is not going to be common,
4555 whereas asking for visible ones is normal.
4558 if (! (flags & PresentationInfo::Hidden)) {
4563 if ((*s)->presentation_info().flag_match (flags)) {
4564 if (match_cnt++ == n) {
4570 /* there is no nth stripable that matches the given flags */
4571 return boost::shared_ptr<Stripable>();
4574 boost::shared_ptr<Route>
4575 Session::route_by_selected_count (uint32_t id) const
4577 RouteList r (*(routes.reader ()));
4578 r.sort (Stripable::Sorter());
4580 RouteList::iterator i;
4582 for (i = r.begin(); i != r.end(); ++i) {
4583 if ((*i)->is_selected()) {
4591 return boost::shared_ptr<Route> ();
4595 Session::reassign_track_numbers ()
4599 RouteList r (*(routes.reader ()));
4600 r.sort (Stripable::Sorter());
4602 StateProtector sp (this);
4604 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4605 assert (!(*i)->is_auditioner());
4606 if (boost::dynamic_pointer_cast<Track> (*i)) {
4607 (*i)->set_track_number(++tn);
4609 else if (!(*i)->is_master() && !(*i)->is_monitor()) {
4610 (*i)->set_track_number(--bn);
4613 const uint32_t decimals = ceilf (log10f (tn + 1));
4614 const bool decimals_changed = _track_number_decimals != decimals;
4615 _track_number_decimals = decimals;
4617 if (decimals_changed && config.get_track_name_number ()) {
4618 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4619 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4621 t->resync_track_name();
4624 // trigger GUI re-layout
4625 config.ParameterChanged("track-name-number");
4629 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4630 boost::shared_ptr<RouteList> rl = routes.reader ();
4631 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4632 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4640 Session::playlist_region_added (boost::weak_ptr<Region> w)
4642 boost::shared_ptr<Region> r = w.lock ();
4647 /* These are the operations that are currently in progress... */
4648 list<GQuark> curr = _current_trans_quarks;
4651 /* ...and these are the operations during which we want to update
4652 the session range location markers.
4655 ops.push_back (Operations::capture);
4656 ops.push_back (Operations::paste);
4657 ops.push_back (Operations::duplicate_region);
4658 ops.push_back (Operations::insert_file);
4659 ops.push_back (Operations::insert_region);
4660 ops.push_back (Operations::drag_region_brush);
4661 ops.push_back (Operations::region_drag);
4662 ops.push_back (Operations::selection_grab);
4663 ops.push_back (Operations::region_fill);
4664 ops.push_back (Operations::fill_selection);
4665 ops.push_back (Operations::create_region);
4666 ops.push_back (Operations::region_copy);
4667 ops.push_back (Operations::fixed_time_region_copy);
4670 /* See if any of the current operations match the ones that we want */
4672 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4674 /* If so, update the session range markers */
4676 maybe_update_session_range (r->position (), r->last_sample ());
4680 /** Update the session range markers if a is before the current start or
4681 * b is after the current end.
4684 Session::maybe_update_session_range (samplepos_t a, samplepos_t b)
4690 samplepos_t session_end_marker_shift_samples = session_end_shift * _nominal_sample_rate;
4692 if (_session_range_location == 0) {
4694 set_session_range_location (a, b + session_end_marker_shift_samples);
4698 if (_session_range_is_free && (a < _session_range_location->start())) {
4699 _session_range_location->set_start (a);
4702 if (_session_range_is_free && (b > _session_range_location->end())) {
4703 _session_range_location->set_end (b);
4709 Session::set_session_range_is_free (bool yn)
4711 _session_range_is_free = yn;
4715 Session::playlist_ranges_moved (list<Evoral::RangeMove<samplepos_t> > const & ranges)
4717 for (list<Evoral::RangeMove<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4718 maybe_update_session_range (i->to, i->to + i->length);
4723 Session::playlist_regions_extended (list<Evoral::Range<samplepos_t> > const & ranges)
4725 for (list<Evoral::Range<samplepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4726 maybe_update_session_range (i->from, i->to);
4730 /* Region management */
4732 boost::shared_ptr<Region>
4733 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4735 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4736 RegionFactory::RegionMap::const_iterator i;
4737 boost::shared_ptr<Region> region;
4739 Glib::Threads::Mutex::Lock lm (region_lock);
4741 for (i = regions.begin(); i != regions.end(); ++i) {
4745 if (region->whole_file()) {
4747 if (child->source_equivalent (region)) {
4753 return boost::shared_ptr<Region> ();
4757 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4759 set<boost::shared_ptr<Region> > relevant_regions;
4761 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4762 RegionFactory::get_regions_using_source (*s, relevant_regions);
4765 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4766 set<boost::shared_ptr<Region> >::iterator tmp;
4771 _playlists->destroy_region (*r);
4772 RegionFactory::map_remove (*r);
4774 (*r)->drop_sources ();
4775 (*r)->drop_references ();
4777 relevant_regions.erase (r);
4782 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4785 Glib::Threads::Mutex::Lock ls (source_lock);
4786 /* remove from the main source list */
4787 sources.erase ((*s)->id());
4790 (*s)->mark_for_remove ();
4791 (*s)->drop_references ();
4801 Session::remove_last_capture ()
4803 list<boost::shared_ptr<Source> > srcs;
4805 boost::shared_ptr<RouteList> rl = routes.reader ();
4806 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4807 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4812 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4815 srcs.insert (srcs.end(), l.begin(), l.end());
4820 destroy_sources (srcs);
4822 save_state (_current_snapshot_name);
4828 Session::get_last_capture_sources (std::list<boost::shared_ptr<Source> >& srcs)
4830 boost::shared_ptr<RouteList> rl = routes.reader ();
4831 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4832 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4837 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4840 srcs.insert (srcs.end(), l.begin(), l.end());
4846 /* Source Management */
4849 Session::add_source (boost::shared_ptr<Source> source)
4851 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4852 pair<SourceMap::iterator,bool> result;
4854 entry.first = source->id();
4855 entry.second = source;
4858 Glib::Threads::Mutex::Lock lm (source_lock);
4859 result = sources.insert (entry);
4862 if (result.second) {
4864 /* yay, new source */
4866 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4869 if (!fs->within_session()) {
4870 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4876 boost::shared_ptr<AudioFileSource> afs;
4878 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4879 if (Config->get_auto_analyse_audio()) {
4880 Analyser::queue_source_for_analysis (source, false);
4884 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4886 SourceAdded(source);
4891 Session::remove_source (boost::weak_ptr<Source> src)
4893 if (deletion_in_progress ()) {
4897 SourceMap::iterator i;
4898 boost::shared_ptr<Source> source = src.lock();
4905 Glib::Threads::Mutex::Lock lm (source_lock);
4907 if ((i = sources.find (source->id())) != sources.end()) {
4909 SourceRemoved(source);
4913 if (!in_cleanup () && !loading ()) {
4915 /* save state so we don't end up with a session file
4916 * referring to non-existent sources.
4919 save_state (_current_snapshot_name);
4923 boost::shared_ptr<Source>
4924 Session::source_by_id (const PBD::ID& id)
4926 Glib::Threads::Mutex::Lock lm (source_lock);
4927 SourceMap::iterator i;
4928 boost::shared_ptr<Source> source;
4930 if ((i = sources.find (id)) != sources.end()) {
4937 boost::shared_ptr<AudioFileSource>
4938 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4940 /* Restricted to audio files because only audio sources have channel
4944 Glib::Threads::Mutex::Lock lm (source_lock);
4946 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4947 boost::shared_ptr<AudioFileSource> afs
4948 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4950 if (afs && afs->path() == path && chn == afs->channel()) {
4955 return boost::shared_ptr<AudioFileSource>();
4958 boost::shared_ptr<MidiSource>
4959 Session::midi_source_by_path (const std::string& path, bool need_source_lock) const
4961 /* Restricted to MIDI files because audio sources require a channel
4962 for unique identification, in addition to a path.
4965 Glib::Threads::Mutex::Lock lm (source_lock, Glib::Threads::NOT_LOCK);
4966 if (need_source_lock) {
4970 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4971 boost::shared_ptr<MidiSource> ms
4972 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4973 boost::shared_ptr<FileSource> fs
4974 = boost::dynamic_pointer_cast<FileSource>(s->second);
4976 if (ms && fs && fs->path() == path) {
4981 return boost::shared_ptr<MidiSource>();
4985 Session::count_sources_by_origin (const string& path)
4988 Glib::Threads::Mutex::Lock lm (source_lock);
4990 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4991 boost::shared_ptr<FileSource> fs
4992 = boost::dynamic_pointer_cast<FileSource>(i->second);
4994 if (fs && fs->origin() == path) {
5003 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
5005 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
5006 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
5008 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
5013 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
5015 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
5017 if (Glib::path_is_absolute (filepath)) {
5019 /* rip the session dir from the audiofile source */
5021 string session_path;
5022 bool in_another_session = true;
5024 if (filepath.find (interchange_dir_string) != string::npos) {
5026 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
5027 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
5028 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
5029 session_path = Glib::path_get_dirname (session_path); /* now has session path */
5031 /* see if it is within our session */
5033 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5034 if (i->path == session_path) {
5035 in_another_session = false;
5040 in_another_session = false;
5044 if (in_another_session) {
5045 SessionDirectory sd (session_path);
5046 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
5050 /* 1) if file belongs to this session
5051 * it may be a relative path (interchange/...)
5052 * or just basename (session_state, remove source)
5053 * -> just use the basename
5055 std::string filename = Glib::path_get_basename (filepath);
5058 /* 2) if the file is outside our session dir:
5059 * (imported but not copied) add the path for check-summming */
5061 path = Glib::path_get_dirname (filepath);
5064 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
5068 Session::new_audio_source_path_for_embedded (const std::string& path)
5072 * we know that the filename is already unique because it exists
5073 * out in the filesystem.
5075 * However, when we bring it into the session, we could get a
5078 * Eg. two embedded files:
5083 * When merged into session, these collide.
5085 * There will not be a conflict with in-memory sources
5086 * because when the source was created we already picked
5087 * a unique name for it.
5089 * This collision is not likely to be common, but we have to guard
5090 * against it. So, if there is a collision, take the md5 hash of the
5091 * the path, and use that as the filename instead.
5094 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5095 string base = Glib::path_get_basename (path);
5096 string newpath = Glib::build_filename (sdir.sound_path(), base);
5098 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5102 md5.digestString (path.c_str());
5103 md5.writeToString ();
5104 base = md5.digestChars;
5106 string ext = get_suffix (path);
5113 newpath = Glib::build_filename (sdir.sound_path(), base);
5115 /* if this collides, we're screwed */
5117 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
5118 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
5127 /** Return true if there are no audio file sources that use @param name as
5128 * the filename component of their path.
5130 * Return false otherwise.
5132 * This method MUST ONLY be used to check in-session, mono files since it
5133 * hard-codes the channel of the audio file source we are looking for as zero.
5135 * If/when Ardour supports native files in non-mono formats, the logic here
5136 * will need to be revisited.
5139 Session::audio_source_name_is_unique (const string& name)
5141 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
5142 vector<space_and_path>::iterator i;
5143 uint32_t existing = 0;
5145 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5147 /* note that we search *without* the extension so that
5148 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
5149 in the event that this new name is required for
5150 a file format change.
5153 const string spath = *i;
5155 if (matching_unsuffixed_filename_exists_in (spath, name)) {
5160 /* it is possible that we have the path already
5161 * assigned to a source that has not yet been written
5162 * (ie. the write source for a diskstream). we have to
5163 * check this in order to make sure that our candidate
5164 * path isn't used again, because that can lead to
5165 * two Sources point to the same file with different
5166 * notions of their removability.
5170 string possible_path = Glib::build_filename (spath, name);
5172 if (audio_source_by_path_and_channel (possible_path, 0)) {
5178 return (existing == 0);
5182 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)
5185 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
5187 if (Profile->get_trx() && destructive) {
5189 sstr << setfill ('0') << setw (4) << cnt;
5190 sstr << legalized_base;
5192 sstr << legalized_base;
5194 if (take_required || related_exists) {
5206 } else if (nchan > 2) {
5211 /* XXX what? more than 26 channels! */
5222 /** Return a unique name based on \a base for a new internal audio source */
5224 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5227 string possible_name;
5228 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5230 bool some_related_source_name_exists = false;
5232 legalized = legalize_for_path (base);
5234 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5236 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5238 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5240 if (audio_source_name_is_unique (possible_name)) {
5244 some_related_source_name_exists = true;
5247 error << string_compose(
5248 _("There are already %1 recordings for %2, which I consider too many."),
5249 limit, base) << endmsg;
5251 throw failed_constructor();
5255 /* We've established that the new name does not exist in any session
5256 * directory, so now find out which one we should use for this new
5260 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5262 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5267 /** Return a unique name based on `base` for a new internal MIDI source */
5269 Session::new_midi_source_path (const string& base, bool need_lock)
5271 string possible_path;
5272 string possible_name;
5274 possible_name = legalize_for_path (base);
5276 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5277 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5279 /* - the main session folder is the first in the vector.
5280 * - after checking all locations for file-name uniqueness,
5281 * we keep the one from the last iteration as new file name
5282 * - midi files are small and should just be kept in the main session-folder
5284 * -> reverse the array, check main session folder last and use that as location
5287 std::reverse(sdirs.begin(), sdirs.end());
5290 possible_name = bump_name_once (possible_name, '-');
5292 vector<space_and_path>::iterator i;
5293 uint32_t existing = 0;
5295 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5297 possible_path = Glib::build_filename (*i, possible_name + ".mid");
5299 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5303 if (midi_source_by_path (possible_path, need_lock)) {
5308 if (possible_path.size () >= PATH_MAX) {
5309 error << string_compose(
5310 _("There are already many recordings for %1, resulting in a too long file-path %2."),
5311 base, possible_path) << endmsg;
5316 if (existing == 0) {
5321 /* No need to "find best location" for software/app-based RAID, because
5322 MIDI is so small that we always put it in the same place.
5325 return possible_path;
5329 /** Create a new within-session audio source */
5330 boost::shared_ptr<AudioFileSource>
5331 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5333 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5335 if (!path.empty()) {
5336 return boost::dynamic_pointer_cast<AudioFileSource> (
5337 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, sample_rate(), true, true));
5339 throw failed_constructor ();
5343 /** Create a new within-session MIDI source */
5344 boost::shared_ptr<MidiSource>
5345 Session::create_midi_source_for_session (string const & basic_name)
5347 const string path = new_midi_source_path (basic_name);
5349 if (!path.empty()) {
5350 return boost::dynamic_pointer_cast<SMFSource> (
5351 SourceFactory::createWritable (
5352 DataType::MIDI, *this, path, false, sample_rate()));
5354 throw failed_constructor ();
5358 /** Create a new within-session MIDI source */
5359 boost::shared_ptr<MidiSource>
5360 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5362 /* the caller passes in the track the source will be used in,
5363 so that we can keep the numbering sane.
5365 Rationale: a track with the name "Foo" that has had N
5366 captures carried out so far will ALREADY have a write source
5367 named "Foo-N+1.mid" waiting to be used for the next capture.
5369 If we call new_midi_source_name() we will get "Foo-N+2". But
5370 there is no region corresponding to "Foo-N+1", so when
5371 "Foo-N+2" appears in the track, the gap presents the user
5372 with odd behaviour - why did it skip past Foo-N+1?
5374 We could explain this to the user in some odd way, but
5375 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5378 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5381 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5383 std::string name = track->steal_write_source_name ();
5386 return boost::shared_ptr<MidiSource>();
5389 /* MIDI files are small, just put them in the first location of the
5390 session source search path.
5393 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5395 return boost::dynamic_pointer_cast<SMFSource> (
5396 SourceFactory::createWritable (
5397 DataType::MIDI, *this, path, false, sample_rate()));
5401 Session::playlist_is_active (boost::shared_ptr<Playlist> playlist)
5403 Glib::Threads::Mutex::Lock lm (playlists->lock);
5404 for (SessionPlaylists::List::iterator i = playlists->playlists.begin(); i != playlists->playlists.end(); i++) {
5405 if ( (*i) == playlist ) {
5413 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5415 if (playlist->hidden()) {
5419 _playlists->add (playlist);
5422 playlist->release();
5429 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5431 if (deletion_in_progress ()) {
5435 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5441 _playlists->remove (playlist);
5447 Session::set_audition (boost::shared_ptr<Region> r)
5449 pending_audition_region = r;
5450 add_post_transport_work (PostTransportAudition);
5451 _butler->schedule_transport_work ();
5455 Session::audition_playlist ()
5457 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5458 ev->region.reset ();
5464 Session::register_lua_function (
5465 const std::string& name,
5466 const std::string& script,
5467 const LuaScriptParamList& args
5470 Glib::Threads::Mutex::Lock lm (lua_lock);
5472 lua_State* L = lua.getState();
5474 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5475 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5476 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5477 if ((*i)->optional && !(*i)->is_set) { continue; }
5478 tbl_arg[(*i)->name] = (*i)->value;
5480 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5483 LuaScriptsChanged (); /* EMIT SIGNAL */
5488 Session::unregister_lua_function (const std::string& name)
5490 Glib::Threads::Mutex::Lock lm (lua_lock);
5491 (*_lua_del)(name); // throws luabridge::LuaException
5492 lua.collect_garbage ();
5495 LuaScriptsChanged (); /* EMIT SIGNAL */
5499 std::vector<std::string>
5500 Session::registered_lua_functions ()
5502 Glib::Threads::Mutex::Lock lm (lua_lock);
5503 std::vector<std::string> rv;
5506 luabridge::LuaRef list ((*_lua_list)());
5507 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5508 if (!i.key ().isString ()) { assert(0); continue; }
5509 rv.push_back (i.key ().cast<std::string> ());
5516 static void _lua_print (std::string s) {
5517 std::cout << "SessionLua: " << s << "\n";
5522 Session::try_run_lua (pframes_t nframes)
5524 if (_n_lua_scripts == 0) return;
5525 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5527 try { (*_lua_run)(nframes); } catch (...) { }
5528 lua.collect_garbage_step ();
5533 Session::setup_lua ()
5536 lua.Print.connect (&_lua_print);
5540 "function ArdourSession ()"
5541 " local self = { scripts = {}, instances = {} }"
5543 " local remove = function (n)"
5544 " self.scripts[n] = nil"
5545 " self.instances[n] = nil"
5546 " Session:scripts_changed()" // call back
5549 " local addinternal = function (n, f, a)"
5550 " assert(type(n) == 'string', 'function-name must be string')"
5551 " assert(type(f) == 'function', 'Given script is a not a function')"
5552 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5553 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5554 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5555 " 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 }"
5556 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5557 " Session:scripts_changed()" // call back
5560 " local add = function (n, b, a)"
5561 " assert(type(b) == 'string', 'ByteCode must be string')"
5562 " load (b)()" // assigns f
5563 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5564 " addinternal (n, load(f), a)"
5567 " local run = function (...)"
5568 " for n, s in pairs (self.instances) do"
5569 " local status, err = pcall (s, ...)"
5570 " if not status then"
5571 " print ('fn \"'.. n .. '\": ', err)"
5578 " local cleanup = function ()"
5579 " self.scripts = nil"
5580 " self.instances = nil"
5583 " local list = function ()"
5585 " for n, _ in pairs (self.scripts) do"
5591 " local function basic_serialize (o)"
5592 " if type(o) == \"number\" then"
5593 " return tostring(o)"
5595 " return string.format(\"%q\", o)"
5599 " local function serialize (name, value)"
5600 " local rv = name .. ' = '"
5602 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5603 " return rv .. basic_serialize(value) .. ' '"
5604 " elseif type(value) == \"table\" then"
5606 " for k,v in pairs(value) do"
5607 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5608 " rv = rv .. serialize(fieldname, v) .. ' '"
5609 " collectgarbage()" // string concatenation allocates a new string :(
5612 " elseif type(value) == \"function\" then"
5613 " return rv .. string.format(\"%q\", string.dump(value, true))"
5615 " error('cannot save a ' .. type(value))"
5620 " local save = function ()"
5621 " return (serialize('scripts', self.scripts))"
5624 " local restore = function (state)"
5625 " self.scripts = {}"
5627 " for n, s in pairs (scripts) do"
5628 " addinternal (n, load(s['f']), s['a'])"
5632 " return { run = run, add = add, remove = remove,"
5633 " list = list, restore = restore, save = save, cleanup = cleanup}"
5636 " sess = ArdourSession ()"
5637 " ArdourSession = nil"
5639 "function ardour () end"
5642 lua_State* L = lua.getState();
5645 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5646 lua.do_command ("sess = nil"); // hide it.
5647 lua.do_command ("collectgarbage()");
5649 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5650 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5651 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5652 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5653 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5654 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5655 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5656 } catch (luabridge::LuaException const& e) {
5657 fatal << string_compose (_("programming error: %1"),
5658 std::string ("Failed to setup session Lua interpreter") + e.what ())
5660 abort(); /*NOTREACHED*/
5662 fatal << string_compose (_("programming error: %1"),
5663 X_("Failed to setup session Lua interpreter"))
5665 abort(); /*NOTREACHED*/
5669 LuaBindings::stddef (L);
5670 LuaBindings::common (L);
5671 LuaBindings::dsp (L);
5673 luabridge::push <Session *> (L, this);
5674 lua_setglobal (L, "Session");
5678 Session::scripts_changed ()
5680 assert (!lua_lock.trylock()); // must hold lua_lock
5683 luabridge::LuaRef list ((*_lua_list)());
5685 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5686 if (!i.key ().isString ()) { assert(0); continue; }
5689 _n_lua_scripts = cnt;
5690 } catch (luabridge::LuaException const& e) {
5691 fatal << string_compose (_("programming error: %1"),
5692 std::string ("Indexing Lua Session Scripts failed.") + e.what ())
5694 abort(); /*NOTREACHED*/
5696 fatal << string_compose (_("programming error: %1"),
5697 X_("Indexing Lua Session Scripts failed."))
5699 abort(); /*NOTREACHED*/
5704 Session::non_realtime_set_audition ()
5706 assert (pending_audition_region);
5707 auditioner->audition_region (pending_audition_region);
5708 pending_audition_region.reset ();
5709 AuditionActive (true); /* EMIT SIGNAL */
5713 Session::audition_region (boost::shared_ptr<Region> r)
5715 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5721 Session::cancel_audition ()
5726 if (auditioner->auditioning()) {
5727 auditioner->cancel_audition ();
5728 AuditionActive (false); /* EMIT SIGNAL */
5733 Session::is_auditioning () const
5735 /* can be called before we have an auditioner object */
5737 return auditioner->auditioning();
5744 Session::graph_reordered ()
5746 /* don't do this stuff if we are setting up connections
5747 from a set_state() call or creating new tracks. Ditto for deletion.
5750 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5756 /* force all diskstreams to update their capture offset values to
5757 * reflect any changes in latencies within the graph.
5759 update_route_latency (false, true);
5762 /** @return Number of samples that there is disk space available to write,
5765 boost::optional<samplecnt_t>
5766 Session::available_capture_duration ()
5768 Glib::Threads::Mutex::Lock lm (space_lock);
5770 if (_total_free_4k_blocks_uncertain) {
5771 return boost::optional<samplecnt_t> ();
5774 float sample_bytes_on_disk = 4.0; // keep gcc happy
5776 switch (config.get_native_file_data_format()) {
5778 sample_bytes_on_disk = 4.0;
5782 sample_bytes_on_disk = 3.0;
5786 sample_bytes_on_disk = 2.0;
5790 /* impossible, but keep some gcc versions happy */
5791 fatal << string_compose (_("programming error: %1"),
5792 X_("illegal native file data format"))
5794 abort(); /*NOTREACHED*/
5797 double scale = 4096.0 / sample_bytes_on_disk;
5799 if (_total_free_4k_blocks * scale > (double) max_samplecnt) {
5800 return max_samplecnt;
5803 return (samplecnt_t) floor (_total_free_4k_blocks * scale);
5807 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5810 RCUWriter<BundleList> writer (_bundles);
5811 boost::shared_ptr<BundleList> b = writer.get_copy ();
5812 b->push_back (bundle);
5816 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5823 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5825 bool removed = false;
5828 RCUWriter<BundleList> writer (_bundles);
5829 boost::shared_ptr<BundleList> b = writer.get_copy ();
5830 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5832 if (i != b->end()) {
5839 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5845 boost::shared_ptr<Bundle>
5846 Session::bundle_by_name (string name) const
5848 boost::shared_ptr<BundleList> b = _bundles.reader ();
5850 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5851 if ((*i)->name() == name) {
5856 return boost::shared_ptr<Bundle> ();
5860 Session::tempo_map_changed (const PropertyChange&)
5864 _playlists->update_after_tempo_map_change ();
5866 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5872 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5874 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5875 (*i)->recompute_samples_from_beat ();
5879 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5880 * the given count with the current block size.
5883 Session::ensure_buffers (ChanCount howmany)
5885 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5889 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5891 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5892 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5897 Session::next_insert_id ()
5899 /* this doesn't really loop forever. just think about it */
5902 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5903 if (!insert_bitset[n]) {
5904 insert_bitset[n] = true;
5910 /* none available, so resize and try again */
5912 insert_bitset.resize (insert_bitset.size() + 16, false);
5917 Session::next_send_id ()
5919 /* this doesn't really loop forever. just think about it */
5922 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5923 if (!send_bitset[n]) {
5924 send_bitset[n] = true;
5930 /* none available, so resize and try again */
5932 send_bitset.resize (send_bitset.size() + 16, false);
5937 Session::next_aux_send_id ()
5939 /* this doesn't really loop forever. just think about it */
5942 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5943 if (!aux_send_bitset[n]) {
5944 aux_send_bitset[n] = true;
5950 /* none available, so resize and try again */
5952 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5957 Session::next_return_id ()
5959 /* this doesn't really loop forever. just think about it */
5962 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5963 if (!return_bitset[n]) {
5964 return_bitset[n] = true;
5970 /* none available, so resize and try again */
5972 return_bitset.resize (return_bitset.size() + 16, false);
5977 Session::mark_send_id (uint32_t id)
5979 if (id >= send_bitset.size()) {
5980 send_bitset.resize (id+16, false);
5982 if (send_bitset[id]) {
5983 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5985 send_bitset[id] = true;
5989 Session::mark_aux_send_id (uint32_t id)
5991 if (id >= aux_send_bitset.size()) {
5992 aux_send_bitset.resize (id+16, false);
5994 if (aux_send_bitset[id]) {
5995 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5997 aux_send_bitset[id] = true;
6001 Session::mark_return_id (uint32_t id)
6003 if (id >= return_bitset.size()) {
6004 return_bitset.resize (id+16, false);
6006 if (return_bitset[id]) {
6007 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
6009 return_bitset[id] = true;
6013 Session::mark_insert_id (uint32_t id)
6015 if (id >= insert_bitset.size()) {
6016 insert_bitset.resize (id+16, false);
6018 if (insert_bitset[id]) {
6019 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
6021 insert_bitset[id] = true;
6025 Session::unmark_send_id (uint32_t id)
6027 if (id < send_bitset.size()) {
6028 send_bitset[id] = false;
6033 Session::unmark_aux_send_id (uint32_t id)
6035 if (id < aux_send_bitset.size()) {
6036 aux_send_bitset[id] = false;
6041 Session::unmark_return_id (uint32_t id)
6043 if (deletion_in_progress ()) {
6046 if (id < return_bitset.size()) {
6047 return_bitset[id] = false;
6052 Session::unmark_insert_id (uint32_t id)
6054 if (id < insert_bitset.size()) {
6055 insert_bitset[id] = false;
6060 Session::reset_native_file_format ()
6062 boost::shared_ptr<RouteList> rl = routes.reader ();
6064 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6065 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6067 /* don't save state as we do this, there's no point */
6068 _state_of_the_state = StateOfTheState (_state_of_the_state | InCleanup);
6069 tr->reset_write_sources (false);
6070 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
6076 Session::route_name_unique (string n) const
6078 boost::shared_ptr<RouteList> r = routes.reader ();
6080 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6081 if ((*i)->name() == n) {
6090 Session::route_name_internal (string n) const
6092 if (auditioner && auditioner->name() == n) {
6096 if (_click_io && _click_io->name() == n) {
6104 Session::freeze_all (InterThreadInfo& itt)
6106 boost::shared_ptr<RouteList> r = routes.reader ();
6108 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6110 boost::shared_ptr<Track> t;
6112 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
6113 /* XXX this is wrong because itt.progress will keep returning to zero at the start
6123 boost::shared_ptr<Region>
6124 Session::write_one_track (Track& track, samplepos_t start, samplepos_t end,
6125 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
6126 InterThreadInfo& itt,
6127 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
6128 bool for_export, bool for_freeze)
6130 boost::shared_ptr<Region> result;
6131 boost::shared_ptr<Playlist> playlist;
6132 boost::shared_ptr<Source> source;
6133 ChanCount diskstream_channels (track.n_channels());
6134 samplepos_t position;
6135 samplecnt_t this_chunk;
6137 samplepos_t latency_skip;
6139 samplepos_t len = end - start;
6140 bool need_block_size_reset = false;
6141 ChanCount const max_proc = track.max_processor_streams ();
6142 string legal_playlist_name;
6143 string possible_path;
6145 DataType data_type = track.data_type();
6148 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
6149 end, start) << endmsg;
6153 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
6154 include_endpoint, for_export, for_freeze);
6156 if (data_type == DataType::MIDI && endpoint && !for_export && !for_freeze && diskstream_channels.n(DataType::AUDIO) > 0) {
6157 data_type = DataType::AUDIO;
6160 if (diskstream_channels.n(data_type) < 1) {
6161 error << _("Cannot write a range with no data.") << endmsg;
6165 // block all process callback handling
6167 block_processing ();
6170 // synchronize with AudioEngine::process_callback()
6171 // make sure processing is not currently running
6172 // and processing_blocked() is honored before
6173 // acquiring thread buffers
6174 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6177 _bounce_processing_active = true;
6179 /* call tree *MUST* hold route_lock */
6181 if ((playlist = track.playlist()) == 0) {
6185 legal_playlist_name = legalize_for_path (playlist->name());
6187 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(data_type); ++chan_n) {
6189 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
6190 string path = ((data_type == DataType::AUDIO)
6191 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
6192 : new_midi_source_path (legal_playlist_name));
6199 source = SourceFactory::createWritable (data_type, *this, path, false, sample_rate());
6202 catch (failed_constructor& err) {
6203 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6207 srcs.push_back (source);
6210 /* tell redirects that care that we are about to use a much larger
6211 * blocksize. this will flush all plugins too, so that they are ready
6212 * to be used for this process.
6215 need_block_size_reset = true;
6216 track.set_block_size (bounce_chunk_size);
6217 _engine.main_thread()->get_buffers ();
6221 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6223 /* create a set of reasonably-sized buffers */
6224 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6225 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6227 buffers.set_count (max_proc);
6229 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6230 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6231 boost::shared_ptr<MidiSource> ms;
6233 afs->prepare_for_peakfile_writes ();
6234 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6235 Source::Lock lock(ms->mutex());
6236 ms->mark_streaming_write_started(lock);
6240 while (to_do && !itt.cancel) {
6242 this_chunk = min (to_do, bounce_chunk_size);
6244 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6248 start += this_chunk;
6249 to_do -= this_chunk;
6250 itt.progress = (float) (1.0 - ((double) to_do / len));
6252 if (latency_skip >= bounce_chunk_size) {
6253 latency_skip -= bounce_chunk_size;
6257 const samplecnt_t current_chunk = this_chunk - latency_skip;
6260 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6261 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6262 boost::shared_ptr<MidiSource> ms;
6265 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6268 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6269 Source::Lock lock(ms->mutex());
6271 const MidiBuffer& buf = buffers.get_midi(0);
6272 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6273 Evoral::Event<samplepos_t> ev = *i;
6274 if (!endpoint || for_export) {
6275 ev.set_time(ev.time() - position);
6277 ms->append_event_samples(lock, ev, ms->timeline_position());
6284 /* post-roll, pick up delayed processor output */
6285 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6287 while (latency_skip && !itt.cancel) {
6288 this_chunk = min (latency_skip, bounce_chunk_size);
6289 latency_skip -= this_chunk;
6291 buffers.silence (this_chunk, 0);
6292 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6295 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6296 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6299 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6311 xnow = localtime (&now);
6313 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6314 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6315 boost::shared_ptr<MidiSource> ms;
6318 afs->update_header (position, *xnow, now);
6319 afs->flush_header ();
6320 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6321 Source::Lock lock(ms->mutex());
6322 ms->mark_streaming_write_completed(lock);
6326 /* construct a region to represent the bounced material */
6330 plist.add (Properties::start, 0);
6331 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6332 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6334 result = RegionFactory::create (srcs, plist);
6340 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6341 (*src)->mark_for_remove ();
6342 (*src)->drop_references ();
6346 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6347 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6350 afs->done_with_peakfile_writes ();
6354 _bounce_processing_active = false;
6356 if (need_block_size_reset) {
6357 _engine.main_thread()->drop_buffers ();
6358 track.set_block_size (get_block_size());
6361 unblock_processing ();
6367 Session::gain_automation_buffer() const
6369 return ProcessThread::gain_automation_buffer ();
6373 Session::trim_automation_buffer() const
6375 return ProcessThread::trim_automation_buffer ();
6379 Session::send_gain_automation_buffer() const
6381 return ProcessThread::send_gain_automation_buffer ();
6385 Session::scratch_automation_buffer() const
6387 return ProcessThread::scratch_automation_buffer ();
6391 Session::pan_automation_buffer() const
6393 return ProcessThread::pan_automation_buffer ();
6397 Session::get_silent_buffers (ChanCount count)
6399 return ProcessThread::get_silent_buffers (count);
6403 Session::get_scratch_buffers (ChanCount count, bool silence)
6405 return ProcessThread::get_scratch_buffers (count, silence);
6409 Session::get_noinplace_buffers (ChanCount count)
6411 return ProcessThread::get_noinplace_buffers (count);
6415 Session::get_route_buffers (ChanCount count, bool silence)
6417 return ProcessThread::get_route_buffers (count, silence);
6422 Session::get_mix_buffers (ChanCount count)
6424 return ProcessThread::get_mix_buffers (count);
6428 Session::ntracks () const
6431 boost::shared_ptr<RouteList> r = routes.reader ();
6433 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6434 if (boost::dynamic_pointer_cast<Track> (*i)) {
6443 Session::nbusses () const
6446 boost::shared_ptr<RouteList> r = routes.reader ();
6448 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6449 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6458 Session::nstripables (bool with_monitor) const
6460 uint32_t rv = routes.reader()->size ();
6461 rv += _vca_manager->vcas ().size ();
6475 Session::add_automation_list(AutomationList *al)
6477 automation_lists[al->id()] = al;
6480 /** @return true if there is at least one record-enabled track, otherwise false */
6482 Session::have_rec_enabled_track () const
6484 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6488 Session::have_rec_disabled_track () const
6490 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6493 /** Update the state of our rec-enabled tracks flag */
6495 Session::update_route_record_state ()
6497 boost::shared_ptr<RouteList> rl = routes.reader ();
6498 RouteList::iterator i = rl->begin();
6499 while (i != rl->end ()) {
6501 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6502 if (tr && tr->rec_enable_control()->get_value()) {
6509 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6511 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6513 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6514 RecordStateChanged (); /* EMIT SIGNAL */
6517 for (i = rl->begin(); i != rl->end (); ++i) {
6518 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6519 if (tr && !tr->rec_enable_control()->get_value()) {
6524 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6526 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6528 if (record_status() == Recording && record_arm_state_changed ) {
6529 RecordArmStateChanged ();
6535 Session::listen_position_changed ()
6538 /* skip duing session restore (already taken care of) */
6541 ProcessorChangeBlocker pcb (this);
6542 boost::shared_ptr<RouteList> r = routes.reader ();
6543 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6544 (*i)->listen_position_changed ();
6549 Session::solo_control_mode_changed ()
6551 if (soloing() || listening()) {
6553 /* We can't use ::clear_all_solo_state() here because during
6554 session loading at program startup, that will queue a call
6555 to rt_clear_all_solo_state() that will not execute until
6556 AFTER solo states have been established (thus throwing away
6557 the session's saved solo state). So just explicitly turn
6560 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6562 clear_all_solo_state (get_routes());
6567 /** Called when a property of one of our route groups changes */
6569 Session::route_group_property_changed (RouteGroup* rg)
6571 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6574 /** Called when a route is added to one of our route groups */
6576 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6578 RouteAddedToRouteGroup (rg, r);
6581 /** Called when a route is removed from one of our route groups */
6583 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6585 update_route_record_state ();
6586 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6588 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6589 remove_route_group (*rg);
6593 boost::shared_ptr<AudioTrack>
6594 Session::get_nth_audio_track (int nth) const
6596 boost::shared_ptr<RouteList> rl = routes.reader ();
6597 rl->sort (Stripable::Sorter ());
6599 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6600 if (!boost::dynamic_pointer_cast<AudioTrack> (*r)) {
6607 return boost::dynamic_pointer_cast<AudioTrack> (*r);
6609 return boost::shared_ptr<AudioTrack> ();
6612 boost::shared_ptr<RouteList>
6613 Session::get_tracks () const
6615 boost::shared_ptr<RouteList> rl = routes.reader ();
6616 boost::shared_ptr<RouteList> tl (new RouteList);
6618 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6619 if (boost::dynamic_pointer_cast<Track> (*r)) {
6620 assert (!(*r)->is_auditioner()); // XXX remove me
6627 boost::shared_ptr<RouteList>
6628 Session::get_routes_with_regions_at (samplepos_t const p) const
6630 boost::shared_ptr<RouteList> r = routes.reader ();
6631 boost::shared_ptr<RouteList> rl (new RouteList);
6633 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6634 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6639 boost::shared_ptr<Playlist> pl = tr->playlist ();
6644 if (pl->has_region_at (p)) {
6653 Session::goto_end ()
6655 if (_session_range_location) {
6656 request_locate (_session_range_location->end(), false);
6658 request_locate (0, false);
6663 Session::goto_start (bool and_roll)
6665 if (_session_range_location) {
6666 request_locate (_session_range_location->start(), and_roll);
6668 request_locate (0, and_roll);
6673 Session::current_start_sample () const
6675 return _session_range_location ? _session_range_location->start() : 0;
6679 Session::current_end_sample () const
6681 return _session_range_location ? _session_range_location->end() : 0;
6685 Session::set_session_range_location (samplepos_t start, samplepos_t end)
6687 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6688 _locations->add (_session_range_location);
6692 Session::step_edit_status_change (bool yn)
6698 send = (_step_editors == 0);
6703 send = (_step_editors == 1);
6706 if (_step_editors > 0) {
6712 StepEditStatusChange (val);
6718 Session::start_time_changed (samplepos_t old)
6720 /* Update the auto loop range to match the session range
6721 (unless the auto loop range has been changed by the user)
6724 Location* s = _locations->session_range_location ();
6729 Location* l = _locations->auto_loop_location ();
6731 if (l && l->start() == old) {
6732 l->set_start (s->start(), true);
6738 Session::end_time_changed (samplepos_t old)
6740 /* Update the auto loop range to match the session range
6741 (unless the auto loop range has been changed by the user)
6744 Location* s = _locations->session_range_location ();
6749 Location* l = _locations->auto_loop_location ();
6751 if (l && l->end() == old) {
6752 l->set_end (s->end(), true);
6757 std::vector<std::string>
6758 Session::source_search_path (DataType type) const
6762 if (session_dirs.size() == 1) {
6764 case DataType::AUDIO:
6765 sp.push_back (_session_dir->sound_path());
6767 case DataType::MIDI:
6768 sp.push_back (_session_dir->midi_path());
6772 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6773 SessionDirectory sdir (i->path);
6775 case DataType::AUDIO:
6776 sp.push_back (sdir.sound_path());
6778 case DataType::MIDI:
6779 sp.push_back (sdir.midi_path());
6785 if (type == DataType::AUDIO) {
6786 const string sound_path_2X = _session_dir->sound_path_2X();
6787 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6788 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6789 sp.push_back (sound_path_2X);
6794 // now check the explicit (possibly user-specified) search path
6797 case DataType::AUDIO:
6798 sp += Searchpath(config.get_audio_search_path ());
6800 case DataType::MIDI:
6801 sp += Searchpath(config.get_midi_search_path ());
6809 Session::ensure_search_path_includes (const string& path, DataType type)
6818 case DataType::AUDIO:
6819 sp += Searchpath(config.get_audio_search_path ());
6821 case DataType::MIDI:
6822 sp += Searchpath (config.get_midi_search_path ());
6826 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6827 /* No need to add this new directory if it has the same inode as
6828 an existing one; checking inode rather than name prevents duplicated
6829 directories when we are using symlinks.
6831 On Windows, I think we could just do if (*i == path) here.
6833 if (PBD::equivalent_paths (*i, path)) {
6841 case DataType::AUDIO:
6842 config.set_audio_search_path (sp.to_string());
6844 case DataType::MIDI:
6845 config.set_midi_search_path (sp.to_string());
6851 Session::remove_dir_from_search_path (const string& dir, DataType type)
6856 case DataType::AUDIO:
6857 sp = Searchpath(config.get_audio_search_path ());
6859 case DataType::MIDI:
6860 sp = Searchpath (config.get_midi_search_path ());
6867 case DataType::AUDIO:
6868 config.set_audio_search_path (sp.to_string());
6870 case DataType::MIDI:
6871 config.set_midi_search_path (sp.to_string());
6877 boost::shared_ptr<Speakers>
6878 Session::get_speakers()
6884 Session::unknown_processors () const
6888 boost::shared_ptr<RouteList> r = routes.reader ();
6889 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6890 list<string> t = (*i)->unknown_processors ();
6891 copy (t.begin(), t.end(), back_inserter (p));
6901 Session::set_worst_io_latencies_x (IOChange, void *)
6903 set_worst_io_latencies ();
6907 Session::send_latency_compensation_change ()
6909 /* As a result of Send::set_output_latency()
6910 * or InternalReturn::set_playback_offset ()
6911 * the send's own latency can change (source track
6912 * is aligned with target bus).
6914 * This can only happen be triggered by
6915 * Route::update_signal_latency ()
6916 * when updating the processor latency.
6918 * We need to walk the graph again to take those changes into account
6919 * (we should probably recurse or process the graph in a 2 step process).
6921 ++_send_latency_changes;
6925 Session::update_route_latency (bool playback, bool apply_to_delayline)
6927 /* Note: RouteList is process-graph sorted */
6928 boost::shared_ptr<RouteList> r = routes.reader ();
6931 /* reverse the list so that we work backwards from the last route to run to the first,
6932 * this is not needed, but can help to reduce the iterations for aux-sends.
6934 RouteList* rl = routes.reader().get();
6935 r.reset (new RouteList (*rl));
6936 reverse (r->begin(), r->end());
6939 bool changed = false;
6942 _send_latency_changes = 0;
6943 _worst_route_latency = 0;
6945 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6946 // if (!(*i)->active()) { continue ; } // TODO
6948 if ((*i)->signal_latency () != (l = (*i)->update_signal_latency (apply_to_delayline))) {
6951 _worst_route_latency = std::max (l, _worst_route_latency);
6954 if (_send_latency_changes > 0) {
6955 // only 1 extra iteration is needed (we allow only 1 level of aux-sends)
6956 // BUT.. jack'n'sends'n'bugs
6957 if (++bailout < 5) {
6958 cerr << "restarting Session::update_latency. # of send changes: " << _send_latency_changes << " iteration: " << bailout << endl;
6963 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_route_latency, (changed ? "yes" : "no")));
6969 Session::update_latency (bool playback)
6971 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6973 if (inital_connect_or_deletion_in_progress () || _adding_routes_in_progress || _route_deletion_in_progress) {
6976 if (!_engine.running()) {
6980 /* Note; RouteList is sorted as process-graph */
6981 boost::shared_ptr<RouteList> r = routes.reader ();
6984 /* reverse the list so that we work backwards from the last route to run to the first */
6985 RouteList* rl = routes.reader().get();
6986 r.reset (new RouteList (*rl));
6987 reverse (r->begin(), r->end());
6990 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6991 samplecnt_t latency = (*i)->set_private_port_latencies (playback);
6992 (*i)->set_public_port_latencies (latency, playback);
6996 set_worst_output_latency ();
6997 update_route_latency (true, true);
6999 set_worst_input_latency ();
7000 update_route_latency (false, false);
7003 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
7007 Session::initialize_latencies ()
7010 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
7011 update_latency (false);
7012 update_latency (true);
7015 set_worst_io_latencies ();
7019 Session::set_worst_io_latencies ()
7021 set_worst_output_latency ();
7022 set_worst_input_latency ();
7026 Session::set_worst_output_latency ()
7028 if (inital_connect_or_deletion_in_progress ()) {
7032 _worst_output_latency = 0;
7034 if (!_engine.running()) {
7038 boost::shared_ptr<RouteList> r = routes.reader ();
7040 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7041 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
7044 _worst_output_latency = max (_worst_output_latency, _click_io->latency());
7046 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
7050 Session::set_worst_input_latency ()
7052 if (inital_connect_or_deletion_in_progress ()) {
7056 _worst_input_latency = 0;
7058 if (!_engine.running()) {
7062 boost::shared_ptr<RouteList> r = routes.reader ();
7064 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7065 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
7068 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
7072 Session::update_latency_compensation (bool force_whole_graph)
7074 if (inital_connect_or_deletion_in_progress ()) {
7077 /* this lock is not usually contended, but under certain conditions,
7078 * update_latency_compensation may be called concurrently.
7079 * e.g. drag/drop copy a latent plugin while rolling.
7080 * GUI thread (via route_processors_changed) and
7081 * auto_connect_thread_run may race.
7083 Glib::Threads::Mutex::Lock lx (_update_latency_lock, Glib::Threads::TRY_LOCK);
7085 /* no need to do this twice */
7089 bool some_track_latency_changed = update_route_latency (false, false);
7091 if (some_track_latency_changed || force_whole_graph) {
7092 _engine.update_latencies ();
7093 /* above call will ask the backend up update its latencies, which
7094 * eventually will trigger AudioEngine::latency_callback () and
7095 * call Session::update_latency ()
7098 boost::shared_ptr<RouteList> r = routes.reader ();
7099 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
7100 (*i)->apply_latency_compensation ();
7106 Session::session_name_is_legal (const string& path)
7108 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
7110 for (int i = 0; illegal_chars[i]; ++i) {
7111 if (path.find (illegal_chars[i]) != string::npos) {
7112 return illegal_chars[i];
7120 Session::notify_presentation_info_change ()
7122 if (deletion_in_progress()) {
7126 reassign_track_numbers();
7128 #ifdef USE_TRACKS_CODE_FEATURES
7129 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
7130 * if track order has been changed by user
7132 reconnect_existing_routes(true, true);
7138 Session::operation_in_progress (GQuark op) const
7140 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
7143 boost::shared_ptr<Port>
7144 Session::ltc_output_port () const
7146 return _ltc_output ? _ltc_output->nth (0) : boost::shared_ptr<Port> ();
7150 Session::reconnect_ltc_output ()
7154 string src = Config->get_ltc_output_port();
7156 _ltc_output->disconnect (this);
7158 if (src != _("None") && !src.empty()) {
7159 _ltc_output->nth (0)->connect (src);
7165 Session::set_range_selection (samplepos_t start, samplepos_t end)
7167 _range_selection = Evoral::Range<samplepos_t> (start, end);
7168 #ifdef USE_TRACKS_CODE_FEATURES
7169 follow_playhead_priority ();
7174 Session::set_object_selection (samplepos_t start, samplepos_t end)
7176 _object_selection = Evoral::Range<samplepos_t> (start, end);
7177 #ifdef USE_TRACKS_CODE_FEATURES
7178 follow_playhead_priority ();
7183 Session::clear_range_selection ()
7185 _range_selection = Evoral::Range<samplepos_t> (-1,-1);
7186 #ifdef USE_TRACKS_CODE_FEATURES
7187 follow_playhead_priority ();
7192 Session::clear_object_selection ()
7194 _object_selection = Evoral::Range<samplepos_t> (-1,-1);
7195 #ifdef USE_TRACKS_CODE_FEATURES
7196 follow_playhead_priority ();
7201 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
7202 const ChanCount& input_start,
7203 const ChanCount& output_start,
7204 const ChanCount& input_offset,
7205 const ChanCount& output_offset)
7207 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7208 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
7209 input_start, output_start,
7210 input_offset, output_offset));
7212 auto_connect_thread_wakeup ();
7216 Session::auto_connect_thread_wakeup ()
7218 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
7219 pthread_cond_signal (&_auto_connect_cond);
7220 pthread_mutex_unlock (&_auto_connect_mutex);
7225 Session::queue_latency_recompute ()
7227 g_atomic_int_inc (&_latency_recompute_pending);
7228 auto_connect_thread_wakeup ();
7232 Session::auto_connect (const AutoConnectRequest& ar)
7234 boost::shared_ptr<Route> route = ar.route.lock();
7236 if (!route) { return; }
7238 if (!IO::connecting_legal) {
7242 /* If both inputs and outputs are auto-connected to physical ports,
7243 * use the max of input and output offsets to ensure auto-connected
7244 * port numbers always match up (e.g. the first audio input and the
7245 * first audio output of the route will have the same physical
7246 * port number). Otherwise just use the lowest input or output
7250 const bool in_out_physical =
7251 (Config->get_input_auto_connect() & AutoConnectPhysical)
7252 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7253 && ar.connect_inputs;
7255 const ChanCount in_offset = in_out_physical
7256 ? ChanCount::max(ar.input_offset, ar.output_offset)
7259 const ChanCount out_offset = in_out_physical
7260 ? ChanCount::max(ar.input_offset, ar.output_offset)
7263 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7264 vector<string> physinputs;
7265 vector<string> physoutputs;
7268 /* for connecting track inputs we only want MIDI ports marked
7272 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7274 if (!physinputs.empty() && ar.connect_inputs) {
7275 uint32_t nphysical_in = physinputs.size();
7277 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7280 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7281 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7284 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7290 if (!physoutputs.empty()) {
7291 uint32_t nphysical_out = physoutputs.size();
7292 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7296 * do not create new connections if we reached the limit of physical outputs
7299 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7300 ARDOUR::Profile->get_trx () &&
7301 ar.output_offset.get(*t) == nphysical_out ) {
7305 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7306 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7307 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7308 /* master bus is audio only */
7309 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7310 port = _master_out->input()->ports().port(*t,
7311 i % _master_out->input()->n_ports().get(*t))->name();
7315 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7324 Session::auto_connect_thread_start ()
7326 if (g_atomic_int_get (&_ac_thread_active)) {
7330 while (!_auto_connect_queue.empty ()) {
7331 _auto_connect_queue.pop ();
7334 g_atomic_int_set (&_ac_thread_active, 1);
7335 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7336 g_atomic_int_set (&_ac_thread_active, 0);
7341 Session::auto_connect_thread_terminate ()
7343 if (!g_atomic_int_get (&_ac_thread_active)) {
7348 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7349 while (!_auto_connect_queue.empty ()) {
7350 _auto_connect_queue.pop ();
7354 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7355 * fail to wakeup the thread.
7358 pthread_mutex_lock (&_auto_connect_mutex);
7359 g_atomic_int_set (&_ac_thread_active, 0);
7360 pthread_cond_signal (&_auto_connect_cond);
7361 pthread_mutex_unlock (&_auto_connect_mutex);
7364 pthread_join (_auto_connect_thread, &status);
7368 Session::auto_connect_thread (void *arg)
7370 Session *s = static_cast<Session *>(arg);
7371 s->auto_connect_thread_run ();
7377 Session::auto_connect_thread_run ()
7379 pthread_set_name (X_("autoconnect"));
7380 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7381 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7382 pthread_mutex_lock (&_auto_connect_mutex);
7383 while (g_atomic_int_get (&_ac_thread_active)) {
7385 if (!_auto_connect_queue.empty ()) {
7386 // Why would we need the process lock ??
7387 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7388 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7389 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7390 // We have control over those, but what does jack do?
7391 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7393 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7394 while (!_auto_connect_queue.empty ()) {
7395 const AutoConnectRequest ar (_auto_connect_queue.front());
7396 _auto_connect_queue.pop ();
7403 if (!actively_recording ()) { // might not be needed,
7404 /* this is only used for updating plugin latencies, the
7405 * graph does not change. so it's safe in general.
7407 * update_latency_compensation ()
7408 * calls DiskWriter::set_capture_offset () which
7409 * modifies the capture-offset, which can be a problem.
7411 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7412 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7413 update_latency_compensation ();
7418 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7419 // jack1 cannot cope with removing ports while processing
7420 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7421 AudioEngine::instance()->clear_pending_port_deletions ();
7424 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7426 pthread_mutex_unlock (&_auto_connect_mutex);
7430 Session::cancel_all_solo ()
7434 get_stripables (sl);
7436 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7437 clear_all_solo_state (routes.reader());
7441 Session::maybe_update_tempo_from_midiclock_tempo (float bpm)
7443 if (_tempo_map->n_tempos() == 1) {
7444 TempoSection& ts (_tempo_map->tempo_section_at_sample (0));
7445 if (fabs (ts.note_types_per_minute() - bpm) > (0.01 * ts.note_types_per_minute())) {
7446 const Tempo tempo (bpm, 4.0, bpm);
7447 std::cerr << "new tempo " << bpm << " old " << ts.note_types_per_minute() << std::endl;
7448 _tempo_map->replace_tempo (ts, tempo, 0.0, 0.0, AudioTime);