2 Copyright (C) 1999-2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
36 #include <boost/algorithm/string/erase.hpp>
38 #include "pbd/basename.h"
39 #include "pbd/convert.h"
40 #include "pbd/error.h"
41 #include "pbd/file_utils.h"
43 #include "pbd/pthread_utils.h"
44 #include "pbd/search_path.h"
45 #include "pbd/stacktrace.h"
46 #include "pbd/stl_delete.h"
47 #include "pbd/replace_all.h"
48 #include "pbd/unwind.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/boost_debug.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/directory_names.h"
70 #ifdef USE_TRACKS_CODE_FEATURES
71 #include "ardour/engine_state_controller.h"
73 #include "ardour/filename_extensions.h"
74 #include "ardour/gain_control.h"
75 #include "ardour/graph.h"
76 #include "ardour/luabindings.h"
77 #include "ardour/midiport_manager.h"
78 #include "ardour/scene_changer.h"
79 #include "ardour/midi_patch_manager.h"
80 #include "ardour/midi_track.h"
81 #include "ardour/midi_ui.h"
82 #include "ardour/operations.h"
83 #include "ardour/playlist.h"
84 #include "ardour/playlist_factory.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/revision.h"
94 #include "ardour/route_graph.h"
95 #include "ardour/route_group.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/solo_isolate_control.h"
102 #include "ardour/source_factory.h"
103 #include "ardour/speakers.h"
104 #include "ardour/tempo.h"
105 #include "ardour/ticker.h"
106 #include "ardour/track.h"
107 #include "ardour/user_bundle.h"
108 #include "ardour/utils.h"
109 #include "ardour/vca_manager.h"
110 #include "ardour/vca.h"
112 #include "midi++/port.h"
113 #include "midi++/mmc.h"
115 #include "LuaBridge/LuaBridge.h"
117 #include "pbd/i18n.h"
119 #include <glibmm/checksum.h>
128 using namespace ARDOUR;
131 bool Session::_disable_all_loaded_plugins = false;
132 bool Session::_bypass_all_loaded_plugins = false;
133 guint Session::_name_id_counter = 0;
135 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
136 PBD::Signal1<void,std::string> Session::Dialog;
137 PBD::Signal0<int> Session::AskAboutPendingState;
138 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
139 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
140 PBD::Signal0<void> Session::SendFeedback;
141 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
143 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
144 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
145 PBD::Signal2<void,std::string, std::string> Session::Exported;
146 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
147 PBD::Signal0<void> Session::Quit;
148 PBD::Signal0<void> Session::FeedbackDetected;
149 PBD::Signal0<void> Session::SuccessfulGraphSort;
150 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
152 const framecnt_t Session::bounce_chunk_size = 8192;
153 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
154 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
156 // seconds should be added after the region exceeds end marker
157 #ifdef USE_TRACKS_CODE_FEATURES
158 const uint32_t Session::session_end_shift = 5;
160 const uint32_t Session::session_end_shift = 0;
163 /** @param snapshot_name Snapshot name, without .ardour suffix */
164 Session::Session (AudioEngine &eng,
165 const string& fullpath,
166 const string& snapshot_name,
167 BusProfile* bus_profile,
169 : playlists (new SessionPlaylists)
171 , process_function (&Session::process_with_events)
172 , _bounce_processing_active (false)
173 , waiting_for_sync_offset (false)
174 , _base_frame_rate (0)
175 , _nominal_frame_rate (0)
176 , _current_frame_rate (0)
177 , transport_sub_state (0)
178 , _record_status (Disabled)
179 , _transport_frame (0)
180 , _session_range_location (0)
181 , _session_range_end_is_free (true)
184 , _transport_speed (0)
185 , _default_transport_speed (1.0)
186 , _last_transport_speed (0)
187 , _target_transport_speed (0.0)
188 , auto_play_legal (false)
189 , _last_slave_transport_frame (0)
190 , maximum_output_latency (0)
191 , _requested_return_frame (-1)
192 , current_block_size (0)
193 , _worst_output_latency (0)
194 , _worst_input_latency (0)
195 , _worst_track_latency (0)
196 , _have_captured (false)
197 , _non_soloed_outs_muted (false)
200 , _solo_isolated_cnt (0)
202 , _was_seamless (Config->get_seamless_loop ())
203 , _under_nsm_control (false)
205 , delta_accumulator_cnt (0)
206 , average_slave_delta (1800) // !!! why 1800 ???
208 , have_first_delta_accumulator (false)
209 , _slave_state (Stopped)
210 , _mtc_active (false)
211 , _ltc_active (false)
212 , post_export_sync (false)
213 , post_export_position (0)
215 , _export_rolling (false)
216 , _realtime_export (false)
217 , _region_export (false)
218 , _export_preroll (0)
219 , _export_latency (0)
220 , _pre_export_mmc_enabled (false)
221 , _name (snapshot_name)
223 , _send_qf_mtc (false)
224 , _pframes_since_last_mtc (0)
226 , loop_changing (false)
228 , _session_dir (new SessionDirectory (fullpath))
229 , _current_snapshot_name (snapshot_name)
231 , state_was_pending (false)
232 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
234 , _save_queued (false)
235 , _last_roll_location (0)
236 , _last_roll_or_reversal_location (0)
237 , _last_record_location (0)
238 , pending_locate_roll (false)
239 , pending_locate_frame (0)
240 , pending_locate_flush (false)
241 , pending_abort (false)
242 , pending_auto_loop (false)
243 , _mempool ("Session", 2097152)
244 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
246 , _butler (new Butler (*this))
247 , _post_transport_work (0)
248 , cumulative_rf_motion (0)
250 , _locations (new Locations (*this))
251 , _ignore_skips_updates (false)
252 , _rt_thread_active (false)
253 , _rt_emit_pending (false)
254 , _ac_thread_active (0)
255 , _latency_recompute_pending (0)
257 , outbound_mtc_timecode_frame (0)
258 , next_quarter_frame_to_send (-1)
259 , _samples_per_timecode_frame (0)
260 , _frames_per_hour (0)
261 , _timecode_frames_per_hour (0)
262 , last_timecode_valid (false)
263 , last_timecode_when (0)
264 , _send_timecode_update (false)
276 , ltc_timecode_offset (0)
277 , ltc_timecode_negative_offset (false)
278 , midi_control_ui (0)
280 , _all_route_group (new RouteGroup (*this, "all"))
281 , routes (new RouteList)
282 , _adding_routes_in_progress (false)
283 , _reconnecting_routes_in_progress (false)
284 , _route_deletion_in_progress (false)
285 , destructive_index (0)
286 , _track_number_decimals(1)
287 , default_fade_steepness (0)
288 , default_fade_msecs (0)
289 , _total_free_4k_blocks (0)
290 , _total_free_4k_blocks_uncertain (false)
291 , no_questions_about_missing_files (false)
294 , _bundles (new BundleList)
295 , _bundle_xml_node (0)
299 , click_emphasis_data (0)
301 , click_emphasis_length (0)
302 , _clicks_cleared (0)
303 , _count_in_samples (0)
304 , _play_range (false)
305 , _range_selection (-1,-1)
306 , _object_selection (-1,-1)
307 , _preroll_record_punch_pos (-1)
308 , _preroll_record_trim_len (0)
310 , first_file_data_format_reset (true)
311 , first_file_header_format_reset (true)
312 , have_looped (false)
313 , _have_rec_enabled_track (false)
314 , _have_rec_disabled_track (true)
316 , _suspend_timecode_transmission (0)
317 , _speakers (new Speakers)
318 , _ignore_route_processor_changes (0)
323 , _vca_manager (new VCAManager (*this))
327 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
329 pthread_mutex_init (&_rt_emit_mutex, 0);
330 pthread_cond_init (&_rt_emit_cond, 0);
332 pthread_mutex_init (&_auto_connect_mutex, 0);
333 pthread_cond_init (&_auto_connect_cond, 0);
335 init_name_id_counter (1); // reset for new sessions, start at 1
336 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
338 pre_engine_init (fullpath); // sets _is_new
344 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
346 #ifdef USE_TRACKS_CODE_FEATURES
347 sr = EngineStateController::instance()->get_current_sample_rate();
349 if (ensure_engine (sr, true)) {
351 throw SessionException (_("Cannot connect to audio/midi engine"));
354 // set samplerate for plugins added early
355 // e.g from templates or MB channelstrip
356 set_block_size (_engine.samples_per_cycle());
357 set_frame_rate (_engine.sample_rate());
359 if (create (mix_template, bus_profile)) {
361 throw SessionException (_("Session initialization failed"));
364 /* if a mix template was provided, then ::create() will
365 * have copied it into the session and we need to load it
366 * so that we have the state ready for ::set_state()
367 * after the engine is started.
369 * Note that we do NOT try to get the sample rate from
370 * the template at this time, though doing so would
371 * be easy if we decided this was an appropriate part
375 if (!mix_template.empty()) {
376 if (load_state (_current_snapshot_name)) {
377 throw SessionException (_("Failed to load template/snapshot state"));
379 store_recent_templates (mix_template);
382 /* load default session properties - if any */
387 if (load_state (_current_snapshot_name)) {
388 throw SessionException (_("Failed to load state"));
391 /* try to get sample rate from XML state so that we
392 * can influence the SR if we set up the audio
397 XMLProperty const * prop;
398 XMLNode const * root (state_tree->root());
399 if ((prop = root->property (X_("sample-rate"))) != 0) {
400 sr = atoi (prop->value());
404 if (ensure_engine (sr, false)) {
406 throw SessionException (_("Cannot connect to audio/midi engine"));
410 if (post_engine_init ()) {
412 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
415 store_recent_sessions (_name, _path);
417 bool was_dirty = dirty();
419 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
421 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
422 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
425 DirtyChanged (); /* EMIT SIGNAL */
428 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
429 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
431 emit_thread_start ();
432 auto_connect_thread_start ();
434 /* hook us up to the engine since we are now completely constructed */
436 BootMessage (_("Connect to engine"));
438 _engine.set_session (this);
439 _engine.reset_timebase ();
441 #ifdef USE_TRACKS_CODE_FEATURES
443 EngineStateController::instance()->set_session(this);
446 if ( ARDOUR::Profile->get_trx () ) {
448 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
449 * each available input must have corresponding track when session starts.
452 uint32_t how_many (0);
454 std::vector<std::string> inputs;
455 EngineStateController::instance()->get_physical_audio_inputs(inputs);
457 how_many = inputs.size();
459 list<boost::shared_ptr<AudioTrack> > tracks;
461 // Track names after driver
462 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
463 string track_name = "";
464 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
466 track_name = inputs[i];
467 replace_all (track_name, "system:capture", "");
469 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
470 tracks.insert(tracks.begin(), single_track.front());
472 } else { // Default track names
473 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
476 if (tracks.size() != how_many) {
478 throw failed_constructor ();
484 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
489 BootMessage (_("Session loading complete"));
501 Session::next_name_id ()
503 return g_atomic_int_add (&_name_id_counter, 1);
507 Session::name_id_counter ()
509 return g_atomic_int_get (&_name_id_counter);
513 Session::init_name_id_counter (guint n)
515 g_atomic_int_set (&_name_id_counter, n);
519 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
521 if (_engine.current_backend() == 0) {
522 /* backend is unknown ... */
523 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
524 if (r.get_value_or (-1) != 0) {
527 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
529 } else if (_engine.setup_required()) {
530 /* backend is known, but setup is needed */
531 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
532 if (r.get_value_or (-1) != 0) {
535 } else if (!_engine.running()) {
536 if (_engine.start()) {
541 /* at this point the engine should be running */
543 if (!_engine.running()) {
547 return immediately_post_engine ();
552 Session::immediately_post_engine ()
554 /* Do various initializations that should take place directly after we
555 * know that the engine is running, but before we either create a
556 * session or set state for an existing one.
559 if (how_many_dsp_threads () > 1) {
560 /* For now, only create the graph if we are using >1 DSP threads, as
561 it is a bit slower than the old code with 1 thread.
563 _process_graph.reset (new Graph (*this));
566 /* every time we reconnect, recompute worst case output latencies */
568 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
570 if (synced_to_engine()) {
571 _engine.transport_stop ();
574 if (config.get_jack_time_master()) {
575 _engine.transport_locate (_transport_frame);
580 BootMessage (_("Set up LTC"));
582 BootMessage (_("Set up Click"));
584 BootMessage (_("Set up standard connections"));
588 catch (failed_constructor& err) {
592 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
594 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
602 vector<void*> debug_pointers;
604 /* if we got to here, leaving pending capture state around
608 remove_pending_capture_state ();
612 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
614 /* disconnect from any and all signals that we are connected to */
616 Port::PortSignalDrop (); /* EMIT SIGNAL */
619 /* shutdown control surface protocols while we still have ports
620 and the engine to move data to any devices.
623 ControlProtocolManager::instance().drop_protocols ();
625 /* stop autoconnecting */
626 auto_connect_thread_terminate ();
628 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
630 _engine.remove_session ();
632 #ifdef USE_TRACKS_CODE_FEATURES
633 EngineStateController::instance()->remove_session();
636 /* deregister all ports - there will be no process or any other
637 * callbacks from the engine any more.
640 Port::PortDrop (); /* EMIT SIGNAL */
644 /* clear history so that no references to objects are held any more */
648 /* clear state tree so that no references to objects are held any more */
653 // unregister all lua functions, drop held references (if any)
655 lua.do_command ("Session = nil");
663 lua.collect_garbage ();
665 /* reset dynamic state version back to default */
666 Stateful::loading_state_version = 0;
668 _butler->drop_references ();
672 delete _all_route_group;
674 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
675 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
679 if (click_data != default_click) {
680 delete [] click_data;
683 if (click_emphasis_data != default_click_emphasis) {
684 delete [] click_emphasis_data;
689 /* need to remove auditioner before monitoring section
690 * otherwise it is re-connected */
693 /* drop references to routes held by the monitoring section
694 * specifically _monitor_out aux/listen references */
695 remove_monitor_section();
697 /* clear out any pending dead wood from RCU managed objects */
702 AudioDiskstream::free_working_buffers();
704 /* tell everyone who is still standing that we're about to die */
707 /* tell everyone to drop references and delete objects as we go */
709 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
710 RegionFactory::delete_all_regions ();
712 /* Do this early so that VCAs no longer hold references to routes */
714 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
717 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
719 /* reset these three references to special routes before we do the usual route delete thing */
721 _master_out.reset ();
722 _monitor_out.reset ();
725 RCUWriter<RouteList> writer (routes);
726 boost::shared_ptr<RouteList> r = writer.get_copy ();
728 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
729 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
730 (*i)->drop_references ();
734 /* writer goes out of scope and updates master */
739 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
740 Glib::Threads::Mutex::Lock lm (source_lock);
741 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
742 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
743 i->second->drop_references ();
749 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
752 emit_thread_terminate ();
754 pthread_cond_destroy (&_rt_emit_cond);
755 pthread_mutex_destroy (&_rt_emit_mutex);
757 pthread_cond_destroy (&_auto_connect_cond);
758 pthread_mutex_destroy (&_auto_connect_mutex);
760 delete _scene_changer; _scene_changer = 0;
761 delete midi_control_ui; midi_control_ui = 0;
763 delete _mmc; _mmc = 0;
764 delete _midi_ports; _midi_ports = 0;
765 delete _locations; _locations = 0;
770 /* clear event queue, the session is gone, nobody is interested in
771 * those anymore, but they do leak memory if not removed
773 while (!immediate_events.empty ()) {
774 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
775 SessionEvent *ev = immediate_events.front ();
776 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
777 immediate_events.pop_front ();
781 case SessionEvent::AutoLoop:
782 case SessionEvent::AutoLoopDeclick:
783 case SessionEvent::Skip:
784 case SessionEvent::PunchIn:
785 case SessionEvent::PunchOut:
786 case SessionEvent::RecordStart:
787 case SessionEvent::StopOnce:
788 case SessionEvent::RangeStop:
789 case SessionEvent::RangeLocate:
793 case SessionEvent::RealTimeOperation:
800 del = del && !_remove_event (ev);
807 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
809 BOOST_SHOW_POINTERS ();
813 Session::setup_ltc ()
817 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
818 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
820 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
821 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
824 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
825 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
826 // TODO use auto-connect thread somehow (needs a route currently)
827 // see note in Session::auto_connect_thread_run() why process lock is needed.
828 reconnect_ltc_input ();
832 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
833 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
836 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
837 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
838 // TODO use auto-connect thread
839 reconnect_ltc_output ();
843 /* fix up names of LTC ports because we don't want the normal
844 * IO style of NAME/TYPE-{in,out}N
847 _ltc_input->nth (0)->set_name (X_("LTC-in"));
848 _ltc_output->nth (0)->set_name (X_("LTC-out"));
852 Session::setup_click ()
856 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
857 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
859 _click_io.reset (new ClickIO (*this, X_("Click")));
860 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
861 _click_gain->activate ();
863 setup_click_state (state_tree->root());
865 setup_click_state (0);
870 Session::setup_click_state (const XMLNode* node)
872 const XMLNode* child = 0;
874 if (node && (child = find_named_node (*node, "Click")) != 0) {
876 /* existing state for Click */
879 if (Stateful::loading_state_version < 3000) {
880 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
882 const XMLNodeList& children (child->children());
883 XMLNodeList::const_iterator i = children.begin();
884 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
886 if (i != children.end()) {
887 c = _click_gain->set_state (**i, Stateful::loading_state_version);
893 _clicking = Config->get_clicking ();
897 error << _("could not setup Click I/O") << endmsg;
904 /* default state for Click: dual-mono to first 2 physical outputs */
907 _engine.get_physical_outputs (DataType::AUDIO, outs);
909 for (uint32_t physport = 0; physport < 2; ++physport) {
910 if (outs.size() > physport) {
911 if (_click_io->add_port (outs[physport], this)) {
912 // relax, even though its an error
917 if (_click_io->n_ports () > ChanCount::ZERO) {
918 _clicking = Config->get_clicking ();
924 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
925 MidiPortFlags include, MidiPortFlags exclude)
927 _engine.get_physical_inputs (type, inputs, include, exclude);
928 _engine.get_physical_outputs (type, outputs, include, exclude);
932 Session::setup_bundles ()
936 RCUWriter<BundleList> writer (_bundles);
937 boost::shared_ptr<BundleList> b = writer.get_copy ();
938 for (BundleList::iterator i = b->begin(); i != b->end();) {
939 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
947 vector<string> inputs[DataType::num_types];
948 vector<string> outputs[DataType::num_types];
950 for (uint32_t i = 0; i < DataType::num_types; ++i) {
951 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
952 MidiPortFlags (0), /* no specific inclusions */
953 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
957 /* Create a set of Bundle objects that map
958 to the physical I/O currently available. We create both
959 mono and stereo bundles, so that the common cases of mono
960 and stereo tracks get bundles to put in their mixer strip
961 in / out menus. There may be a nicer way of achieving that;
962 it doesn't really scale that well to higher channel counts
965 /* mono output bundles */
967 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
969 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
971 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
973 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
976 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
977 c->add_channel (_("mono"), DataType::AUDIO);
978 c->set_port (0, outputs[DataType::AUDIO][np]);
980 add_bundle (c, false);
983 /* stereo output bundles */
985 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
986 if (np + 1 < outputs[DataType::AUDIO].size()) {
988 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
989 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
990 c->add_channel (_("L"), DataType::AUDIO);
991 c->set_port (0, outputs[DataType::AUDIO][np]);
992 c->add_channel (_("R"), DataType::AUDIO);
993 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
995 add_bundle (c, false);
999 /* mono input bundles */
1001 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1003 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1005 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1007 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1010 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1011 c->add_channel (_("mono"), DataType::AUDIO);
1012 c->set_port (0, inputs[DataType::AUDIO][np]);
1014 add_bundle (c, false);
1017 /* stereo input bundles */
1019 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1020 if (np + 1 < inputs[DataType::AUDIO].size()) {
1022 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1024 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1025 c->add_channel (_("L"), DataType::AUDIO);
1026 c->set_port (0, inputs[DataType::AUDIO][np]);
1027 c->add_channel (_("R"), DataType::AUDIO);
1028 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1030 add_bundle (c, false);
1034 /* MIDI input bundles */
1036 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1037 string n = inputs[DataType::MIDI][np];
1039 std::string pn = _engine.get_pretty_name_by_name (n);
1043 boost::erase_first (n, X_("alsa_pcm:"));
1045 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1046 c->add_channel ("", DataType::MIDI);
1047 c->set_port (0, inputs[DataType::MIDI][np]);
1048 add_bundle (c, false);
1051 /* MIDI output bundles */
1053 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1054 string n = outputs[DataType::MIDI][np];
1055 std::string pn = _engine.get_pretty_name_by_name (n);
1059 boost::erase_first (n, X_("alsa_pcm:"));
1061 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1062 c->add_channel ("", DataType::MIDI);
1063 c->set_port (0, outputs[DataType::MIDI][np]);
1064 add_bundle (c, false);
1067 // we trust the backend to only calls us if there's a change
1068 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1072 Session::auto_connect_master_bus ()
1074 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1078 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1079 // In this case it means "Multi Out" output mode
1080 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1084 /* if requested auto-connect the outputs to the first N physical ports.
1087 uint32_t limit = _master_out->n_outputs().n_total();
1088 vector<string> outputs[DataType::num_types];
1090 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1091 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1094 for (uint32_t n = 0; n < limit; ++n) {
1095 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1097 if (outputs[p->type()].size() > n) {
1098 connect_to = outputs[p->type()][n];
1101 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1102 if (_master_out->output()->connect (p, connect_to, this)) {
1103 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1112 Session::remove_monitor_section ()
1114 if (!_monitor_out || Profile->get_trx()) {
1118 /* force reversion to Solo-In-Place */
1119 Config->set_solo_control_is_listen_control (false);
1121 /* if we are auditioning, cancel it ... this is a workaround
1122 to a problem (auditioning does not execute the process graph,
1123 which is needed to remove routes when using >1 core for processing)
1128 /* Hold process lock while doing this so that we don't hear bits and
1129 * pieces of audio as we work on each route.
1132 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1134 /* Connect tracks to monitor section. Note that in an
1135 existing session, the internal sends will already exist, but we want the
1136 routes to notice that they connect to the control out specifically.
1140 boost::shared_ptr<RouteList> r = routes.reader ();
1141 ProcessorChangeBlocker pcb (this, false);
1143 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1145 if ((*x)->is_monitor()) {
1147 } else if ((*x)->is_master()) {
1150 (*x)->remove_aux_or_listen (_monitor_out);
1155 remove_route (_monitor_out);
1156 if (_state_of_the_state & Deletion) {
1160 auto_connect_master_bus ();
1163 auditioner->connect ();
1166 Config->ParameterChanged ("use-monitor-bus");
1170 Session::add_monitor_section ()
1174 if (_monitor_out || !_master_out || Profile->get_trx()) {
1178 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1184 BOOST_MARK_ROUTE(r);
1187 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1188 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1189 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1191 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1196 add_routes (rl, false, false, false, 0);
1198 assert (_monitor_out);
1200 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1201 are undefined, at best.
1204 uint32_t limit = _monitor_out->n_inputs().n_audio();
1208 /* connect the inputs to the master bus outputs. this
1209 * represents a separate data feed from the internal sends from
1210 * each route. as of jan 2011, it allows the monitor section to
1211 * conditionally ignore either the internal sends or the normal
1212 * input feed, but we should really find a better way to do
1216 _master_out->output()->disconnect (this);
1218 for (uint32_t n = 0; n < limit; ++n) {
1219 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1220 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1223 string connect_to = o->name();
1224 if (_monitor_out->input()->connect (p, connect_to, this)) {
1225 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1233 /* if monitor section is not connected, connect it to physical outs
1236 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1238 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1240 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1243 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1245 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1246 Config->get_monitor_bus_preferred_bundle())
1252 /* Monitor bus is audio only */
1254 vector<string> outputs[DataType::num_types];
1256 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1257 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1260 uint32_t mod = outputs[DataType::AUDIO].size();
1261 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1265 for (uint32_t n = 0; n < limit; ++n) {
1267 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1269 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1270 connect_to = outputs[DataType::AUDIO][n % mod];
1273 if (!connect_to.empty()) {
1274 if (_monitor_out->output()->connect (p, connect_to, this)) {
1275 error << string_compose (
1276 _("cannot connect control output %1 to %2"),
1287 /* Hold process lock while doing this so that we don't hear bits and
1288 * pieces of audio as we work on each route.
1291 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1293 /* Connect tracks to monitor section. Note that in an
1294 existing session, the internal sends will already exist, but we want the
1295 routes to notice that they connect to the control out specifically.
1299 boost::shared_ptr<RouteList> rls = routes.reader ();
1301 ProcessorChangeBlocker pcb (this, false /* XXX */);
1303 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1305 if ((*x)->is_monitor()) {
1307 } else if ((*x)->is_master()) {
1310 (*x)->enable_monitor_send ();
1315 auditioner->connect ();
1317 Config->ParameterChanged ("use-monitor-bus");
1321 Session::reset_monitor_section ()
1323 /* Process lock should be held by the caller.*/
1325 if (!_monitor_out || Profile->get_trx()) {
1329 uint32_t limit = _master_out->n_outputs().n_audio();
1331 /* connect the inputs to the master bus outputs. this
1332 * represents a separate data feed from the internal sends from
1333 * each route. as of jan 2011, it allows the monitor section to
1334 * conditionally ignore either the internal sends or the normal
1335 * input feed, but we should really find a better way to do
1339 _master_out->output()->disconnect (this);
1340 _monitor_out->output()->disconnect (this);
1342 // monitor section follow master bus - except midi
1343 ChanCount mon_chn (_master_out->output()->n_ports());
1344 mon_chn.set_midi (0);
1346 _monitor_out->input()->ensure_io (mon_chn, false, this);
1347 _monitor_out->output()->ensure_io (mon_chn, false, this);
1349 for (uint32_t n = 0; n < limit; ++n) {
1350 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1351 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1354 string connect_to = o->name();
1355 if (_monitor_out->input()->connect (p, connect_to, this)) {
1356 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1363 /* connect monitor section to physical outs
1366 if (Config->get_auto_connect_standard_busses()) {
1368 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1370 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1373 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1375 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1376 Config->get_monitor_bus_preferred_bundle())
1382 /* Monitor bus is audio only */
1384 vector<string> outputs[DataType::num_types];
1386 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1387 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1390 uint32_t mod = outputs[DataType::AUDIO].size();
1391 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1395 for (uint32_t n = 0; n < limit; ++n) {
1397 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1399 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1400 connect_to = outputs[DataType::AUDIO][n % mod];
1403 if (!connect_to.empty()) {
1404 if (_monitor_out->output()->connect (p, connect_to, this)) {
1405 error << string_compose (
1406 _("cannot connect control output %1 to %2"),
1417 /* Connect tracks to monitor section. Note that in an
1418 existing session, the internal sends will already exist, but we want the
1419 routes to notice that they connect to the control out specifically.
1423 boost::shared_ptr<RouteList> rls = routes.reader ();
1425 ProcessorChangeBlocker pcb (this, false);
1427 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1429 if ((*x)->is_monitor()) {
1431 } else if ((*x)->is_master()) {
1434 (*x)->enable_monitor_send ();
1440 Session::hookup_io ()
1442 /* stop graph reordering notifications from
1443 causing resorts, etc.
1446 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1450 /* we delay creating the auditioner till now because
1451 it makes its own connections to ports.
1455 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1457 throw failed_constructor ();
1459 a->use_new_diskstream ();
1463 catch (failed_constructor& err) {
1464 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1468 /* load bundles, which we may have postponed earlier on */
1469 if (_bundle_xml_node) {
1470 load_bundles (*_bundle_xml_node);
1471 delete _bundle_xml_node;
1474 /* Tell all IO objects to connect themselves together */
1476 IO::enable_connecting ();
1478 /* Now tell all "floating" ports to connect to whatever
1479 they should be connected to.
1482 AudioEngine::instance()->reconnect_ports ();
1484 /* Anyone who cares about input state, wake up and do something */
1486 IOConnectionsComplete (); /* EMIT SIGNAL */
1488 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1490 /* now handle the whole enchilada as if it was one
1491 graph reorder event.
1496 /* update the full solo state, which can't be
1497 correctly determined on a per-route basis, but
1498 needs the global overview that only the session
1502 update_route_solo_state ();
1506 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1508 boost::shared_ptr<Track> track = wp.lock ();
1513 boost::shared_ptr<Playlist> playlist;
1515 if ((playlist = track->playlist()) != 0) {
1516 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1517 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1518 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1523 Session::record_enabling_legal () const
1525 /* this used to be in here, but survey says.... we don't need to restrict it */
1526 // if (record_status() == Recording) {
1530 if (Config->get_all_safe()) {
1537 Session::set_track_monitor_input_status (bool yn)
1539 boost::shared_ptr<RouteList> rl = routes.reader ();
1540 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1541 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1542 if (tr && tr->rec_enable_control()->get_value()) {
1543 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1544 tr->request_input_monitoring (yn);
1550 Session::auto_punch_start_changed (Location* location)
1552 replace_event (SessionEvent::PunchIn, location->start());
1554 if (get_record_enabled() && config.get_punch_in()) {
1555 /* capture start has been changed, so save new pending state */
1556 save_state ("", true);
1561 Session::auto_punch_end_changed (Location* location)
1563 framepos_t when_to_stop = location->end();
1564 // when_to_stop += _worst_output_latency + _worst_input_latency;
1565 replace_event (SessionEvent::PunchOut, when_to_stop);
1569 Session::auto_punch_changed (Location* location)
1571 framepos_t when_to_stop = location->end();
1573 replace_event (SessionEvent::PunchIn, location->start());
1574 //when_to_stop += _worst_output_latency + _worst_input_latency;
1575 replace_event (SessionEvent::PunchOut, when_to_stop);
1578 /** @param loc A loop location.
1579 * @param pos Filled in with the start time of the required fade-out (in session frames).
1580 * @param length Filled in with the length of the required fade-out.
1583 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1585 pos = max (loc->start(), loc->end() - 64);
1586 length = loc->end() - pos;
1590 Session::auto_loop_changed (Location* location)
1592 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1595 auto_loop_declick_range (location, dcp, dcl);
1597 if (transport_rolling() && play_loop) {
1599 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1601 // if (_transport_frame > location->end()) {
1603 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1604 // relocate to beginning of loop
1605 clear_events (SessionEvent::LocateRoll);
1607 request_locate (location->start(), true);
1610 else if (Config->get_seamless_loop() && !loop_changing) {
1612 // schedule a locate-roll to refill the diskstreams at the
1613 // previous loop end
1614 loop_changing = true;
1616 if (location->end() > last_loopend) {
1617 clear_events (SessionEvent::LocateRoll);
1618 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1624 clear_events (SessionEvent::AutoLoopDeclick);
1625 clear_events (SessionEvent::AutoLoop);
1628 /* possibly move playhead if not rolling; if we are rolling we'll move
1629 to the loop start on stop if that is appropriate.
1634 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1635 if (pos == location->start()) {
1636 request_locate (pos);
1641 last_loopend = location->end();
1646 Session::set_auto_punch_location (Location* location)
1650 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1651 punch_connections.drop_connections();
1652 existing->set_auto_punch (false, this);
1653 remove_event (existing->start(), SessionEvent::PunchIn);
1654 clear_events (SessionEvent::PunchOut);
1655 auto_punch_location_changed (0);
1660 if (location == 0) {
1664 if (location->end() <= location->start()) {
1665 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1669 punch_connections.drop_connections ();
1671 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1672 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1673 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1675 location->set_auto_punch (true, this);
1677 auto_punch_changed (location);
1679 auto_punch_location_changed (location);
1683 Session::set_session_extents (framepos_t start, framepos_t end)
1686 if ((existing = _locations->session_range_location()) == 0) {
1687 //if there is no existing session, we need to make a new session location (should never happen)
1688 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1692 error << _("Session: you can't use that location for session start/end)") << endmsg;
1696 existing->set( start, end );
1702 Session::set_auto_loop_location (Location* location)
1706 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1707 loop_connections.drop_connections ();
1708 existing->set_auto_loop (false, this);
1709 remove_event (existing->end(), SessionEvent::AutoLoop);
1712 auto_loop_declick_range (existing, dcp, dcl);
1713 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1714 auto_loop_location_changed (0);
1719 if (location == 0) {
1723 if (location->end() <= location->start()) {
1724 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1728 last_loopend = location->end();
1730 loop_connections.drop_connections ();
1732 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1733 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1734 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1735 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1737 location->set_auto_loop (true, this);
1739 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1740 // set all tracks to use internal looping
1741 boost::shared_ptr<RouteList> rl = routes.reader ();
1742 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1743 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1744 if (tr && !tr->hidden()) {
1745 tr->set_loop (location);
1750 /* take care of our stuff first */
1752 auto_loop_changed (location);
1754 /* now tell everyone else */
1756 auto_loop_location_changed (location);
1760 Session::update_marks (Location*)
1766 Session::update_skips (Location* loc, bool consolidate)
1768 if (_ignore_skips_updates) {
1772 Locations::LocationList skips;
1775 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1776 consolidate_skips (loc);
1779 sync_locations_to_skips ();
1785 Session::consolidate_skips (Location* loc)
1787 Locations::LocationList all_locations = _locations->list ();
1789 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1791 if (!(*l)->is_skip ()) {
1796 /* don't test against self */
1803 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1804 case Evoral::OverlapInternal:
1805 case Evoral::OverlapExternal:
1806 case Evoral::OverlapStart:
1807 case Evoral::OverlapEnd:
1808 /* adjust new location to cover existing one */
1809 loc->set_start (min (loc->start(), (*l)->start()));
1810 loc->set_end (max (loc->end(), (*l)->end()));
1811 /* we don't need this one any more */
1812 _locations->remove (*l);
1813 /* the location has been deleted, so remove reference to it in our local list */
1814 l = all_locations.erase (l);
1817 case Evoral::OverlapNone:
1825 Session::sync_locations_to_skips ()
1827 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1828 * Session::_sync_locations_to_skips() from the audioengine thread.
1830 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1834 Session::_sync_locations_to_skips ()
1836 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1838 Locations::LocationList const & locs (_locations->list());
1840 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1842 Location* location = *i;
1844 if (location->is_skip() && location->is_skipping()) {
1845 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1853 Session::location_added (Location *location)
1855 if (location->is_auto_punch()) {
1856 set_auto_punch_location (location);
1859 if (location->is_auto_loop()) {
1860 set_auto_loop_location (location);
1863 if (location->is_session_range()) {
1864 /* no need for any signal handling or event setting with the session range,
1865 because we keep a direct reference to it and use its start/end directly.
1867 _session_range_location = location;
1870 if (location->is_mark()) {
1871 /* listen for per-location signals that require us to do any * global updates for marks */
1873 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1874 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1875 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1876 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1879 if (location->is_skip()) {
1880 /* listen for per-location signals that require us to update skip-locate events */
1882 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1883 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1884 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1885 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1887 update_skips (location, true);
1894 Session::location_removed (Location *location)
1896 if (location->is_auto_loop()) {
1897 set_auto_loop_location (0);
1898 set_track_loop (false);
1901 if (location->is_auto_punch()) {
1902 set_auto_punch_location (0);
1905 if (location->is_session_range()) {
1906 /* this is never supposed to happen */
1907 error << _("programming error: session range removed!") << endl;
1910 if (location->is_skip()) {
1912 update_skips (location, false);
1919 Session::locations_changed ()
1921 _locations->apply (*this, &Session::_locations_changed);
1925 Session::_locations_changed (const Locations::LocationList& locations)
1927 /* There was some mass-change in the Locations object.
1929 We might be re-adding a location here but it doesn't actually matter
1930 for all the locations that the Session takes an interest in.
1934 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1935 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1936 location_added (*i);
1940 update_skips (NULL, false);
1944 Session::enable_record ()
1946 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1947 /* no recording at anything except normal speed */
1952 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1954 if (rs == Recording) {
1958 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1960 _last_record_location = _transport_frame;
1961 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1963 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1964 set_track_monitor_input_status (true);
1967 RecordStateChanged ();
1974 Session::set_all_tracks_record_enabled (bool enable )
1976 boost::shared_ptr<RouteList> rl = routes.reader();
1977 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1981 Session::disable_record (bool rt_context, bool force)
1985 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1987 if (!Config->get_latched_record_enable () || force) {
1988 g_atomic_int_set (&_record_status, Disabled);
1989 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1991 if (rs == Recording) {
1992 g_atomic_int_set (&_record_status, Enabled);
1996 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1997 set_track_monitor_input_status (false);
2000 RecordStateChanged (); /* emit signal */
2003 remove_pending_capture_state ();
2005 unset_preroll_record_punch ();
2010 Session::step_back_from_record ()
2012 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2014 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2015 set_track_monitor_input_status (false);
2018 RecordStateChanged (); /* emit signal */
2023 Session::maybe_enable_record (bool rt_context)
2025 if (_step_editors > 0) {
2029 g_atomic_int_set (&_record_status, Enabled);
2031 /* This function is currently called from somewhere other than an RT thread.
2032 * (except maybe lua scripts, which can use rt_context = true)
2033 * This save_state() call therefore doesn't impact anything. Doing it here
2034 * means that we save pending state of which sources the next record will use,
2035 * which gives us some chance of recovering from a crash during the record.
2039 save_state ("", true);
2042 if (_transport_speed) {
2043 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2047 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2048 RecordStateChanged (); /* EMIT SIGNAL */
2055 Session::audible_frame () const
2059 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2060 offset *= transport_speed ();
2062 if (synced_to_engine()) {
2063 /* Note: this is basically just sync-to-JACK */
2064 ret = _engine.transport_frame();
2066 ret = _transport_frame;
2069 if (transport_rolling()) {
2072 /* Check to see if we have passed the first guaranteed
2073 * audible frame past our last start position. if not,
2074 * return that last start point because in terms
2075 * of audible frames, we have not moved yet.
2077 * `Start position' in this context means the time we last
2078 * either started, located, or changed transport direction.
2081 if (_transport_speed > 0.0f) {
2083 if (!play_loop || !have_looped) {
2084 if (ret < _last_roll_or_reversal_location) {
2085 return _last_roll_or_reversal_location;
2089 Location *location = _locations->auto_loop_location();
2090 frameoffset_t lo = location->start() - ret;
2092 ret = location->end () - lo;
2096 } else if (_transport_speed < 0.0f) {
2098 /* XXX wot? no backward looping? */
2100 if (ret > _last_roll_or_reversal_location) {
2101 return _last_roll_or_reversal_location;
2106 return std::max ((framepos_t)0, ret);
2111 Session::preroll_samples (framepos_t pos) const
2113 const float pr = Config->get_preroll_seconds();
2114 if (pos >= 0 && pr < 0) {
2115 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2116 const Meter& meter = _tempo_map->meter_at_frame (pos);
2117 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2122 return pr * frame_rate();
2126 Session::set_frame_rate (framecnt_t frames_per_second)
2128 /** \fn void Session::set_frame_size(framecnt_t)
2129 the AudioEngine object that calls this guarantees
2130 that it will not be called while we are also in
2131 ::process(). Its fine to do things that block
2135 if (_base_frame_rate == 0) {
2136 _base_frame_rate = frames_per_second;
2138 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2139 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2141 _nominal_frame_rate = frames_per_second;
2146 reset_write_sources (false);
2148 // XXX we need some equivalent to this, somehow
2149 // SndFileSource::setup_standard_crossfades (frames_per_second);
2153 /* XXX need to reset/reinstantiate all LADSPA plugins */
2157 Session::set_block_size (pframes_t nframes)
2159 /* the AudioEngine guarantees
2160 that it will not be called while we are also in
2161 ::process(). It is therefore fine to do things that block
2166 current_block_size = nframes;
2170 boost::shared_ptr<RouteList> r = routes.reader ();
2172 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2173 (*i)->set_block_size (nframes);
2176 boost::shared_ptr<RouteList> rl = routes.reader ();
2177 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2178 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2180 tr->set_block_size (nframes);
2184 set_worst_io_latencies ();
2190 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2192 boost::shared_ptr<Route> r2;
2194 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2195 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2199 /* make a copy of the existing list of routes that feed r1 */
2201 Route::FedBy existing (r1->fed_by());
2203 /* for each route that feeds r1, recurse, marking it as feeding
2207 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2208 if (!(r2 = i->r.lock ())) {
2209 /* (*i) went away, ignore it */
2213 /* r2 is a route that feeds r1 which somehow feeds base. mark
2214 base as being fed by r2
2217 rbase->add_fed_by (r2, i->sends_only);
2221 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2225 if (r1->feeds (r2) && r2->feeds (r1)) {
2229 /* now recurse, so that we can mark base as being fed by
2230 all routes that feed r2
2233 trace_terminal (r2, rbase);
2240 Session::resort_routes ()
2242 /* don't do anything here with signals emitted
2243 by Routes during initial setup or while we
2244 are being destroyed.
2247 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2251 if (_route_deletion_in_progress) {
2256 RCUWriter<RouteList> writer (routes);
2257 boost::shared_ptr<RouteList> r = writer.get_copy ();
2258 resort_routes_using (r);
2259 /* writer goes out of scope and forces update */
2263 if (DEBUG_ENABLED(DEBUG::Graph)) {
2264 boost::shared_ptr<RouteList> rl = routes.reader ();
2265 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2266 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2268 const Route::FedBy& fb ((*i)->fed_by());
2270 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2271 boost::shared_ptr<Route> sf = f->r.lock();
2273 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2282 /** This is called whenever we need to rebuild the graph of how we will process
2284 * @param r List of routes, in any order.
2288 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2290 /* We are going to build a directed graph of our routes;
2291 this is where the edges of that graph are put.
2296 /* Go through all routes doing two things:
2298 * 1. Collect the edges of the route graph. Each of these edges
2299 * is a pair of routes, one of which directly feeds the other
2300 * either by a JACK connection or by an internal send.
2302 * 2. Begin the process of making routes aware of which other
2303 * routes directly or indirectly feed them. This information
2304 * is used by the solo code.
2307 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2309 /* Clear out the route's list of direct or indirect feeds */
2310 (*i)->clear_fed_by ();
2312 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2314 bool via_sends_only;
2316 /* See if this *j feeds *i according to the current state of the JACK
2317 connections and internal sends.
2319 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2320 /* add the edge to the graph (part #1) */
2321 edges.add (*j, *i, via_sends_only);
2322 /* tell the route (for part #2) */
2323 (*i)->add_fed_by (*j, via_sends_only);
2328 /* Attempt a topological sort of the route graph */
2329 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2331 if (sorted_routes) {
2332 /* We got a satisfactory topological sort, so there is no feedback;
2335 Note: the process graph rechain does not require a
2336 topologically-sorted list, but hey ho.
2338 if (_process_graph) {
2339 _process_graph->rechain (sorted_routes, edges);
2342 _current_route_graph = edges;
2344 /* Complete the building of the routes' lists of what directly
2345 or indirectly feeds them.
2347 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2348 trace_terminal (*i, *i);
2351 *r = *sorted_routes;
2354 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2355 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2356 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2360 SuccessfulGraphSort (); /* EMIT SIGNAL */
2363 /* The topological sort failed, so we have a problem. Tell everyone
2364 and stick to the old graph; this will continue to be processed, so
2365 until the feedback is fixed, what is played back will not quite
2366 reflect what is actually connected. Note also that we do not
2367 do trace_terminal here, as it would fail due to an endless recursion,
2368 so the solo code will think that everything is still connected
2372 FeedbackDetected (); /* EMIT SIGNAL */
2377 /** Find a route name starting with \a base, maybe followed by the
2378 * lowest \a id. \a id will always be added if \a definitely_add_number
2379 * is true on entry; otherwise it will only be added if required
2380 * to make the name unique.
2382 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2383 * The available route name with the lowest ID will be used, and \a id
2384 * will be set to the ID.
2386 * \return false if a route name could not be found, and \a track_name
2387 * and \a id do not reflect a free route name.
2390 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2392 /* the base may conflict with ports that do not belong to existing
2393 routes, but hidden objects like the click track. So check port names
2394 before anything else.
2397 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2398 if (base == reserved->first) {
2399 /* Check if this reserved name already exists, and if
2400 so, disallow it without a numeric suffix.
2402 if (!reserved->second || route_by_name (reserved->first)) {
2403 definitely_add_number = true;
2412 /* if we have "base 1" already, it doesn't make sense to add "base"
2413 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2415 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2416 /* just use the base */
2422 name = string_compose ("%1 %2", base, id);
2424 if (route_by_name (name) == 0) {
2430 } while (id < (UINT_MAX-1));
2435 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2437 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2439 in = ChanCount::ZERO;
2440 out = ChanCount::ZERO;
2442 boost::shared_ptr<RouteList> r = routes.reader ();
2444 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2445 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2446 if (tr && !tr->is_auditioner()) {
2447 in += tr->n_inputs();
2448 out += tr->n_outputs();
2454 Session::default_track_name_pattern (DataType t)
2457 case DataType::AUDIO:
2458 if (Profile->get_trx()) {
2465 case DataType::MIDI:
2472 /** Caller must not hold process lock
2473 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2474 * @param instrument plugin info for the instrument to insert pre-fader, if any
2476 list<boost::shared_ptr<MidiTrack> >
2477 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2478 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2479 RouteGroup* route_group, uint32_t how_many,
2480 string name_template, PresentationInfo::order_t order,
2484 uint32_t track_id = 0;
2486 RouteList new_routes;
2487 list<boost::shared_ptr<MidiTrack> > ret;
2489 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2490 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2493 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2494 error << "cannot find name for new midi track" << endmsg;
2498 boost::shared_ptr<MidiTrack> track;
2501 track.reset (new MidiTrack (*this, track_name, mode));
2503 if (track->init ()) {
2508 track->set_strict_io (true);
2511 track->use_new_diskstream();
2513 BOOST_MARK_TRACK (track);
2516 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2517 if (track->input()->ensure_io (input, false, this)) {
2518 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2522 if (track->output()->ensure_io (output, false, this)) {
2523 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2528 track->non_realtime_input_change();
2531 route_group->add (track);
2534 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2536 new_routes.push_back (track);
2537 ret.push_back (track);
2540 catch (failed_constructor &err) {
2541 error << _("Session: could not create new midi track.") << endmsg;
2545 catch (AudioEngine::PortRegistrationFailure& pfe) {
2547 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;
2555 if (!new_routes.empty()) {
2556 StateProtector sp (this);
2557 if (Profile->get_trx()) {
2558 add_routes (new_routes, false, false, false, order);
2560 add_routes (new_routes, true, true, false, order);
2564 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2565 PluginPtr plugin = instrument->load (*this);
2567 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2571 plugin->load_preset (*pset);
2573 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2575 pi->set_strict_io (true);
2578 (*r)->add_processor (pi, PreFader);
2580 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2581 (*r)->move_instrument_down (false);
2591 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2592 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2593 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2596 uint32_t bus_id = 0;
2600 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2603 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2604 error << "cannot find name for new midi bus" << endmsg;
2609 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2616 bus->set_strict_io (true);
2619 BOOST_MARK_ROUTE(bus);
2622 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2624 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2625 error << _("cannot configure new midi bus input") << endmsg;
2630 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2631 error << _("cannot configure new midi bus output") << endmsg;
2637 route_group->add (bus);
2640 bus->add_internal_return ();
2641 ret.push_back (bus);
2644 catch (failed_constructor &err) {
2645 error << _("Session: could not create new audio route.") << endmsg;
2649 catch (AudioEngine::PortRegistrationFailure& pfe) {
2650 error << pfe.what() << endmsg;
2660 StateProtector sp (this);
2661 add_routes (ret, false, false, false, order);
2664 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2665 PluginPtr plugin = instrument->load (*this);
2667 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2671 plugin->load_preset (*pset);
2673 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2675 pi->set_strict_io (true);
2678 (*r)->add_processor (pi, PreFader);
2680 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2681 (*r)->move_instrument_down (false);
2693 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2695 boost::shared_ptr<Route> midi_track (wmt.lock());
2701 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2703 if (change.after.n_audio() <= change.before.n_audio()) {
2707 /* new audio ports: make sure the audio goes somewhere useful,
2708 * unless the user has no-auto-connect selected.
2710 * The existing ChanCounts don't matter for this call as they are only
2711 * to do with matching input and output indices, and we are only changing
2714 auto_connect_route (midi_track, false, ChanCount(), change.before);
2718 #ifdef USE_TRACKS_CODE_FEATURES
2721 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2723 return route1->remote_control_id() < route2->remote_control_id();
2727 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2729 // it is not allowed to perform connection
2730 if (!IO::connecting_legal) {
2734 // if we are deleting routes we will call this once at the end
2735 if (_route_deletion_in_progress) {
2739 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2745 // We need to disconnect the route's inputs and outputs first
2746 // basing on autoconnect configuration
2747 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2748 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2750 ChanCount existing_inputs;
2751 ChanCount existing_outputs;
2752 count_existing_track_channels (existing_inputs, existing_outputs);
2754 //ChanCount inputs = ChanCount::ZERO;
2755 //ChanCount outputs = ChanCount::ZERO;
2757 RouteList existing_routes = *routes.reader ();
2758 existing_routes.sort (compare_routes_by_remote_id);
2761 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2763 vector<string> physinputs;
2764 vector<string> physoutputs;
2766 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2767 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2769 uint32_t input_n = 0;
2770 uint32_t output_n = 0;
2771 RouteList::iterator rIter = existing_routes.begin();
2772 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2773 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2774 for (; rIter != existing_routes.end(); ++rIter) {
2775 if (*rIter == _master_out || *rIter == _monitor_out ) {
2779 if (current_output_auto_connection == AutoConnectPhysical) {
2780 (*rIter)->amp()->deactivate();
2781 } else if (current_output_auto_connection == AutoConnectMaster) {
2782 (*rIter)->amp()->activate();
2785 if (reconnectIputs) {
2786 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2788 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2790 if (current_input_auto_connection & AutoConnectPhysical) {
2792 if ( input_n == physinputs.size() ) {
2796 string port = physinputs[input_n];
2798 if (port.empty() ) {
2799 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2802 //GZ: check this; could be heavy
2803 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2809 if (reconnectOutputs) {
2811 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2812 if (current_output_auto_connection & AutoConnectPhysical) {
2814 //GZ: check this; could be heavy
2815 (*rIter)->output()->disconnect (this);
2816 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2818 //GZ: check this; could be heavy
2819 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2821 } else if (current_output_auto_connection & AutoConnectMaster){
2823 if (!reconnect_master) {
2827 //GZ: check this; could be heavy
2828 (*rIter)->output()->disconnect (this);
2831 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2832 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2834 error << error << "Master bus is not available" << endmsg;
2839 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2840 if (current_output_auto_connection & AutoConnectPhysical) {
2842 if ( output_n == physoutputs.size() ) {
2846 string port = physoutputs[output_n];
2848 if (port.empty() ) {
2849 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2852 //GZ: check this; could be heavy
2853 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2856 } else if (current_output_auto_connection & AutoConnectMaster) {
2858 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2862 // connect to master bus
2863 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2865 if (port.empty() ) {
2866 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2870 //GZ: check this; could be heavy
2871 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2878 _master_out->output()->disconnect (this);
2879 auto_connect_master_bus ();
2884 session_routes_reconnected (); /* EMIT SIGNAL */
2888 Session::reconnect_midi_scene_ports(bool inputs)
2892 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2894 scene_in_ptr->disconnect_all ();
2896 std::vector<EngineStateController::MidiPortState> midi_port_states;
2897 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2899 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2901 for (; state_iter != midi_port_states.end(); ++state_iter) {
2902 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2903 scene_in_ptr->connect (state_iter->name);
2910 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2912 if (scene_out_ptr ) {
2913 scene_out_ptr->disconnect_all ();
2915 std::vector<EngineStateController::MidiPortState> midi_port_states;
2916 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2918 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2920 for (; state_iter != midi_port_states.end(); ++state_iter) {
2921 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2922 scene_out_ptr->connect (state_iter->name);
2930 Session::reconnect_mtc_ports ()
2932 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2938 mtc_in_ptr->disconnect_all ();
2940 std::vector<EngineStateController::MidiPortState> midi_port_states;
2941 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2943 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2945 for (; state_iter != midi_port_states.end(); ++state_iter) {
2946 if (state_iter->available && state_iter->mtc_in) {
2947 mtc_in_ptr->connect (state_iter->name);
2951 if (!_midi_ports->mtc_input_port ()->connected () &&
2952 config.get_external_sync () &&
2953 (Config->get_sync_source () == MTC) ) {
2954 config.set_external_sync (false);
2957 if ( ARDOUR::Profile->get_trx () ) {
2958 // Tracks need this signal to update timecode_source_dropdown
2959 MtcOrLtcInputPortChanged (); //emit signal
2964 Session::reconnect_mmc_ports(bool inputs)
2966 if (inputs ) { // get all enabled midi input ports
2968 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2970 mmc_in_ptr->disconnect_all ();
2971 std::vector<std::string> enabled_midi_inputs;
2972 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2974 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2976 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2977 mmc_in_ptr->connect (*port_iter);
2981 } else { // get all enabled midi output ports
2983 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2985 mmc_out_ptr->disconnect_all ();
2986 std::vector<std::string> enabled_midi_outputs;
2987 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2989 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2991 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2992 mmc_out_ptr->connect (*port_iter);
3001 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3003 if (first_new_order == PresentationInfo::max_order) {
3004 /* adding at end, no worries */
3008 /* create a gap in the presentation info to accomodate @param how_many
3012 get_stripables (sl);
3014 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3015 boost::shared_ptr<Stripable> s (*si);
3017 if (s->is_monitor() || s->is_auditioner()) {
3021 if (s->presentation_info().order () >= first_new_order) {
3022 s->set_presentation_order (s->presentation_info().order () + how_many);
3027 /** Caller must not hold process lock
3028 * @param name_template string to use for the start of the name, or "" to use "Audio".
3030 list< boost::shared_ptr<AudioTrack> >
3031 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3032 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3036 uint32_t track_id = 0;
3038 RouteList new_routes;
3039 list<boost::shared_ptr<AudioTrack> > ret;
3041 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3042 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3046 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3047 error << "cannot find name for new audio track" << endmsg;
3051 boost::shared_ptr<AudioTrack> track;
3054 track.reset (new AudioTrack (*this, track_name, mode));
3056 if (track->init ()) {
3060 if (Profile->get_mixbus ()) {
3061 track->set_strict_io (true);
3064 if (ARDOUR::Profile->get_trx ()) {
3065 // TRACKS considers it's not a USE CASE, it's
3066 // a piece of behavior of the session model:
3068 // Gain for a newly created route depends on
3069 // the current output_auto_connect mode:
3071 // 0 for Stereo Out mode
3073 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3074 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3078 track->use_new_diskstream();
3080 BOOST_MARK_TRACK (track);
3083 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3085 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3086 error << string_compose (
3087 _("cannot configure %1 in/%2 out configuration for new audio track"),
3088 input_channels, output_channels)
3093 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3094 error << string_compose (
3095 _("cannot configure %1 in/%2 out configuration for new audio track"),
3096 input_channels, output_channels)
3103 route_group->add (track);
3106 track->non_realtime_input_change();
3108 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3110 new_routes.push_back (track);
3111 ret.push_back (track);
3114 catch (failed_constructor &err) {
3115 error << _("Session: could not create new audio track.") << endmsg;
3119 catch (AudioEngine::PortRegistrationFailure& pfe) {
3121 error << pfe.what() << endmsg;
3129 if (!new_routes.empty()) {
3130 StateProtector sp (this);
3131 if (Profile->get_trx()) {
3132 add_routes (new_routes, false, false, false, order);
3134 add_routes (new_routes, true, true, false, order);
3141 /** Caller must not hold process lock.
3142 * @param name_template string to use for the start of the name, or "" to use "Bus".
3145 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3146 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3149 uint32_t bus_id = 0;
3153 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3156 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3157 error << "cannot find name for new audio bus" << endmsg;
3162 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3168 if (Profile->get_mixbus ()) {
3169 bus->set_strict_io (true);
3172 BOOST_MARK_ROUTE(bus);
3175 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3177 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3178 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3179 input_channels, output_channels)
3185 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3186 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3187 input_channels, output_channels)
3194 route_group->add (bus);
3197 bus->add_internal_return ();
3198 ret.push_back (bus);
3201 catch (failed_constructor &err) {
3202 error << _("Session: could not create new audio route.") << endmsg;
3206 catch (AudioEngine::PortRegistrationFailure& pfe) {
3207 error << pfe.what() << endmsg;
3217 StateProtector sp (this);
3218 if (Profile->get_trx()) {
3219 add_routes (ret, false, false, false, order);
3221 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3230 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3231 PlaylistDisposition pd)
3235 if (!tree.read (template_path.c_str())) {
3239 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3243 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3246 uint32_t number = 0;
3247 const uint32_t being_added = how_many;
3248 /* This will prevent the use of any existing XML-provided PBD::ID
3251 Stateful::ForceIDRegeneration force_ids;
3252 IO::disable_connecting ();
3256 /* We're going to modify the node contents a bit so take a
3257 * copy. The node may be re-used when duplicating more than once.
3260 XMLNode node_copy (node);
3265 if (!name_base.empty()) {
3267 /* if we're adding more than one routes, force
3268 * all the names of the new routes to be
3269 * numbered, via the final parameter.
3272 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3273 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3279 string const route_name = node_copy.property(X_("name"))->value ();
3281 /* generate a new name by adding a number to the end of the template name */
3282 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3283 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3284 abort(); /*NOTREACHED*/
3288 /* set this name in the XML description that we are about to use */
3290 if (pd == CopyPlaylist) {
3291 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3293 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3294 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3295 // Use same name as Route::set_name_in_state so playlist copy
3296 // is picked up when creating the Route in XMLRouteFactory below
3297 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3298 playlist->reset_shares ();
3300 } else if (pd == SharePlaylist) {
3301 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3303 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3304 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3305 playlist->share_with ((node_copy.property (X_("id")))->value());
3309 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3311 Route::set_name_in_state (node_copy, name, rename_playlist);
3313 /* trim bitslots from listen sends so that new ones are used */
3314 XMLNodeList children = node_copy.children ();
3315 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3316 if ((*i)->name() == X_("Processor")) {
3317 /* ForceIDRegeneration does not catch the following */
3318 XMLProperty const * role = (*i)->property (X_("role"));
3319 XMLProperty const * type = (*i)->property (X_("type"));
3320 if (role && role->value() == X_("Aux")) {
3321 /* check if the target bus exists.
3322 * we should not save aux-sends in templates.
3324 XMLProperty const * target = (*i)->property (X_("target"));
3326 (*i)->add_property ("type", "dangling-aux-send");
3329 boost::shared_ptr<Route> r = route_by_id (target->value());
3330 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3331 (*i)->add_property ("type", "dangling-aux-send");
3335 if (role && role->value() == X_("Listen")) {
3336 (*i)->remove_property (X_("bitslot"));
3338 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3340 Delivery::Role xrole;
3341 uint32_t bitslot = 0;
3342 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3343 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3344 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3345 (*i)->remove_property (X_("bitslot"));
3346 (*i)->remove_property (X_("name"));
3347 (*i)->add_property ("bitslot", buf);
3348 (*i)->add_property ("name", name);
3350 else if (type && type->value() == X_("intreturn")) {
3351 (*i)->remove_property (X_("bitslot"));
3352 (*i)->add_property ("ignore-bitslot", "1");
3354 else if (type && type->value() == X_("return")) {
3355 // Return::set_state() generates a new one
3356 (*i)->remove_property (X_("bitslot"));
3358 else if (type && type->value() == X_("port")) {
3359 // PortInsert::set_state() handles the bitslot
3360 (*i)->remove_property (X_("bitslot"));
3361 (*i)->add_property ("ignore-name", "1");
3366 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3369 error << _("Session: cannot create track/bus from template description") << endmsg;
3373 if (boost::dynamic_pointer_cast<Track>(route)) {
3374 /* force input/output change signals so that the new diskstream
3375 picks up the configuration of the route. During session
3376 loading this normally happens in a different way.
3379 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3381 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3382 change.after = route->input()->n_ports();
3383 route->input()->changed (change, this);
3384 change.after = route->output()->n_ports();
3385 route->output()->changed (change, this);
3388 ret.push_back (route);
3391 catch (failed_constructor &err) {
3392 error << _("Session: could not create new route from template") << endmsg;
3396 catch (AudioEngine::PortRegistrationFailure& pfe) {
3397 error << pfe.what() << endmsg;
3406 StateProtector sp (this);
3407 if (Profile->get_trx()) {
3408 add_routes (ret, false, false, false, insert_at);
3410 add_routes (ret, true, true, false, insert_at);
3412 IO::enable_connecting ();
3419 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3422 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3423 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3426 error << _("Adding new tracks/busses failed") << endmsg;
3431 update_latency (true);
3432 update_latency (false);
3437 save_state (_current_snapshot_name);
3440 update_route_record_state ();
3442 RouteAdded (new_routes); /* EMIT SIGNAL */
3446 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3448 ChanCount existing_inputs;
3449 ChanCount existing_outputs;
3453 count_existing_track_channels (existing_inputs, existing_outputs);
3456 RCUWriter<RouteList> writer (routes);
3457 boost::shared_ptr<RouteList> r = writer.get_copy ();
3458 r->insert (r->end(), new_routes.begin(), new_routes.end());
3459 n_routes = r->size();
3461 /* if there is no control out and we're not in the middle of loading,
3462 * resort the graph here. if there is a control out, we will resort
3463 * toward the end of this method. if we are in the middle of loading,
3464 * we will resort when done.
3467 if (!_monitor_out && IO::connecting_legal) {
3468 resort_routes_using (r);
3472 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3473 ensure_route_presentation_info_gap (order, new_routes.size());
3475 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3477 boost::weak_ptr<Route> wpr (*x);
3478 boost::shared_ptr<Route> r (*x);
3480 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3481 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3482 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3484 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3485 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3486 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3488 if (r->is_master()) {
3492 if (r->is_monitor()) {
3496 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3498 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3499 track_playlist_changed (boost::weak_ptr<Track> (tr));
3500 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3502 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3504 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3505 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3506 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3510 if (!r->presentation_info().special()) {
3512 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3514 /* presentation info order may already have been set from XML */
3516 if (!r->presentation_info().order_set()) {
3518 if (order == PresentationInfo::max_order) {
3519 /* just add to the end */
3520 r->set_presentation_order (n_routes + added, false);
3521 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3523 r->set_presentation_order (order + added);
3524 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3527 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3531 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3532 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3533 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3535 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3537 r->presentation_info().order(),
3538 enum_2_string (r->presentation_info().flags()),
3539 r->presentation_info()));
3543 if (input_auto_connect || output_auto_connect) {
3544 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3545 existing_inputs += r->n_inputs();
3546 existing_outputs += r->n_outputs();
3552 if (_monitor_out && IO::connecting_legal) {
3553 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3555 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3556 if ((*x)->is_monitor()) {
3558 } else if ((*x)->is_master()) {
3561 (*x)->enable_monitor_send ();
3566 reassign_track_numbers ();
3570 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3572 boost::shared_ptr<RouteList> r = routes.reader ();
3573 boost::shared_ptr<Send> s;
3575 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3576 if ((s = (*i)->internal_send_for (dest)) != 0) {
3577 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3583 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3585 boost::shared_ptr<RouteList> r = routes.reader ();
3586 boost::shared_ptr<Send> s;
3588 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3589 if ((s = (*i)->internal_send_for (dest)) != 0) {
3590 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3596 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3598 boost::shared_ptr<RouteList> r = routes.reader ();
3599 boost::shared_ptr<Send> s;
3601 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3602 if ((s = (*i)->internal_send_for (dest)) != 0) {
3603 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3608 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3610 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3612 boost::shared_ptr<RouteList> r = routes.reader ();
3613 boost::shared_ptr<RouteList> t (new RouteList);
3615 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3616 /* no MIDI sends because there are no MIDI busses yet */
3617 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3622 add_internal_sends (dest, p, t);
3626 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3628 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3629 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3634 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3636 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3640 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3642 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3646 if (!dest->internal_return()) {
3647 dest->add_internal_return ();
3650 sender->add_aux_send (dest, before);
3656 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3658 { // RCU Writer scope
3659 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3660 RCUWriter<RouteList> writer (routes);
3661 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3664 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3666 if (*iter == _master_out) {
3670 /* speed up session deletion, don't do the solo dance */
3671 if (0 == (_state_of_the_state & Deletion)) {
3672 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3677 /* deleting the master out seems like a dumb
3678 idea, but its more of a UI policy issue
3682 if (*iter == _master_out) {
3683 _master_out = boost::shared_ptr<Route> ();
3686 if (*iter == _monitor_out) {
3687 _monitor_out.reset ();
3690 // We need to disconnect the route's inputs and outputs
3692 (*iter)->input()->disconnect (0);
3693 (*iter)->output()->disconnect (0);
3695 /* if the route had internal sends sending to it, remove them */
3696 if ((*iter)->internal_return()) {
3698 boost::shared_ptr<RouteList> r = routes.reader ();
3699 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3700 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3702 (*i)->remove_processor (s);
3707 /* if the monitoring section had a pointer to this route, remove it */
3708 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3709 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3710 ProcessorChangeBlocker pcb (this, false);
3711 (*iter)->remove_aux_or_listen (_monitor_out);
3714 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3715 if (mt && mt->step_editing()) {
3716 if (_step_editors > 0) {
3722 /* writer goes out of scope, forces route list update */
3724 } // end of RCU Writer scope
3726 update_route_solo_state ();
3727 update_latency_compensation ();
3730 /* Re-sort routes to remove the graph's current references to the one that is
3731 * going away, then flush old references out of the graph.
3732 * Wave Tracks: reconnect routes
3735 #ifdef USE_TRACKS_CODE_FEATURES
3736 reconnect_existing_routes(true, false);
3738 routes.flush (); // maybe unsafe, see below.
3742 if (_process_graph && !(_state_of_the_state & Deletion)) {
3743 _process_graph->clear_other_chain ();
3746 /* get rid of it from the dead wood collection in the route list manager */
3747 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3751 /* try to cause everyone to drop their references
3752 * and unregister ports from the backend
3755 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3756 cerr << "Drop references to " << (*iter)->name() << endl;
3757 (*iter)->drop_references ();
3760 if (_state_of_the_state & Deletion) {
3764 PresentationInfo::Change(); /* EMIT SIGNAL */
3766 /* save the new state of the world */
3768 if (save_state (_current_snapshot_name)) {
3769 save_history (_current_snapshot_name);
3772 update_route_record_state ();
3776 Session::remove_route (boost::shared_ptr<Route> route)
3778 boost::shared_ptr<RouteList> rl (new RouteList);
3779 rl->push_back (route);
3784 Session::route_mute_changed ()
3790 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3792 boost::shared_ptr<Route> route (wpr.lock());
3798 assert (Config->get_solo_control_is_listen_control());
3800 if (route->solo_control()->soloed_by_self_or_masters()) {
3802 if (Config->get_exclusive_solo()) {
3804 RouteGroup* rg = route->route_group ();
3805 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3807 boost::shared_ptr<RouteList> r = routes.reader ();
3809 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3810 if ((*i) == route) {
3811 /* already changed */
3815 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3816 /* route does not get solo propagated to it */
3820 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3821 /* this route is a part of the same solo group as the route
3822 * that was changed. Changing that route did change or will
3823 * change all group members appropriately, so we can ignore it
3828 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3834 } else if (_listen_cnt > 0) {
3841 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3843 boost::shared_ptr<Route> route (wpr.lock());
3849 bool send_changed = false;
3851 if (route->solo_isolate_control()->solo_isolated()) {
3852 if (_solo_isolated_cnt == 0) {
3853 send_changed = true;
3855 _solo_isolated_cnt++;
3856 } else if (_solo_isolated_cnt > 0) {
3857 _solo_isolated_cnt--;
3858 if (_solo_isolated_cnt == 0) {
3859 send_changed = true;
3864 IsolatedChanged (); /* EMIT SIGNAL */
3869 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3871 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3873 boost::shared_ptr<Route> route (wpr.lock());
3879 if (Config->get_solo_control_is_listen_control()) {
3880 route_listen_changed (group_override, wpr);
3884 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()));
3886 if (route->solo_control()->transitioned_into_solo() == 0) {
3887 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3890 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()));
3894 boost::shared_ptr<RouteList> r = routes.reader ();
3895 int32_t delta = route->solo_control()->transitioned_into_solo ();
3897 /* the route may be a member of a group that has shared-solo
3898 * semantics. If so, then all members of that group should follow the
3899 * solo of the changed route. But ... this is optional, controlled by a
3900 * Controllable::GroupControlDisposition.
3902 * The first argument to the signal that this method is connected to is the
3903 * GroupControlDisposition value that was used to change solo.
3905 * If the solo change was done with group semantics (either InverseGroup
3906 * (force the entire group to change even if the group shared solo is
3907 * disabled) or UseGroup (use the group, which may or may not have the
3908 * shared solo property enabled)) then as we propagate the change to
3909 * the entire session we should IGNORE THE GROUP that the changed route
3913 RouteGroup* rg = route->route_group ();
3914 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3916 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
3918 if (delta == 1 && Config->get_exclusive_solo()) {
3920 /* new solo: disable all other solos, but not the group if its solo-enabled */
3922 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3924 if ((*i) == route) {
3925 /* already changed */
3929 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3930 /* route does not get solo propagated to it */
3934 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3935 /* this route is a part of the same solo group as the route
3936 * that was changed. Changing that route did change or will
3937 * change all group members appropriately, so we can ignore it
3943 (*i)->solo_control()->set_value (0.0, group_override);
3947 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3949 RouteList uninvolved;
3951 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3953 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3954 bool via_sends_only;
3955 bool in_signal_flow;
3957 if ((*i) == route) {
3958 /* already changed */
3962 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3963 /* route does not get solo propagated to it */
3964 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(),
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
3978 in_signal_flow = false;
3980 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3982 if ((*i)->feeds (route, &via_sends_only)) {
3983 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3984 if (!via_sends_only) {
3985 if (!route->soloed_by_others_upstream()) {
3986 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3988 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3991 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3993 in_signal_flow = true;
3995 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3998 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4000 if (route->feeds (*i, &via_sends_only)) {
4001 /* propagate solo upstream only if routing other than
4002 sends is involved, but do consider the other route
4003 (*i) to be part of the signal flow even if only
4006 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4010 route->soloed_by_others_downstream(),
4011 route->soloed_by_others_upstream()));
4012 if (!via_sends_only) {
4013 //NB. Triggers Invert Push, which handles soloed by downstream
4014 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4015 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4017 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4019 in_signal_flow = true;
4021 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4024 if (!in_signal_flow) {
4025 uninvolved.push_back (*i);
4029 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4031 /* now notify that the mute state of the routes not involved in the signal
4032 pathway of the just-solo-changed route may have altered.
4035 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4036 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4037 (*i)->act_on_mute ();
4038 /* Session will emit SoloChanged() after all solo changes are
4039 * complete, which should be used by UIs to update mute status
4045 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4047 /* now figure out if anything that matters is soloed (or is "listening")*/
4049 bool something_soloed = false;
4050 bool something_listening = false;
4051 uint32_t listeners = 0;
4052 uint32_t isolated = 0;
4055 r = routes.reader();
4058 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4059 if ((*i)->can_solo()) {
4060 if (Config->get_solo_control_is_listen_control()) {
4061 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4063 something_listening = true;
4066 (*i)->set_listen (false);
4067 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4068 something_soloed = true;
4073 if ((*i)->solo_isolate_control()->solo_isolated()) {
4078 if (something_soloed != _non_soloed_outs_muted) {
4079 _non_soloed_outs_muted = something_soloed;
4080 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4083 if (something_listening != _listening) {
4084 _listening = something_listening;
4085 SoloActive (_listening);
4088 _listen_cnt = listeners;
4090 if (isolated != _solo_isolated_cnt) {
4091 _solo_isolated_cnt = isolated;
4092 IsolatedChanged (); /* EMIT SIGNAL */
4095 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4096 something_soloed, listeners, isolated));
4099 SoloChanged (); /* EMIT SIGNAL */
4104 Session::get_stripables (StripableList& sl) const
4106 boost::shared_ptr<RouteList> r = routes.reader ();
4107 sl.insert (sl.end(), r->begin(), r->end());
4109 VCAList v = _vca_manager->vcas ();
4110 sl.insert (sl.end(), v.begin(), v.end());
4113 boost::shared_ptr<RouteList>
4114 Session::get_routes_with_internal_returns() const
4116 boost::shared_ptr<RouteList> r = routes.reader ();
4117 boost::shared_ptr<RouteList> rl (new RouteList);
4119 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4120 if ((*i)->internal_return ()) {
4128 Session::io_name_is_legal (const std::string& name) const
4130 boost::shared_ptr<RouteList> r = routes.reader ();
4132 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4133 if (name == reserved->first) {
4134 if (!route_by_name (reserved->first)) {
4135 /* first instance of a reserved name is allowed */
4138 /* all other instances of a reserved name are not allowed */
4143 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4144 if ((*i)->name() == name) {
4148 if ((*i)->has_io_processor_named (name)) {
4157 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4160 vector<string> connections;
4162 /* if we are passed only a single route and we're not told to turn
4163 * others off, then just do the simple thing.
4166 if (flip_others == false && rl->size() == 1) {
4167 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4169 mt->set_input_active (onoff);
4174 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4176 PortSet& ps ((*rt)->input()->ports());
4178 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4179 p->get_connections (connections);
4182 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4183 routes_using_input_from (*s, rl2);
4186 /* scan all relevant routes to see if others are on or off */
4188 bool others_are_already_on = false;
4190 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4192 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4198 if ((*r) != (*rt)) {
4199 if (mt->input_active()) {
4200 others_are_already_on = true;
4203 /* this one needs changing */
4204 mt->set_input_active (onoff);
4210 /* globally reverse other routes */
4212 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4213 if ((*r) != (*rt)) {
4214 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4216 mt->set_input_active (!others_are_already_on);
4225 Session::routes_using_input_from (const string& str, RouteList& rl)
4227 boost::shared_ptr<RouteList> r = routes.reader();
4229 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4230 if ((*i)->input()->connected_to (str)) {
4236 boost::shared_ptr<Route>
4237 Session::route_by_name (string name) const
4239 boost::shared_ptr<RouteList> r = routes.reader ();
4241 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4242 if ((*i)->name() == name) {
4247 return boost::shared_ptr<Route> ((Route*) 0);
4250 boost::shared_ptr<Route>
4251 Session::route_by_id (PBD::ID id) const
4253 boost::shared_ptr<RouteList> r = routes.reader ();
4255 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4256 if ((*i)->id() == id) {
4261 return boost::shared_ptr<Route> ((Route*) 0);
4264 boost::shared_ptr<Processor>
4265 Session::processor_by_id (PBD::ID id) const
4267 boost::shared_ptr<RouteList> r = routes.reader ();
4269 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4270 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4276 return boost::shared_ptr<Processor> ();
4279 boost::shared_ptr<Track>
4280 Session::track_by_diskstream_id (PBD::ID id) const
4282 boost::shared_ptr<RouteList> r = routes.reader ();
4284 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4285 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4286 if (t && t->using_diskstream_id (id)) {
4291 return boost::shared_ptr<Track> ();
4294 boost::shared_ptr<Route>
4295 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4297 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4300 boost::shared_ptr<Stripable>
4301 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4304 PresentationInfo::order_t match_cnt = 0;
4306 get_stripables (sl);
4307 sl.sort (Stripable::PresentationOrderSorter());
4309 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4311 if ((*s)->presentation_info().hidden()) {
4312 /* if the caller didn't explicitly ask for hidden
4313 stripables, ignore hidden ones. This matches
4314 the semantics of the pre-PresentationOrder
4315 "get by RID" logic of Ardour 4.x and earlier.
4317 XXX at some point we should likely reverse
4318 the logic of the flags, because asking for "the
4319 hidden stripables" is not going to be common,
4320 whereas asking for visible ones is normal.
4323 if (! (flags & PresentationInfo::Hidden)) {
4328 if ((*s)->presentation_info().flag_match (flags)) {
4329 if (match_cnt++ == n) {
4335 /* there is no nth stripable that matches the given flags */
4336 return boost::shared_ptr<Stripable>();
4339 boost::shared_ptr<Route>
4340 Session::route_by_selected_count (uint32_t id) const
4342 boost::shared_ptr<RouteList> r = routes.reader ();
4344 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4345 /* NOT IMPLEMENTED */
4348 return boost::shared_ptr<Route> ((Route*) 0);
4351 struct PresentationOrderSorter {
4352 bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4353 if (a->presentation_info().special() && !b->presentation_info().special()) {
4354 /* a is not ordered, b is; b comes before a */
4356 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4357 /* b is not ordered, a is; a comes before b */
4360 return a->presentation_info().order() < b->presentation_info().order();
4366 Session::reassign_track_numbers ()
4370 RouteList r (*(routes.reader ()));
4371 PresentationOrderSorter sorter;
4374 StateProtector sp (this);
4376 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4377 if (boost::dynamic_pointer_cast<Track> (*i)) {
4378 (*i)->set_track_number(++tn);
4380 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4381 (*i)->set_track_number(--bn);
4384 const uint32_t decimals = ceilf (log10f (tn + 1));
4385 const bool decimals_changed = _track_number_decimals != decimals;
4386 _track_number_decimals = decimals;
4388 if (decimals_changed && config.get_track_name_number ()) {
4389 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4390 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4392 t->resync_track_name();
4395 // trigger GUI re-layout
4396 config.ParameterChanged("track-name-number");
4400 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4401 boost::shared_ptr<RouteList> rl = routes.reader ();
4402 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4403 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4411 Session::playlist_region_added (boost::weak_ptr<Region> w)
4413 boost::shared_ptr<Region> r = w.lock ();
4418 /* These are the operations that are currently in progress... */
4419 list<GQuark> curr = _current_trans_quarks;
4422 /* ...and these are the operations during which we want to update
4423 the session range location markers.
4426 ops.push_back (Operations::capture);
4427 ops.push_back (Operations::paste);
4428 ops.push_back (Operations::duplicate_region);
4429 ops.push_back (Operations::insert_file);
4430 ops.push_back (Operations::insert_region);
4431 ops.push_back (Operations::drag_region_brush);
4432 ops.push_back (Operations::region_drag);
4433 ops.push_back (Operations::selection_grab);
4434 ops.push_back (Operations::region_fill);
4435 ops.push_back (Operations::fill_selection);
4436 ops.push_back (Operations::create_region);
4437 ops.push_back (Operations::region_copy);
4438 ops.push_back (Operations::fixed_time_region_copy);
4441 /* See if any of the current operations match the ones that we want */
4443 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4445 /* If so, update the session range markers */
4447 maybe_update_session_range (r->position (), r->last_frame ());
4451 /** Update the session range markers if a is before the current start or
4452 * b is after the current end.
4455 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4457 if (_state_of_the_state & Loading) {
4461 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4463 if (_session_range_location == 0) {
4465 set_session_range_location (a, b + session_end_marker_shift_samples);
4469 if (a < _session_range_location->start()) {
4470 _session_range_location->set_start (a);
4473 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4474 _session_range_location->set_end (b);
4480 Session::set_end_is_free (bool yn)
4482 _session_range_end_is_free = yn;
4486 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4488 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4489 maybe_update_session_range (i->to, i->to + i->length);
4494 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4496 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4497 maybe_update_session_range (i->from, i->to);
4501 /* Region management */
4503 boost::shared_ptr<Region>
4504 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4506 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4507 RegionFactory::RegionMap::const_iterator i;
4508 boost::shared_ptr<Region> region;
4510 Glib::Threads::Mutex::Lock lm (region_lock);
4512 for (i = regions.begin(); i != regions.end(); ++i) {
4516 if (region->whole_file()) {
4518 if (child->source_equivalent (region)) {
4524 return boost::shared_ptr<Region> ();
4528 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4530 set<boost::shared_ptr<Region> > relevant_regions;
4532 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4533 RegionFactory::get_regions_using_source (*s, relevant_regions);
4536 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4537 set<boost::shared_ptr<Region> >::iterator tmp;
4542 playlists->destroy_region (*r);
4543 RegionFactory::map_remove (*r);
4545 (*r)->drop_sources ();
4546 (*r)->drop_references ();
4548 relevant_regions.erase (r);
4553 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4556 Glib::Threads::Mutex::Lock ls (source_lock);
4557 /* remove from the main source list */
4558 sources.erase ((*s)->id());
4561 (*s)->mark_for_remove ();
4562 (*s)->drop_references ();
4571 Session::remove_last_capture ()
4573 list<boost::shared_ptr<Source> > srcs;
4575 boost::shared_ptr<RouteList> rl = routes.reader ();
4576 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4577 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4582 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4585 srcs.insert (srcs.end(), l.begin(), l.end());
4590 destroy_sources (srcs);
4592 save_state (_current_snapshot_name);
4597 /* Source Management */
4600 Session::add_source (boost::shared_ptr<Source> source)
4602 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4603 pair<SourceMap::iterator,bool> result;
4605 entry.first = source->id();
4606 entry.second = source;
4609 Glib::Threads::Mutex::Lock lm (source_lock);
4610 result = sources.insert (entry);
4613 if (result.second) {
4615 /* yay, new source */
4617 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4620 if (!fs->within_session()) {
4621 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4627 boost::shared_ptr<AudioFileSource> afs;
4629 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4630 if (Config->get_auto_analyse_audio()) {
4631 Analyser::queue_source_for_analysis (source, false);
4635 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4640 Session::remove_source (boost::weak_ptr<Source> src)
4642 if (_state_of_the_state & Deletion) {
4646 SourceMap::iterator i;
4647 boost::shared_ptr<Source> source = src.lock();
4654 Glib::Threads::Mutex::Lock lm (source_lock);
4656 if ((i = sources.find (source->id())) != sources.end()) {
4661 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4663 /* save state so we don't end up with a session file
4664 referring to non-existent sources.
4667 save_state (_current_snapshot_name);
4671 boost::shared_ptr<Source>
4672 Session::source_by_id (const PBD::ID& id)
4674 Glib::Threads::Mutex::Lock lm (source_lock);
4675 SourceMap::iterator i;
4676 boost::shared_ptr<Source> source;
4678 if ((i = sources.find (id)) != sources.end()) {
4685 boost::shared_ptr<AudioFileSource>
4686 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4688 /* Restricted to audio files because only audio sources have channel
4692 Glib::Threads::Mutex::Lock lm (source_lock);
4694 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4695 boost::shared_ptr<AudioFileSource> afs
4696 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4698 if (afs && afs->path() == path && chn == afs->channel()) {
4703 return boost::shared_ptr<AudioFileSource>();
4706 boost::shared_ptr<MidiSource>
4707 Session::midi_source_by_path (const std::string& path) const
4709 /* Restricted to MIDI files because audio sources require a channel
4710 for unique identification, in addition to a path.
4713 Glib::Threads::Mutex::Lock lm (source_lock);
4715 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4716 boost::shared_ptr<MidiSource> ms
4717 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4718 boost::shared_ptr<FileSource> fs
4719 = boost::dynamic_pointer_cast<FileSource>(s->second);
4721 if (ms && fs && fs->path() == path) {
4726 return boost::shared_ptr<MidiSource>();
4730 Session::count_sources_by_origin (const string& path)
4733 Glib::Threads::Mutex::Lock lm (source_lock);
4735 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4736 boost::shared_ptr<FileSource> fs
4737 = boost::dynamic_pointer_cast<FileSource>(i->second);
4739 if (fs && fs->origin() == path) {
4748 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4750 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4751 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4753 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4758 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4760 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4762 if (Glib::path_is_absolute (filepath)) {
4764 /* rip the session dir from the audiofile source */
4766 string session_path;
4767 bool in_another_session = true;
4769 if (filepath.find (interchange_dir_string) != string::npos) {
4771 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4772 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4773 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4774 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4776 /* see if it is within our session */
4778 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4779 if (i->path == session_path) {
4780 in_another_session = false;
4785 in_another_session = false;
4789 if (in_another_session) {
4790 SessionDirectory sd (session_path);
4791 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4795 /* 1) if file belongs to this session
4796 * it may be a relative path (interchange/...)
4797 * or just basename (session_state, remove source)
4798 * -> just use the basename
4800 std::string filename = Glib::path_get_basename (filepath);
4803 /* 2) if the file is outside our session dir:
4804 * (imported but not copied) add the path for check-summming */
4806 path = Glib::path_get_dirname (filepath);
4809 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4813 Session::new_audio_source_path_for_embedded (const std::string& path)
4817 * we know that the filename is already unique because it exists
4818 * out in the filesystem.
4820 * However, when we bring it into the session, we could get a
4823 * Eg. two embedded files:
4828 * When merged into session, these collide.
4830 * There will not be a conflict with in-memory sources
4831 * because when the source was created we already picked
4832 * a unique name for it.
4834 * This collision is not likely to be common, but we have to guard
4835 * against it. So, if there is a collision, take the md5 hash of the
4836 * the path, and use that as the filename instead.
4839 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4840 string base = Glib::path_get_basename (path);
4841 string newpath = Glib::build_filename (sdir.sound_path(), base);
4843 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4847 md5.digestString (path.c_str());
4848 md5.writeToString ();
4849 base = md5.digestChars;
4851 string ext = get_suffix (path);
4858 newpath = Glib::build_filename (sdir.sound_path(), base);
4860 /* if this collides, we're screwed */
4862 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4863 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4872 /** Return true if there are no audio file sources that use @param name as
4873 * the filename component of their path.
4875 * Return false otherwise.
4877 * This method MUST ONLY be used to check in-session, mono files since it
4878 * hard-codes the channel of the audio file source we are looking for as zero.
4880 * If/when Ardour supports native files in non-mono formats, the logic here
4881 * will need to be revisited.
4884 Session::audio_source_name_is_unique (const string& name)
4886 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4887 vector<space_and_path>::iterator i;
4888 uint32_t existing = 0;
4890 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4892 /* note that we search *without* the extension so that
4893 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4894 in the event that this new name is required for
4895 a file format change.
4898 const string spath = *i;
4900 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4905 /* it is possible that we have the path already
4906 * assigned to a source that has not yet been written
4907 * (ie. the write source for a diskstream). we have to
4908 * check this in order to make sure that our candidate
4909 * path isn't used again, because that can lead to
4910 * two Sources point to the same file with different
4911 * notions of their removability.
4915 string possible_path = Glib::build_filename (spath, name);
4917 if (audio_source_by_path_and_channel (possible_path, 0)) {
4923 return (existing == 0);
4927 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)
4930 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4932 if (Profile->get_trx() && destructive) {
4934 sstr << setfill ('0') << setw (4) << cnt;
4935 sstr << legalized_base;
4937 sstr << legalized_base;
4939 if (take_required || related_exists) {
4951 } else if (nchan > 2) {
4956 /* XXX what? more than 26 channels! */
4967 /** Return a unique name based on \a base for a new internal audio source */
4969 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4972 string possible_name;
4973 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4975 bool some_related_source_name_exists = false;
4977 legalized = legalize_for_path (base);
4979 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4981 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4983 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4985 if (audio_source_name_is_unique (possible_name)) {
4989 some_related_source_name_exists = true;
4992 error << string_compose(
4993 _("There are already %1 recordings for %2, which I consider too many."),
4994 limit, base) << endmsg;
4996 throw failed_constructor();
5000 /* We've established that the new name does not exist in any session
5001 * directory, so now find out which one we should use for this new
5005 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5007 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5012 /** Return a unique name based on `base` for a new internal MIDI source */
5014 Session::new_midi_source_path (const string& base)
5017 char buf[PATH_MAX+1];
5018 const uint32_t limit = 10000;
5020 string possible_path;
5021 string possible_name;
5024 legalized = legalize_for_path (base);
5026 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5027 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5029 /* - the main session folder is the first in the vector.
5030 * - after checking all locations for file-name uniqueness,
5031 * we keep the one from the last iteration as new file name
5032 * - midi files are small and should just be kept in the main session-folder
5034 * -> reverse the array, check main session folder last and use that as location
5037 std::reverse(sdirs.begin(), sdirs.end());
5039 for (cnt = 1; cnt <= limit; ++cnt) {
5041 vector<space_and_path>::iterator i;
5042 uint32_t existing = 0;
5044 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5046 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5047 possible_name = buf;
5049 possible_path = Glib::build_filename (*i, possible_name);
5051 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5055 if (midi_source_by_path (possible_path)) {
5060 if (existing == 0) {
5065 error << string_compose(
5066 _("There are already %1 recordings for %2, which I consider too many."),
5067 limit, base) << endmsg;
5073 /* No need to "find best location" for software/app-based RAID, because
5074 MIDI is so small that we always put it in the same place.
5077 return possible_path;
5081 /** Create a new within-session audio source */
5082 boost::shared_ptr<AudioFileSource>
5083 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5085 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5087 if (!path.empty()) {
5088 return boost::dynamic_pointer_cast<AudioFileSource> (
5089 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5091 throw failed_constructor ();
5095 /** Create a new within-session MIDI source */
5096 boost::shared_ptr<MidiSource>
5097 Session::create_midi_source_for_session (string const & basic_name)
5099 const string path = new_midi_source_path (basic_name);
5101 if (!path.empty()) {
5102 return boost::dynamic_pointer_cast<SMFSource> (
5103 SourceFactory::createWritable (
5104 DataType::MIDI, *this, path, false, frame_rate()));
5106 throw failed_constructor ();
5110 /** Create a new within-session MIDI source */
5111 boost::shared_ptr<MidiSource>
5112 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5114 /* the caller passes in the track the source will be used in,
5115 so that we can keep the numbering sane.
5117 Rationale: a track with the name "Foo" that has had N
5118 captures carried out so far will ALREADY have a write source
5119 named "Foo-N+1.mid" waiting to be used for the next capture.
5121 If we call new_midi_source_name() we will get "Foo-N+2". But
5122 there is no region corresponding to "Foo-N+1", so when
5123 "Foo-N+2" appears in the track, the gap presents the user
5124 with odd behaviour - why did it skip past Foo-N+1?
5126 We could explain this to the user in some odd way, but
5127 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5130 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5133 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5135 std::string name = track->steal_write_source_name ();
5138 return boost::shared_ptr<MidiSource>();
5141 /* MIDI files are small, just put them in the first location of the
5142 session source search path.
5145 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5147 return boost::dynamic_pointer_cast<SMFSource> (
5148 SourceFactory::createWritable (
5149 DataType::MIDI, *this, path, false, frame_rate()));
5154 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5156 if (playlist->hidden()) {
5160 playlists->add (playlist);
5163 playlist->release();
5170 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5172 if (_state_of_the_state & Deletion) {
5176 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5182 playlists->remove (playlist);
5188 Session::set_audition (boost::shared_ptr<Region> r)
5190 pending_audition_region = r;
5191 add_post_transport_work (PostTransportAudition);
5192 _butler->schedule_transport_work ();
5196 Session::audition_playlist ()
5198 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5199 ev->region.reset ();
5205 Session::register_lua_function (
5206 const std::string& name,
5207 const std::string& script,
5208 const LuaScriptParamList& args
5211 Glib::Threads::Mutex::Lock lm (lua_lock);
5213 lua_State* L = lua.getState();
5215 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5216 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5217 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5218 if ((*i)->optional && !(*i)->is_set) { continue; }
5219 tbl_arg[(*i)->name] = (*i)->value;
5221 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5226 Session::unregister_lua_function (const std::string& name)
5228 Glib::Threads::Mutex::Lock lm (lua_lock);
5229 (*_lua_del)(name); // throws luabridge::LuaException
5230 lua.collect_garbage ();
5234 std::vector<std::string>
5235 Session::registered_lua_functions ()
5237 Glib::Threads::Mutex::Lock lm (lua_lock);
5238 std::vector<std::string> rv;
5241 luabridge::LuaRef list ((*_lua_list)());
5242 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5243 if (!i.key ().isString ()) { assert(0); continue; }
5244 rv.push_back (i.key ().cast<std::string> ());
5246 } catch (luabridge::LuaException const& e) { }
5251 static void _lua_print (std::string s) {
5252 std::cout << "SessionLua: " << s << "\n";
5257 Session::try_run_lua (pframes_t nframes)
5259 if (_n_lua_scripts == 0) return;
5260 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5262 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5263 lua.collect_garbage_step ();
5268 Session::setup_lua ()
5271 lua.Print.connect (&_lua_print);
5275 "function ArdourSession ()"
5276 " local self = { scripts = {}, instances = {} }"
5278 " local remove = function (n)"
5279 " self.scripts[n] = nil"
5280 " self.instances[n] = nil"
5281 " Session:scripts_changed()" // call back
5284 " local addinternal = function (n, f, a)"
5285 " assert(type(n) == 'string', 'function-name must be string')"
5286 " assert(type(f) == 'function', 'Given script is a not a function')"
5287 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5288 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5289 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5290 " local env = _ENV; env.f = nil env.io = nil env.os = nil env.loadfile = nil env.require = nil env.dofile = nil env.package = nil env.debug = nil"
5291 " 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 }"
5292 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5293 " Session:scripts_changed()" // call back
5296 " local add = function (n, b, a)"
5297 " assert(type(b) == 'string', 'ByteCode must be string')"
5298 " load (b)()" // assigns f
5299 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5300 " addinternal (n, load(f), a)"
5303 " local run = function (...)"
5304 " for n, s in pairs (self.instances) do"
5305 " local status, err = pcall (s, ...)"
5306 " if not status then"
5307 " print ('fn \"'.. n .. '\": ', err)"
5314 " local cleanup = function ()"
5315 " self.scripts = nil"
5316 " self.instances = nil"
5319 " local list = function ()"
5321 " for n, _ in pairs (self.scripts) do"
5327 " local function basic_serialize (o)"
5328 " if type(o) == \"number\" then"
5329 " return tostring(o)"
5331 " return string.format(\"%q\", o)"
5335 " local function serialize (name, value)"
5336 " local rv = name .. ' = '"
5338 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5339 " return rv .. basic_serialize(value) .. ' '"
5340 " elseif type(value) == \"table\" then"
5342 " for k,v in pairs(value) do"
5343 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5344 " rv = rv .. serialize(fieldname, v) .. ' '"
5345 " collectgarbage()" // string concatenation allocates a new string :(
5348 " elseif type(value) == \"function\" then"
5349 " return rv .. string.format(\"%q\", string.dump(value, true))"
5351 " error('cannot save a ' .. type(value))"
5356 " local save = function ()"
5357 " return (serialize('scripts', self.scripts))"
5360 " local restore = function (state)"
5361 " self.scripts = {}"
5363 " for n, s in pairs (scripts) do"
5364 " addinternal (n, load(s['f']), s['a'])"
5368 " return { run = run, add = add, remove = remove,"
5369 " list = list, restore = restore, save = save, cleanup = cleanup}"
5372 " sess = ArdourSession ()"
5373 " ArdourSession = nil"
5375 "function ardour () end"
5378 lua_State* L = lua.getState();
5381 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5382 lua.do_command ("sess = nil"); // hide it.
5383 lua.do_command ("collectgarbage()");
5385 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5386 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5387 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5388 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5389 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5390 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5391 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5392 } catch (luabridge::LuaException const& e) {
5393 fatal << string_compose (_("programming error: %1"),
5394 X_("Failed to setup Lua interpreter"))
5396 abort(); /*NOTREACHED*/
5399 LuaBindings::stddef (L);
5400 LuaBindings::common (L);
5401 LuaBindings::dsp (L);
5402 luabridge::push <Session *> (L, this);
5403 lua_setglobal (L, "Session");
5407 Session::scripts_changed ()
5409 assert (!lua_lock.trylock()); // must hold lua_lock
5412 luabridge::LuaRef list ((*_lua_list)());
5414 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5415 if (!i.key ().isString ()) { assert(0); continue; }
5418 _n_lua_scripts = cnt;
5419 } catch (luabridge::LuaException const& e) {
5420 fatal << string_compose (_("programming error: %1"),
5421 X_("Indexing Lua Session Scripts failed."))
5423 abort(); /*NOTREACHED*/
5428 Session::non_realtime_set_audition ()
5430 assert (pending_audition_region);
5431 auditioner->audition_region (pending_audition_region);
5432 pending_audition_region.reset ();
5433 AuditionActive (true); /* EMIT SIGNAL */
5437 Session::audition_region (boost::shared_ptr<Region> r)
5439 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5445 Session::cancel_audition ()
5450 if (auditioner->auditioning()) {
5451 auditioner->cancel_audition ();
5452 AuditionActive (false); /* EMIT SIGNAL */
5457 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5459 if (a->is_monitor()) {
5462 if (b->is_monitor()) {
5465 return a->presentation_info().order() < b->presentation_info().order();
5469 Session::is_auditioning () const
5471 /* can be called before we have an auditioner object */
5473 return auditioner->auditioning();
5480 Session::graph_reordered ()
5482 /* don't do this stuff if we are setting up connections
5483 from a set_state() call or creating new tracks. Ditto for deletion.
5486 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5490 /* every track/bus asked for this to be handled but it was deferred because
5491 we were connecting. do it now.
5494 request_input_change_handling ();
5498 /* force all diskstreams to update their capture offset values to
5499 reflect any changes in latencies within the graph.
5502 boost::shared_ptr<RouteList> rl = routes.reader ();
5503 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5504 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5506 tr->set_capture_offset ();
5511 /** @return Number of frames that there is disk space available to write,
5514 boost::optional<framecnt_t>
5515 Session::available_capture_duration ()
5517 Glib::Threads::Mutex::Lock lm (space_lock);
5519 if (_total_free_4k_blocks_uncertain) {
5520 return boost::optional<framecnt_t> ();
5523 float sample_bytes_on_disk = 4.0; // keep gcc happy
5525 switch (config.get_native_file_data_format()) {
5527 sample_bytes_on_disk = 4.0;
5531 sample_bytes_on_disk = 3.0;
5535 sample_bytes_on_disk = 2.0;
5539 /* impossible, but keep some gcc versions happy */
5540 fatal << string_compose (_("programming error: %1"),
5541 X_("illegal native file data format"))
5543 abort(); /*NOTREACHED*/
5546 double scale = 4096.0 / sample_bytes_on_disk;
5548 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5549 return max_framecnt;
5552 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5556 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5559 RCUWriter<BundleList> writer (_bundles);
5560 boost::shared_ptr<BundleList> b = writer.get_copy ();
5561 b->push_back (bundle);
5565 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5572 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5574 bool removed = false;
5577 RCUWriter<BundleList> writer (_bundles);
5578 boost::shared_ptr<BundleList> b = writer.get_copy ();
5579 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5581 if (i != b->end()) {
5588 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5594 boost::shared_ptr<Bundle>
5595 Session::bundle_by_name (string name) const
5597 boost::shared_ptr<BundleList> b = _bundles.reader ();
5599 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5600 if ((*i)->name() == name) {
5605 return boost::shared_ptr<Bundle> ();
5609 Session::tempo_map_changed (const PropertyChange&)
5613 playlists->update_after_tempo_map_change ();
5615 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5621 Session::gui_tempo_map_changed ()
5625 playlists->update_after_tempo_map_change ();
5627 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5631 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5633 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5634 (*i)->recompute_frames_from_beat ();
5638 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5639 * the given count with the current block size.
5642 Session::ensure_buffers (ChanCount howmany)
5644 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5648 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5650 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5651 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5656 Session::next_insert_id ()
5658 /* this doesn't really loop forever. just think about it */
5661 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5662 if (!insert_bitset[n]) {
5663 insert_bitset[n] = true;
5669 /* none available, so resize and try again */
5671 insert_bitset.resize (insert_bitset.size() + 16, false);
5676 Session::next_send_id ()
5678 /* this doesn't really loop forever. just think about it */
5681 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5682 if (!send_bitset[n]) {
5683 send_bitset[n] = true;
5689 /* none available, so resize and try again */
5691 send_bitset.resize (send_bitset.size() + 16, false);
5696 Session::next_aux_send_id ()
5698 /* this doesn't really loop forever. just think about it */
5701 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5702 if (!aux_send_bitset[n]) {
5703 aux_send_bitset[n] = true;
5709 /* none available, so resize and try again */
5711 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5716 Session::next_return_id ()
5718 /* this doesn't really loop forever. just think about it */
5721 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5722 if (!return_bitset[n]) {
5723 return_bitset[n] = true;
5729 /* none available, so resize and try again */
5731 return_bitset.resize (return_bitset.size() + 16, false);
5736 Session::mark_send_id (uint32_t id)
5738 if (id >= send_bitset.size()) {
5739 send_bitset.resize (id+16, false);
5741 if (send_bitset[id]) {
5742 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5744 send_bitset[id] = true;
5748 Session::mark_aux_send_id (uint32_t id)
5750 if (id >= aux_send_bitset.size()) {
5751 aux_send_bitset.resize (id+16, false);
5753 if (aux_send_bitset[id]) {
5754 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5756 aux_send_bitset[id] = true;
5760 Session::mark_return_id (uint32_t id)
5762 if (id >= return_bitset.size()) {
5763 return_bitset.resize (id+16, false);
5765 if (return_bitset[id]) {
5766 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5768 return_bitset[id] = true;
5772 Session::mark_insert_id (uint32_t id)
5774 if (id >= insert_bitset.size()) {
5775 insert_bitset.resize (id+16, false);
5777 if (insert_bitset[id]) {
5778 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5780 insert_bitset[id] = true;
5784 Session::unmark_send_id (uint32_t id)
5786 if (id < send_bitset.size()) {
5787 send_bitset[id] = false;
5792 Session::unmark_aux_send_id (uint32_t id)
5794 if (id < aux_send_bitset.size()) {
5795 aux_send_bitset[id] = false;
5800 Session::unmark_return_id (uint32_t id)
5802 if (_state_of_the_state & Deletion) { return; }
5803 if (id < return_bitset.size()) {
5804 return_bitset[id] = false;
5809 Session::unmark_insert_id (uint32_t id)
5811 if (id < insert_bitset.size()) {
5812 insert_bitset[id] = false;
5817 Session::reset_native_file_format ()
5819 boost::shared_ptr<RouteList> rl = routes.reader ();
5821 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5822 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5824 /* don't save state as we do this, there's no point
5826 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5827 tr->reset_write_sources (false);
5828 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5834 Session::route_name_unique (string n) const
5836 boost::shared_ptr<RouteList> r = routes.reader ();
5838 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5839 if ((*i)->name() == n) {
5848 Session::route_name_internal (string n) const
5850 if (auditioner && auditioner->name() == n) {
5854 if (_click_io && _click_io->name() == n) {
5862 Session::freeze_all (InterThreadInfo& itt)
5864 boost::shared_ptr<RouteList> r = routes.reader ();
5866 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5868 boost::shared_ptr<Track> t;
5870 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5871 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5881 boost::shared_ptr<Region>
5882 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5883 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5884 InterThreadInfo& itt,
5885 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5886 bool for_export, bool for_freeze)
5888 boost::shared_ptr<Region> result;
5889 boost::shared_ptr<Playlist> playlist;
5890 boost::shared_ptr<Source> source;
5891 ChanCount diskstream_channels (track.n_channels());
5892 framepos_t position;
5893 framecnt_t this_chunk;
5895 framepos_t latency_skip;
5897 framepos_t len = end - start;
5898 bool need_block_size_reset = false;
5899 ChanCount const max_proc = track.max_processor_streams ();
5900 string legal_playlist_name;
5901 string possible_path;
5904 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5905 end, start) << endmsg;
5909 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5910 include_endpoint, for_export, for_freeze);
5912 if (diskstream_channels.n(track.data_type()) < 1) {
5913 error << _("Cannot write a range with no data.") << endmsg;
5917 // block all process callback handling
5919 block_processing ();
5922 // synchronize with AudioEngine::process_callback()
5923 // make sure processing is not currently running
5924 // and processing_blocked() is honored before
5925 // acquiring thread buffers
5926 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5929 _bounce_processing_active = true;
5931 /* call tree *MUST* hold route_lock */
5933 if ((playlist = track.playlist()) == 0) {
5937 legal_playlist_name = legalize_for_path (playlist->name());
5939 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5941 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5942 string path = ((track.data_type() == DataType::AUDIO)
5943 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5944 : new_midi_source_path (legal_playlist_name));
5951 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5954 catch (failed_constructor& err) {
5955 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5959 srcs.push_back (source);
5962 /* tell redirects that care that we are about to use a much larger
5963 * blocksize. this will flush all plugins too, so that they are ready
5964 * to be used for this process.
5967 need_block_size_reset = true;
5968 track.set_block_size (bounce_chunk_size);
5969 _engine.main_thread()->get_buffers ();
5973 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5975 /* create a set of reasonably-sized buffers */
5976 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5977 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5979 buffers.set_count (max_proc);
5981 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5982 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5983 boost::shared_ptr<MidiSource> ms;
5985 afs->prepare_for_peakfile_writes ();
5986 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5987 Source::Lock lock(ms->mutex());
5988 ms->mark_streaming_write_started(lock);
5992 while (to_do && !itt.cancel) {
5994 this_chunk = min (to_do, bounce_chunk_size);
5996 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6000 start += this_chunk;
6001 to_do -= this_chunk;
6002 itt.progress = (float) (1.0 - ((double) to_do / len));
6004 if (latency_skip >= bounce_chunk_size) {
6005 latency_skip -= bounce_chunk_size;
6009 const framecnt_t current_chunk = this_chunk - latency_skip;
6012 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6013 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6014 boost::shared_ptr<MidiSource> ms;
6017 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6020 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6021 Source::Lock lock(ms->mutex());
6023 const MidiBuffer& buf = buffers.get_midi(0);
6024 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6025 Evoral::Event<framepos_t> ev = *i;
6026 ev.set_time(ev.time() - position);
6027 ms->append_event_frames(lock, ev, ms->timeline_position());
6034 /* post-roll, pick up delayed processor output */
6035 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6037 while (latency_skip && !itt.cancel) {
6038 this_chunk = min (latency_skip, bounce_chunk_size);
6039 latency_skip -= this_chunk;
6041 buffers.silence (this_chunk, 0);
6042 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6045 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6046 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6049 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6061 xnow = localtime (&now);
6063 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6064 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6065 boost::shared_ptr<MidiSource> ms;
6068 afs->update_header (position, *xnow, now);
6069 afs->flush_header ();
6070 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6071 Source::Lock lock(ms->mutex());
6072 ms->mark_streaming_write_completed(lock);
6076 /* construct a region to represent the bounced material */
6080 plist.add (Properties::start, 0);
6081 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6082 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6084 result = RegionFactory::create (srcs, plist);
6090 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6091 (*src)->mark_for_remove ();
6092 (*src)->drop_references ();
6096 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6097 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6100 afs->done_with_peakfile_writes ();
6104 _bounce_processing_active = false;
6106 if (need_block_size_reset) {
6107 _engine.main_thread()->drop_buffers ();
6108 track.set_block_size (get_block_size());
6111 unblock_processing ();
6117 Session::gain_automation_buffer() const
6119 return ProcessThread::gain_automation_buffer ();
6123 Session::trim_automation_buffer() const
6125 return ProcessThread::trim_automation_buffer ();
6129 Session::send_gain_automation_buffer() const
6131 return ProcessThread::send_gain_automation_buffer ();
6135 Session::pan_automation_buffer() const
6137 return ProcessThread::pan_automation_buffer ();
6141 Session::get_silent_buffers (ChanCount count)
6143 return ProcessThread::get_silent_buffers (count);
6147 Session::get_scratch_buffers (ChanCount count, bool silence)
6149 return ProcessThread::get_scratch_buffers (count, silence);
6153 Session::get_noinplace_buffers (ChanCount count)
6155 return ProcessThread::get_noinplace_buffers (count);
6159 Session::get_route_buffers (ChanCount count, bool silence)
6161 return ProcessThread::get_route_buffers (count, silence);
6166 Session::get_mix_buffers (ChanCount count)
6168 return ProcessThread::get_mix_buffers (count);
6172 Session::ntracks () const
6175 boost::shared_ptr<RouteList> r = routes.reader ();
6177 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6178 if (boost::dynamic_pointer_cast<Track> (*i)) {
6187 Session::nbusses () const
6190 boost::shared_ptr<RouteList> r = routes.reader ();
6192 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6193 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6202 Session::add_automation_list(AutomationList *al)
6204 automation_lists[al->id()] = al;
6207 /** @return true if there is at least one record-enabled track, otherwise false */
6209 Session::have_rec_enabled_track () const
6211 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6215 Session::have_rec_disabled_track () const
6217 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6220 /** Update the state of our rec-enabled tracks flag */
6222 Session::update_route_record_state ()
6224 boost::shared_ptr<RouteList> rl = routes.reader ();
6225 RouteList::iterator i = rl->begin();
6226 while (i != rl->end ()) {
6228 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6229 if (tr && tr->rec_enable_control()->get_value()) {
6236 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6238 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6240 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6241 RecordStateChanged (); /* EMIT SIGNAL */
6244 for (i = rl->begin(); i != rl->end (); ++i) {
6245 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6246 if (tr && !tr->rec_enable_control()->get_value()) {
6251 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6253 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6255 if (record_status() == Recording && record_arm_state_changed ) {
6256 RecordArmStateChanged ();
6262 Session::listen_position_changed ()
6264 ProcessorChangeBlocker pcb (this);
6265 boost::shared_ptr<RouteList> r = routes.reader ();
6266 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6267 (*i)->listen_position_changed ();
6272 Session::solo_control_mode_changed ()
6274 if (soloing() || listening()) {
6276 /* We can't use ::clear_all_solo_state() here because during
6277 session loading at program startup, that will queue a call
6278 to rt_clear_all_solo_state() that will not execute until
6279 AFTER solo states have been established (thus throwing away
6280 the session's saved solo state). So just explicitly turn
6283 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6285 clear_all_solo_state (get_routes());
6290 /** Called when a property of one of our route groups changes */
6292 Session::route_group_property_changed (RouteGroup* rg)
6294 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6297 /** Called when a route is added to one of our route groups */
6299 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6301 RouteAddedToRouteGroup (rg, r);
6304 /** Called when a route is removed from one of our route groups */
6306 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6308 update_route_record_state ();
6309 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6311 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6312 remove_route_group (*rg);
6316 boost::shared_ptr<RouteList>
6317 Session::get_tracks () const
6319 boost::shared_ptr<RouteList> rl = routes.reader ();
6320 boost::shared_ptr<RouteList> tl (new RouteList);
6322 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6323 if (boost::dynamic_pointer_cast<Track> (*r)) {
6324 if (!(*r)->is_auditioner()) {
6332 boost::shared_ptr<RouteList>
6333 Session::get_routes_with_regions_at (framepos_t const p) const
6335 boost::shared_ptr<RouteList> r = routes.reader ();
6336 boost::shared_ptr<RouteList> rl (new RouteList);
6338 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6339 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6344 boost::shared_ptr<Playlist> pl = tr->playlist ();
6349 if (pl->has_region_at (p)) {
6358 Session::goto_end ()
6360 if (_session_range_location) {
6361 request_locate (_session_range_location->end(), false);
6363 request_locate (0, false);
6368 Session::goto_start (bool and_roll)
6370 if (_session_range_location) {
6371 request_locate (_session_range_location->start(), and_roll);
6373 request_locate (0, and_roll);
6378 Session::current_start_frame () const
6380 return _session_range_location ? _session_range_location->start() : 0;
6384 Session::current_end_frame () const
6386 return _session_range_location ? _session_range_location->end() : 0;
6390 Session::set_session_range_location (framepos_t start, framepos_t end)
6392 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6393 _locations->add (_session_range_location);
6397 Session::step_edit_status_change (bool yn)
6403 send = (_step_editors == 0);
6408 send = (_step_editors == 1);
6411 if (_step_editors > 0) {
6417 StepEditStatusChange (val);
6423 Session::start_time_changed (framepos_t old)
6425 /* Update the auto loop range to match the session range
6426 (unless the auto loop range has been changed by the user)
6429 Location* s = _locations->session_range_location ();
6434 Location* l = _locations->auto_loop_location ();
6436 if (l && l->start() == old) {
6437 l->set_start (s->start(), true);
6443 Session::end_time_changed (framepos_t old)
6445 /* Update the auto loop range to match the session range
6446 (unless the auto loop range has been changed by the user)
6449 Location* s = _locations->session_range_location ();
6454 Location* l = _locations->auto_loop_location ();
6456 if (l && l->end() == old) {
6457 l->set_end (s->end(), true);
6462 std::vector<std::string>
6463 Session::source_search_path (DataType type) const
6467 if (session_dirs.size() == 1) {
6469 case DataType::AUDIO:
6470 sp.push_back (_session_dir->sound_path());
6472 case DataType::MIDI:
6473 sp.push_back (_session_dir->midi_path());
6477 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6478 SessionDirectory sdir (i->path);
6480 case DataType::AUDIO:
6481 sp.push_back (sdir.sound_path());
6483 case DataType::MIDI:
6484 sp.push_back (sdir.midi_path());
6490 if (type == DataType::AUDIO) {
6491 const string sound_path_2X = _session_dir->sound_path_2X();
6492 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6493 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6494 sp.push_back (sound_path_2X);
6499 // now check the explicit (possibly user-specified) search path
6502 case DataType::AUDIO:
6503 sp += Searchpath(config.get_audio_search_path ());
6505 case DataType::MIDI:
6506 sp += Searchpath(config.get_midi_search_path ());
6514 Session::ensure_search_path_includes (const string& path, DataType type)
6523 case DataType::AUDIO:
6524 sp += Searchpath(config.get_audio_search_path ());
6526 case DataType::MIDI:
6527 sp += Searchpath (config.get_midi_search_path ());
6531 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6532 /* No need to add this new directory if it has the same inode as
6533 an existing one; checking inode rather than name prevents duplicated
6534 directories when we are using symlinks.
6536 On Windows, I think we could just do if (*i == path) here.
6538 if (PBD::equivalent_paths (*i, path)) {
6546 case DataType::AUDIO:
6547 config.set_audio_search_path (sp.to_string());
6549 case DataType::MIDI:
6550 config.set_midi_search_path (sp.to_string());
6556 Session::remove_dir_from_search_path (const string& dir, DataType type)
6561 case DataType::AUDIO:
6562 sp = Searchpath(config.get_audio_search_path ());
6564 case DataType::MIDI:
6565 sp = Searchpath (config.get_midi_search_path ());
6572 case DataType::AUDIO:
6573 config.set_audio_search_path (sp.to_string());
6575 case DataType::MIDI:
6576 config.set_midi_search_path (sp.to_string());
6582 boost::shared_ptr<Speakers>
6583 Session::get_speakers()
6589 Session::unknown_processors () const
6593 boost::shared_ptr<RouteList> r = routes.reader ();
6594 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6595 list<string> t = (*i)->unknown_processors ();
6596 copy (t.begin(), t.end(), back_inserter (p));
6606 Session::update_latency (bool playback)
6609 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6611 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6615 boost::shared_ptr<RouteList> r = routes.reader ();
6616 framecnt_t max_latency = 0;
6619 /* reverse the list so that we work backwards from the last route to run to the first */
6620 RouteList* rl = routes.reader().get();
6621 r.reset (new RouteList (*rl));
6622 reverse (r->begin(), r->end());
6625 /* compute actual latency values for the given direction and store them all in per-port
6626 structures. this will also publish the same values (to JACK) so that computation of latency
6627 for routes can consistently use public latency values.
6630 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6631 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6634 /* because we latency compensate playback, our published playback latencies should
6635 be the same for all output ports - all material played back by ardour has
6636 the same latency, whether its caused by plugins or by latency compensation. since
6637 these may differ from the values computed above, reset all playback port latencies
6641 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6643 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6644 (*i)->set_public_port_latencies (max_latency, playback);
6649 post_playback_latency ();
6653 post_capture_latency ();
6656 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6660 Session::post_playback_latency ()
6662 set_worst_playback_latency ();
6664 boost::shared_ptr<RouteList> r = routes.reader ();
6666 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6667 if (!(*i)->is_auditioner() && ((*i)->active())) {
6668 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6672 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6673 (*i)->set_latency_compensation (_worst_track_latency);
6678 Session::post_capture_latency ()
6680 set_worst_capture_latency ();
6682 /* reflect any changes in capture latencies into capture offsets
6685 boost::shared_ptr<RouteList> rl = routes.reader();
6686 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6687 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6689 tr->set_capture_offset ();
6695 Session::initialize_latencies ()
6698 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6699 update_latency (false);
6700 update_latency (true);
6703 set_worst_io_latencies ();
6707 Session::set_worst_io_latencies ()
6709 set_worst_playback_latency ();
6710 set_worst_capture_latency ();
6714 Session::set_worst_playback_latency ()
6716 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6720 _worst_output_latency = 0;
6722 if (!_engine.connected()) {
6726 boost::shared_ptr<RouteList> r = routes.reader ();
6728 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6729 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6732 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6736 Session::set_worst_capture_latency ()
6738 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6742 _worst_input_latency = 0;
6744 if (!_engine.connected()) {
6748 boost::shared_ptr<RouteList> r = routes.reader ();
6750 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6751 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6754 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6758 Session::update_latency_compensation (bool force_whole_graph)
6760 bool some_track_latency_changed = false;
6762 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6766 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6768 _worst_track_latency = 0;
6770 boost::shared_ptr<RouteList> r = routes.reader ();
6772 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6773 if (!(*i)->is_auditioner() && ((*i)->active())) {
6775 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6776 some_track_latency_changed = true;
6778 _worst_track_latency = max (tl, _worst_track_latency);
6782 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6783 (some_track_latency_changed ? "yes" : "no")));
6785 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6787 if (some_track_latency_changed || force_whole_graph) {
6788 _engine.update_latencies ();
6792 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6793 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6797 tr->set_capture_offset ();
6802 Session::session_name_is_legal (const string& path)
6804 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6806 for (int i = 0; illegal_chars[i]; ++i) {
6807 if (path.find (illegal_chars[i]) != string::npos) {
6808 return illegal_chars[i];
6816 Session::notify_presentation_info_change ()
6818 if (deletion_in_progress()) {
6822 PresentationInfo::Change (); /* EMIT SIGNAL */
6823 reassign_track_numbers();
6825 #ifdef USE_TRACKS_CODE_FEATURES
6826 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6827 * if track order has been changed by user
6829 reconnect_existing_routes(true, true);
6835 Session::operation_in_progress (GQuark op) const
6837 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6840 boost::shared_ptr<Port>
6841 Session::ltc_input_port () const
6843 return _ltc_input->nth (0);
6846 boost::shared_ptr<Port>
6847 Session::ltc_output_port () const
6849 return _ltc_output->nth (0);
6853 Session::reconnect_ltc_input ()
6857 string src = Config->get_ltc_source_port();
6859 _ltc_input->disconnect (this);
6861 if (src != _("None") && !src.empty()) {
6862 _ltc_input->nth (0)->connect (src);
6865 if ( ARDOUR::Profile->get_trx () ) {
6866 // Tracks need this signal to update timecode_source_dropdown
6867 MtcOrLtcInputPortChanged (); //emit signal
6873 Session::reconnect_ltc_output ()
6877 string src = Config->get_ltc_output_port();
6879 _ltc_output->disconnect (this);
6881 if (src != _("None") && !src.empty()) {
6882 _ltc_output->nth (0)->connect (src);
6888 Session::set_range_selection (framepos_t start, framepos_t end)
6890 _range_selection = Evoral::Range<framepos_t> (start, end);
6891 #ifdef USE_TRACKS_CODE_FEATURES
6892 follow_playhead_priority ();
6897 Session::set_object_selection (framepos_t start, framepos_t end)
6899 _object_selection = Evoral::Range<framepos_t> (start, end);
6900 #ifdef USE_TRACKS_CODE_FEATURES
6901 follow_playhead_priority ();
6906 Session::clear_range_selection ()
6908 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6909 #ifdef USE_TRACKS_CODE_FEATURES
6910 follow_playhead_priority ();
6915 Session::clear_object_selection ()
6917 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6918 #ifdef USE_TRACKS_CODE_FEATURES
6919 follow_playhead_priority ();
6924 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6925 const ChanCount& input_start,
6926 const ChanCount& output_start,
6927 const ChanCount& input_offset,
6928 const ChanCount& output_offset)
6930 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6931 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6932 input_start, output_start,
6933 input_offset, output_offset));
6935 auto_connect_thread_wakeup ();
6939 Session::auto_connect_thread_wakeup ()
6941 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6942 pthread_cond_signal (&_auto_connect_cond);
6943 pthread_mutex_unlock (&_auto_connect_mutex);
6948 Session::queue_latency_recompute ()
6950 g_atomic_int_inc (&_latency_recompute_pending);
6951 auto_connect_thread_wakeup ();
6955 Session::auto_connect (const AutoConnectRequest& ar)
6957 boost::shared_ptr<Route> route = ar.route.lock();
6959 if (!route) { return; }
6961 if (!IO::connecting_legal) {
6965 /* If both inputs and outputs are auto-connected to physical ports,
6966 * use the max of input and output offsets to ensure auto-connected
6967 * port numbers always match up (e.g. the first audio input and the
6968 * first audio output of the route will have the same physical
6969 * port number). Otherwise just use the lowest input or output
6973 const bool in_out_physical =
6974 (Config->get_input_auto_connect() & AutoConnectPhysical)
6975 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6976 && ar.connect_inputs;
6978 const ChanCount in_offset = in_out_physical
6979 ? ChanCount::max(ar.input_offset, ar.output_offset)
6982 const ChanCount out_offset = in_out_physical
6983 ? ChanCount::max(ar.input_offset, ar.output_offset)
6986 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6987 vector<string> physinputs;
6988 vector<string> physoutputs;
6991 /* for connecting track inputs we only want MIDI ports marked
6995 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
6997 if (!physinputs.empty() && ar.connect_inputs) {
6998 uint32_t nphysical_in = physinputs.size();
7000 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7003 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7004 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7007 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7013 if (!physoutputs.empty()) {
7014 uint32_t nphysical_out = physoutputs.size();
7015 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7019 * do not create new connections if we reached the limit of physical outputs
7022 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7023 ARDOUR::Profile->get_trx () &&
7024 ar.output_offset.get(*t) == nphysical_out ) {
7028 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7029 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7030 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7031 /* master bus is audio only */
7032 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7033 port = _master_out->input()->ports().port(*t,
7034 i % _master_out->input()->n_ports().get(*t))->name();
7038 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7047 Session::auto_connect_thread_start ()
7049 if (g_atomic_int_get (&_ac_thread_active)) {
7053 while (!_auto_connect_queue.empty ()) {
7054 _auto_connect_queue.pop ();
7057 g_atomic_int_set (&_ac_thread_active, 1);
7058 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7059 g_atomic_int_set (&_ac_thread_active, 0);
7064 Session::auto_connect_thread_terminate ()
7066 if (!g_atomic_int_get (&_ac_thread_active)) {
7071 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7072 while (!_auto_connect_queue.empty ()) {
7073 _auto_connect_queue.pop ();
7077 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7078 * fail to wakeup the thread.
7081 pthread_mutex_lock (&_auto_connect_mutex);
7082 g_atomic_int_set (&_ac_thread_active, 0);
7083 pthread_cond_signal (&_auto_connect_cond);
7084 pthread_mutex_unlock (&_auto_connect_mutex);
7087 pthread_join (_auto_connect_thread, &status);
7091 Session::auto_connect_thread (void *arg)
7093 Session *s = static_cast<Session *>(arg);
7094 s->auto_connect_thread_run ();
7100 Session::auto_connect_thread_run ()
7102 pthread_set_name (X_("autoconnect"));
7103 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7104 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7105 pthread_mutex_lock (&_auto_connect_mutex);
7106 while (g_atomic_int_get (&_ac_thread_active)) {
7108 if (!_auto_connect_queue.empty ()) {
7109 // Why would we need the process lock ??
7110 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7111 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7112 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7113 // We have control over those, but what does jack do?
7114 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7116 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7117 while (!_auto_connect_queue.empty ()) {
7118 const AutoConnectRequest ar (_auto_connect_queue.front());
7119 _auto_connect_queue.pop ();
7126 if (!actively_recording ()) { // might not be needed,
7127 /* this is only used for updating plugin latencies, the
7128 * graph does not change. so it's safe in general.
7130 * .. update_latency_compensation () entails set_capture_offset()
7131 * which calls Diskstream::set_capture_offset () which
7132 * modifies the capture offset... which can be a proplem
7133 * in "prepare_to_stop"
7135 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7136 update_latency_compensation ();
7141 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7142 // jack1 cannot cope with removing ports while processing
7143 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7144 AudioEngine::instance()->clear_pending_port_deletions ();
7147 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7149 pthread_mutex_unlock (&_auto_connect_mutex);
7153 Session::cancel_all_solo ()
7157 get_stripables (sl);
7159 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7160 clear_all_solo_state (routes.reader());