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", 3145728)
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)
309 , _count_in_once (false)
311 , first_file_data_format_reset (true)
312 , first_file_header_format_reset (true)
313 , have_looped (false)
314 , _have_rec_enabled_track (false)
315 , _have_rec_disabled_track (true)
317 , _suspend_timecode_transmission (0)
318 , _speakers (new Speakers)
319 , _ignore_route_processor_changes (0)
324 , _vca_manager (new VCAManager (*this))
328 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
330 pthread_mutex_init (&_rt_emit_mutex, 0);
331 pthread_cond_init (&_rt_emit_cond, 0);
333 pthread_mutex_init (&_auto_connect_mutex, 0);
334 pthread_cond_init (&_auto_connect_cond, 0);
336 init_name_id_counter (1); // reset for new sessions, start at 1
337 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
339 pre_engine_init (fullpath); // sets _is_new
345 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
347 #ifdef USE_TRACKS_CODE_FEATURES
348 sr = EngineStateController::instance()->get_current_sample_rate();
350 if (ensure_engine (sr, true)) {
352 throw SessionException (_("Cannot connect to audio/midi engine"));
355 // set samplerate for plugins added early
356 // e.g from templates or MB channelstrip
357 set_block_size (_engine.samples_per_cycle());
358 set_frame_rate (_engine.sample_rate());
360 if (create (mix_template, bus_profile)) {
362 throw SessionException (_("Session initialization failed"));
365 /* if a mix template was provided, then ::create() will
366 * have copied it into the session and we need to load it
367 * so that we have the state ready for ::set_state()
368 * after the engine is started.
370 * Note that we do NOT try to get the sample rate from
371 * the template at this time, though doing so would
372 * be easy if we decided this was an appropriate part
376 if (!mix_template.empty()) {
377 if (load_state (_current_snapshot_name)) {
378 throw SessionException (_("Failed to load template/snapshot state"));
380 store_recent_templates (mix_template);
383 /* load default session properties - if any */
388 if (load_state (_current_snapshot_name)) {
389 throw SessionException (_("Failed to load state"));
392 /* try to get sample rate from XML state so that we
393 * can influence the SR if we set up the audio
398 XMLProperty const * prop;
399 XMLNode const * root (state_tree->root());
400 if ((prop = root->property (X_("sample-rate"))) != 0) {
401 sr = atoi (prop->value());
405 if (ensure_engine (sr, false)) {
407 throw SessionException (_("Cannot connect to audio/midi engine"));
411 if (post_engine_init ()) {
413 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
416 store_recent_sessions (_name, _path);
418 bool was_dirty = dirty();
420 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
422 PresentationInfo::Change.connect_same_thread (*this, boost::bind (&Session::notify_presentation_info_change, this));
424 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
425 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
428 DirtyChanged (); /* EMIT SIGNAL */
431 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
432 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
434 emit_thread_start ();
435 auto_connect_thread_start ();
437 /* hook us up to the engine since we are now completely constructed */
439 BootMessage (_("Connect to engine"));
441 _engine.set_session (this);
442 _engine.reset_timebase ();
444 #ifdef USE_TRACKS_CODE_FEATURES
446 EngineStateController::instance()->set_session(this);
449 if ( ARDOUR::Profile->get_trx () ) {
451 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
452 * each available input must have corresponding track when session starts.
455 uint32_t how_many (0);
457 std::vector<std::string> inputs;
458 EngineStateController::instance()->get_physical_audio_inputs(inputs);
460 how_many = inputs.size();
462 list<boost::shared_ptr<AudioTrack> > tracks;
464 // Track names after driver
465 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
466 string track_name = "";
467 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
469 track_name = inputs[i];
470 replace_all (track_name, "system:capture", "");
472 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
473 tracks.insert(tracks.begin(), single_track.front());
475 } else { // Default track names
476 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
479 if (tracks.size() != how_many) {
481 throw failed_constructor ();
487 ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
492 BootMessage (_("Session loading complete"));
504 Session::next_name_id ()
506 return g_atomic_int_add (&_name_id_counter, 1);
510 Session::name_id_counter ()
512 return g_atomic_int_get (&_name_id_counter);
516 Session::init_name_id_counter (guint n)
518 g_atomic_int_set (&_name_id_counter, n);
522 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
524 if (_engine.current_backend() == 0) {
525 /* backend is unknown ... */
526 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
527 if (r.get_value_or (-1) != 0) {
530 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
532 } else if (_engine.setup_required()) {
533 /* backend is known, but setup is needed */
534 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
535 if (r.get_value_or (-1) != 0) {
538 } else if (!_engine.running()) {
539 if (_engine.start()) {
544 /* at this point the engine should be running */
546 if (!_engine.running()) {
550 return immediately_post_engine ();
555 Session::immediately_post_engine ()
557 /* Do various initializations that should take place directly after we
558 * know that the engine is running, but before we either create a
559 * session or set state for an existing one.
562 if (how_many_dsp_threads () > 1) {
563 /* For now, only create the graph if we are using >1 DSP threads, as
564 it is a bit slower than the old code with 1 thread.
566 _process_graph.reset (new Graph (*this));
569 /* every time we reconnect, recompute worst case output latencies */
571 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
573 if (synced_to_engine()) {
574 _engine.transport_stop ();
577 if (config.get_jack_time_master()) {
578 _engine.transport_locate (_transport_frame);
583 BootMessage (_("Set up LTC"));
585 BootMessage (_("Set up Click"));
587 BootMessage (_("Set up standard connections"));
591 catch (failed_constructor& err) {
595 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
597 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
605 vector<void*> debug_pointers;
607 /* if we got to here, leaving pending capture state around
611 remove_pending_capture_state ();
615 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
617 /* disconnect from any and all signals that we are connected to */
619 Port::PortSignalDrop (); /* EMIT SIGNAL */
622 /* shutdown control surface protocols while we still have ports
623 and the engine to move data to any devices.
626 ControlProtocolManager::instance().drop_protocols ();
628 /* stop autoconnecting */
629 auto_connect_thread_terminate ();
631 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
633 _engine.remove_session ();
635 #ifdef USE_TRACKS_CODE_FEATURES
636 EngineStateController::instance()->remove_session();
639 /* deregister all ports - there will be no process or any other
640 * callbacks from the engine any more.
643 Port::PortDrop (); /* EMIT SIGNAL */
647 /* clear history so that no references to objects are held any more */
651 /* clear state tree so that no references to objects are held any more */
656 // unregister all lua functions, drop held references (if any)
658 lua.do_command ("Session = nil");
666 lua.collect_garbage ();
668 /* reset dynamic state version back to default */
669 Stateful::loading_state_version = 0;
671 _butler->drop_references ();
675 delete _all_route_group;
677 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
678 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
682 if (click_data != default_click) {
683 delete [] click_data;
686 if (click_emphasis_data != default_click_emphasis) {
687 delete [] click_emphasis_data;
692 /* need to remove auditioner before monitoring section
693 * otherwise it is re-connected */
696 /* drop references to routes held by the monitoring section
697 * specifically _monitor_out aux/listen references */
698 remove_monitor_section();
700 /* clear out any pending dead wood from RCU managed objects */
705 AudioDiskstream::free_working_buffers();
707 /* tell everyone who is still standing that we're about to die */
710 /* tell everyone to drop references and delete objects as we go */
712 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
713 RegionFactory::delete_all_regions ();
715 /* Do this early so that VCAs no longer hold references to routes */
717 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
720 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
722 /* reset these three references to special routes before we do the usual route delete thing */
724 _master_out.reset ();
725 _monitor_out.reset ();
728 RCUWriter<RouteList> writer (routes);
729 boost::shared_ptr<RouteList> r = writer.get_copy ();
731 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
732 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
733 (*i)->drop_references ();
737 /* writer goes out of scope and updates master */
742 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
743 Glib::Threads::Mutex::Lock lm (source_lock);
744 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
745 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
746 i->second->drop_references ();
752 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
755 emit_thread_terminate ();
757 pthread_cond_destroy (&_rt_emit_cond);
758 pthread_mutex_destroy (&_rt_emit_mutex);
760 pthread_cond_destroy (&_auto_connect_cond);
761 pthread_mutex_destroy (&_auto_connect_mutex);
763 delete _scene_changer; _scene_changer = 0;
764 delete midi_control_ui; midi_control_ui = 0;
766 delete _mmc; _mmc = 0;
767 delete _midi_ports; _midi_ports = 0;
768 delete _locations; _locations = 0;
773 /* clear event queue, the session is gone, nobody is interested in
774 * those anymore, but they do leak memory if not removed
776 while (!immediate_events.empty ()) {
777 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
778 SessionEvent *ev = immediate_events.front ();
779 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
780 immediate_events.pop_front ();
784 case SessionEvent::AutoLoop:
785 case SessionEvent::AutoLoopDeclick:
786 case SessionEvent::Skip:
787 case SessionEvent::PunchIn:
788 case SessionEvent::PunchOut:
789 case SessionEvent::RecordStart:
790 case SessionEvent::StopOnce:
791 case SessionEvent::RangeStop:
792 case SessionEvent::RangeLocate:
796 case SessionEvent::RealTimeOperation:
803 del = del && !_remove_event (ev);
810 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
812 BOOST_SHOW_POINTERS ();
816 Session::setup_ltc ()
820 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
821 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
823 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
824 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
827 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
828 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
829 // TODO use auto-connect thread somehow (needs a route currently)
830 // see note in Session::auto_connect_thread_run() why process lock is needed.
831 reconnect_ltc_input ();
835 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
836 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
839 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
840 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
841 // TODO use auto-connect thread
842 reconnect_ltc_output ();
846 /* fix up names of LTC ports because we don't want the normal
847 * IO style of NAME/TYPE-{in,out}N
850 _ltc_input->nth (0)->set_name (X_("LTC-in"));
851 _ltc_output->nth (0)->set_name (X_("LTC-out"));
855 Session::setup_click ()
859 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
860 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
862 _click_io.reset (new ClickIO (*this, X_("Click")));
863 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
864 _click_gain->activate ();
866 setup_click_state (state_tree->root());
868 setup_click_state (0);
873 Session::setup_click_state (const XMLNode* node)
875 const XMLNode* child = 0;
877 if (node && (child = find_named_node (*node, "Click")) != 0) {
879 /* existing state for Click */
882 if (Stateful::loading_state_version < 3000) {
883 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
885 const XMLNodeList& children (child->children());
886 XMLNodeList::const_iterator i = children.begin();
887 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
889 if (i != children.end()) {
890 c = _click_gain->set_state (**i, Stateful::loading_state_version);
896 _clicking = Config->get_clicking ();
900 error << _("could not setup Click I/O") << endmsg;
907 /* default state for Click: dual-mono to first 2 physical outputs */
910 _engine.get_physical_outputs (DataType::AUDIO, outs);
912 for (uint32_t physport = 0; physport < 2; ++physport) {
913 if (outs.size() > physport) {
914 if (_click_io->add_port (outs[physport], this)) {
915 // relax, even though its an error
920 if (_click_io->n_ports () > ChanCount::ZERO) {
921 _clicking = Config->get_clicking ();
927 Session::get_physical_ports (vector<string>& inputs, vector<string>& outputs, DataType type,
928 MidiPortFlags include, MidiPortFlags exclude)
930 _engine.get_physical_inputs (type, inputs, include, exclude);
931 _engine.get_physical_outputs (type, outputs, include, exclude);
935 Session::setup_bundles ()
939 RCUWriter<BundleList> writer (_bundles);
940 boost::shared_ptr<BundleList> b = writer.get_copy ();
941 for (BundleList::iterator i = b->begin(); i != b->end();) {
942 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
950 vector<string> inputs[DataType::num_types];
951 vector<string> outputs[DataType::num_types];
953 for (uint32_t i = 0; i < DataType::num_types; ++i) {
954 get_physical_ports (inputs[i], outputs[i], DataType (DataType::Symbol (i)),
955 MidiPortFlags (0), /* no specific inclusions */
956 MidiPortFlags (MidiPortControl|MidiPortVirtual) /* exclude control & virtual ports */
960 /* Create a set of Bundle objects that map
961 to the physical I/O currently available. We create both
962 mono and stereo bundles, so that the common cases of mono
963 and stereo tracks get bundles to put in their mixer strip
964 in / out menus. There may be a nicer way of achieving that;
965 it doesn't really scale that well to higher channel counts
968 /* mono output bundles */
970 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
972 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
974 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
976 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
979 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
980 c->add_channel (_("mono"), DataType::AUDIO);
981 c->set_port (0, outputs[DataType::AUDIO][np]);
983 add_bundle (c, false);
986 /* stereo output bundles */
988 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
989 if (np + 1 < outputs[DataType::AUDIO].size()) {
991 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
992 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
993 c->add_channel (_("L"), DataType::AUDIO);
994 c->set_port (0, outputs[DataType::AUDIO][np]);
995 c->add_channel (_("R"), DataType::AUDIO);
996 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
998 add_bundle (c, false);
1002 /* mono input bundles */
1004 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
1006 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
1008 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
1010 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
1013 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1014 c->add_channel (_("mono"), DataType::AUDIO);
1015 c->set_port (0, inputs[DataType::AUDIO][np]);
1017 add_bundle (c, false);
1020 /* stereo input bundles */
1022 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
1023 if (np + 1 < inputs[DataType::AUDIO].size()) {
1025 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1027 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1028 c->add_channel (_("L"), DataType::AUDIO);
1029 c->set_port (0, inputs[DataType::AUDIO][np]);
1030 c->add_channel (_("R"), DataType::AUDIO);
1031 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1033 add_bundle (c, false);
1037 /* MIDI input bundles */
1039 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1040 string n = inputs[DataType::MIDI][np];
1042 std::string pn = _engine.get_pretty_name_by_name (n);
1046 boost::erase_first (n, X_("alsa_pcm:"));
1048 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1049 c->add_channel ("", DataType::MIDI);
1050 c->set_port (0, inputs[DataType::MIDI][np]);
1051 add_bundle (c, false);
1054 /* MIDI output bundles */
1056 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1057 string n = outputs[DataType::MIDI][np];
1058 std::string pn = _engine.get_pretty_name_by_name (n);
1062 boost::erase_first (n, X_("alsa_pcm:"));
1064 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1065 c->add_channel ("", DataType::MIDI);
1066 c->set_port (0, outputs[DataType::MIDI][np]);
1067 add_bundle (c, false);
1070 // we trust the backend to only calls us if there's a change
1071 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1075 Session::auto_connect_master_bus ()
1077 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1081 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1082 // In this case it means "Multi Out" output mode
1083 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1087 /* if requested auto-connect the outputs to the first N physical ports.
1090 uint32_t limit = _master_out->n_outputs().n_total();
1091 vector<string> outputs[DataType::num_types];
1093 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1094 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1097 for (uint32_t n = 0; n < limit; ++n) {
1098 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1100 if (outputs[p->type()].size() > n) {
1101 connect_to = outputs[p->type()][n];
1104 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1105 if (_master_out->output()->connect (p, connect_to, this)) {
1106 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1115 Session::remove_monitor_section ()
1117 if (!_monitor_out || Profile->get_trx()) {
1121 /* force reversion to Solo-In-Place */
1122 Config->set_solo_control_is_listen_control (false);
1124 /* if we are auditioning, cancel it ... this is a workaround
1125 to a problem (auditioning does not execute the process graph,
1126 which is needed to remove routes when using >1 core for processing)
1131 /* Hold process lock while doing this so that we don't hear bits and
1132 * pieces of audio as we work on each route.
1135 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1137 /* Connect tracks to monitor section. Note that in an
1138 existing session, the internal sends will already exist, but we want the
1139 routes to notice that they connect to the control out specifically.
1143 boost::shared_ptr<RouteList> r = routes.reader ();
1144 ProcessorChangeBlocker pcb (this, false);
1146 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1148 if ((*x)->is_monitor()) {
1150 } else if ((*x)->is_master()) {
1153 (*x)->remove_aux_or_listen (_monitor_out);
1158 remove_route (_monitor_out);
1159 if (_state_of_the_state & Deletion) {
1163 auto_connect_master_bus ();
1166 auditioner->connect ();
1169 Config->ParameterChanged ("use-monitor-bus");
1173 Session::add_monitor_section ()
1177 if (_monitor_out || !_master_out || Profile->get_trx()) {
1181 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1187 BOOST_MARK_ROUTE(r);
1190 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1191 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1192 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1194 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1199 add_routes (rl, false, false, false, 0);
1201 assert (_monitor_out);
1203 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1204 are undefined, at best.
1207 uint32_t limit = _monitor_out->n_inputs().n_audio();
1211 /* connect the inputs to the master bus outputs. this
1212 * represents a separate data feed from the internal sends from
1213 * each route. as of jan 2011, it allows the monitor section to
1214 * conditionally ignore either the internal sends or the normal
1215 * input feed, but we should really find a better way to do
1219 _master_out->output()->disconnect (this);
1221 for (uint32_t n = 0; n < limit; ++n) {
1222 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1223 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1226 string connect_to = o->name();
1227 if (_monitor_out->input()->connect (p, connect_to, this)) {
1228 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1236 /* if monitor section is not connected, connect it to physical outs
1239 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1241 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1243 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1246 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1248 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1249 Config->get_monitor_bus_preferred_bundle())
1255 /* Monitor bus is audio only */
1257 vector<string> outputs[DataType::num_types];
1259 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1260 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1263 uint32_t mod = outputs[DataType::AUDIO].size();
1264 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1268 for (uint32_t n = 0; n < limit; ++n) {
1270 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1272 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1273 connect_to = outputs[DataType::AUDIO][n % mod];
1276 if (!connect_to.empty()) {
1277 if (_monitor_out->output()->connect (p, connect_to, this)) {
1278 error << string_compose (
1279 _("cannot connect control output %1 to %2"),
1290 /* Hold process lock while doing this so that we don't hear bits and
1291 * pieces of audio as we work on each route.
1294 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1296 /* Connect tracks to monitor section. Note that in an
1297 existing session, the internal sends will already exist, but we want the
1298 routes to notice that they connect to the control out specifically.
1302 boost::shared_ptr<RouteList> rls = routes.reader ();
1304 ProcessorChangeBlocker pcb (this, false /* XXX */);
1306 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1308 if ((*x)->is_monitor()) {
1310 } else if ((*x)->is_master()) {
1313 (*x)->enable_monitor_send ();
1318 auditioner->connect ();
1320 Config->ParameterChanged ("use-monitor-bus");
1324 Session::reset_monitor_section ()
1326 /* Process lock should be held by the caller.*/
1328 if (!_monitor_out || Profile->get_trx()) {
1332 uint32_t limit = _master_out->n_outputs().n_audio();
1334 /* connect the inputs to the master bus outputs. this
1335 * represents a separate data feed from the internal sends from
1336 * each route. as of jan 2011, it allows the monitor section to
1337 * conditionally ignore either the internal sends or the normal
1338 * input feed, but we should really find a better way to do
1342 _master_out->output()->disconnect (this);
1343 _monitor_out->output()->disconnect (this);
1345 // monitor section follow master bus - except midi
1346 ChanCount mon_chn (_master_out->output()->n_ports());
1347 mon_chn.set_midi (0);
1349 _monitor_out->input()->ensure_io (mon_chn, false, this);
1350 _monitor_out->output()->ensure_io (mon_chn, false, this);
1352 for (uint32_t n = 0; n < limit; ++n) {
1353 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1354 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1357 string connect_to = o->name();
1358 if (_monitor_out->input()->connect (p, connect_to, this)) {
1359 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1366 /* connect monitor section to physical outs
1369 if (Config->get_auto_connect_standard_busses()) {
1371 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1373 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1376 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1378 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1379 Config->get_monitor_bus_preferred_bundle())
1385 /* Monitor bus is audio only */
1387 vector<string> outputs[DataType::num_types];
1389 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1390 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1393 uint32_t mod = outputs[DataType::AUDIO].size();
1394 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1398 for (uint32_t n = 0; n < limit; ++n) {
1400 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1402 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1403 connect_to = outputs[DataType::AUDIO][n % mod];
1406 if (!connect_to.empty()) {
1407 if (_monitor_out->output()->connect (p, connect_to, this)) {
1408 error << string_compose (
1409 _("cannot connect control output %1 to %2"),
1420 /* Connect tracks to monitor section. Note that in an
1421 existing session, the internal sends will already exist, but we want the
1422 routes to notice that they connect to the control out specifically.
1426 boost::shared_ptr<RouteList> rls = routes.reader ();
1428 ProcessorChangeBlocker pcb (this, false);
1430 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1432 if ((*x)->is_monitor()) {
1434 } else if ((*x)->is_master()) {
1437 (*x)->enable_monitor_send ();
1443 Session::hookup_io ()
1445 /* stop graph reordering notifications from
1446 causing resorts, etc.
1449 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1453 /* we delay creating the auditioner till now because
1454 it makes its own connections to ports.
1458 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1460 throw failed_constructor ();
1462 a->use_new_diskstream ();
1466 catch (failed_constructor& err) {
1467 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1471 /* load bundles, which we may have postponed earlier on */
1472 if (_bundle_xml_node) {
1473 load_bundles (*_bundle_xml_node);
1474 delete _bundle_xml_node;
1477 /* Tell all IO objects to connect themselves together */
1479 IO::enable_connecting ();
1481 /* Now tell all "floating" ports to connect to whatever
1482 they should be connected to.
1485 AudioEngine::instance()->reconnect_ports ();
1487 /* Anyone who cares about input state, wake up and do something */
1489 IOConnectionsComplete (); /* EMIT SIGNAL */
1491 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1493 /* now handle the whole enchilada as if it was one
1494 graph reorder event.
1499 /* update the full solo state, which can't be
1500 correctly determined on a per-route basis, but
1501 needs the global overview that only the session
1505 update_route_solo_state ();
1509 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1511 boost::shared_ptr<Track> track = wp.lock ();
1516 boost::shared_ptr<Playlist> playlist;
1518 if ((playlist = track->playlist()) != 0) {
1519 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1520 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1521 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1526 Session::record_enabling_legal () const
1528 /* this used to be in here, but survey says.... we don't need to restrict it */
1529 // if (record_status() == Recording) {
1533 if (Config->get_all_safe()) {
1540 Session::set_track_monitor_input_status (bool yn)
1542 boost::shared_ptr<RouteList> rl = routes.reader ();
1543 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1544 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1545 if (tr && tr->rec_enable_control()->get_value()) {
1546 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1547 tr->request_input_monitoring (yn);
1553 Session::auto_punch_start_changed (Location* location)
1555 replace_event (SessionEvent::PunchIn, location->start());
1557 if (get_record_enabled() && config.get_punch_in()) {
1558 /* capture start has been changed, so save new pending state */
1559 save_state ("", true);
1564 Session::auto_punch_end_changed (Location* location)
1566 framepos_t when_to_stop = location->end();
1567 // when_to_stop += _worst_output_latency + _worst_input_latency;
1568 replace_event (SessionEvent::PunchOut, when_to_stop);
1572 Session::auto_punch_changed (Location* location)
1574 framepos_t when_to_stop = location->end();
1576 replace_event (SessionEvent::PunchIn, location->start());
1577 //when_to_stop += _worst_output_latency + _worst_input_latency;
1578 replace_event (SessionEvent::PunchOut, when_to_stop);
1581 /** @param loc A loop location.
1582 * @param pos Filled in with the start time of the required fade-out (in session frames).
1583 * @param length Filled in with the length of the required fade-out.
1586 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1588 pos = max (loc->start(), loc->end() - 64);
1589 length = loc->end() - pos;
1593 Session::auto_loop_changed (Location* location)
1595 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1598 auto_loop_declick_range (location, dcp, dcl);
1600 if (transport_rolling() && play_loop) {
1602 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1604 // if (_transport_frame > location->end()) {
1606 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1607 // relocate to beginning of loop
1608 clear_events (SessionEvent::LocateRoll);
1610 request_locate (location->start(), true);
1613 else if (Config->get_seamless_loop() && !loop_changing) {
1615 // schedule a locate-roll to refill the diskstreams at the
1616 // previous loop end
1617 loop_changing = true;
1619 if (location->end() > last_loopend) {
1620 clear_events (SessionEvent::LocateRoll);
1621 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1627 clear_events (SessionEvent::AutoLoopDeclick);
1628 clear_events (SessionEvent::AutoLoop);
1631 /* possibly move playhead if not rolling; if we are rolling we'll move
1632 to the loop start on stop if that is appropriate.
1637 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1638 if (pos == location->start()) {
1639 request_locate (pos);
1644 last_loopend = location->end();
1649 Session::set_auto_punch_location (Location* location)
1653 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1654 punch_connections.drop_connections();
1655 existing->set_auto_punch (false, this);
1656 remove_event (existing->start(), SessionEvent::PunchIn);
1657 clear_events (SessionEvent::PunchOut);
1658 auto_punch_location_changed (0);
1663 if (location == 0) {
1667 if (location->end() <= location->start()) {
1668 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1672 punch_connections.drop_connections ();
1674 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1675 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1676 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1678 location->set_auto_punch (true, this);
1680 auto_punch_changed (location);
1682 auto_punch_location_changed (location);
1686 Session::set_session_extents (framepos_t start, framepos_t end)
1689 if ((existing = _locations->session_range_location()) == 0) {
1690 //if there is no existing session, we need to make a new session location (should never happen)
1691 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange, 0);
1695 error << _("Session: you can't use that location for session start/end)") << endmsg;
1699 existing->set( start, end );
1705 Session::set_auto_loop_location (Location* location)
1709 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1710 loop_connections.drop_connections ();
1711 existing->set_auto_loop (false, this);
1712 remove_event (existing->end(), SessionEvent::AutoLoop);
1715 auto_loop_declick_range (existing, dcp, dcl);
1716 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1717 auto_loop_location_changed (0);
1722 if (location == 0) {
1726 if (location->end() <= location->start()) {
1727 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1731 last_loopend = location->end();
1733 loop_connections.drop_connections ();
1735 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1736 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1737 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1738 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1740 location->set_auto_loop (true, this);
1742 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1743 // set all tracks to use internal looping
1744 boost::shared_ptr<RouteList> rl = routes.reader ();
1745 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1746 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1747 if (tr && !tr->hidden()) {
1748 tr->set_loop (location);
1753 /* take care of our stuff first */
1755 auto_loop_changed (location);
1757 /* now tell everyone else */
1759 auto_loop_location_changed (location);
1763 Session::update_marks (Location*)
1769 Session::update_skips (Location* loc, bool consolidate)
1771 if (_ignore_skips_updates) {
1775 Locations::LocationList skips;
1778 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1779 consolidate_skips (loc);
1782 sync_locations_to_skips ();
1788 Session::consolidate_skips (Location* loc)
1790 Locations::LocationList all_locations = _locations->list ();
1792 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1794 if (!(*l)->is_skip ()) {
1799 /* don't test against self */
1806 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1807 case Evoral::OverlapInternal:
1808 case Evoral::OverlapExternal:
1809 case Evoral::OverlapStart:
1810 case Evoral::OverlapEnd:
1811 /* adjust new location to cover existing one */
1812 loc->set_start (min (loc->start(), (*l)->start()));
1813 loc->set_end (max (loc->end(), (*l)->end()));
1814 /* we don't need this one any more */
1815 _locations->remove (*l);
1816 /* the location has been deleted, so remove reference to it in our local list */
1817 l = all_locations.erase (l);
1820 case Evoral::OverlapNone:
1828 Session::sync_locations_to_skips ()
1830 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1831 * Session::_sync_locations_to_skips() from the audioengine thread.
1833 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1837 Session::_sync_locations_to_skips ()
1839 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1841 Locations::LocationList const & locs (_locations->list());
1843 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1845 Location* location = *i;
1847 if (location->is_skip() && location->is_skipping()) {
1848 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1856 Session::location_added (Location *location)
1858 if (location->is_auto_punch()) {
1859 set_auto_punch_location (location);
1862 if (location->is_auto_loop()) {
1863 set_auto_loop_location (location);
1866 if (location->is_session_range()) {
1867 /* no need for any signal handling or event setting with the session range,
1868 because we keep a direct reference to it and use its start/end directly.
1870 _session_range_location = location;
1873 if (location->is_mark()) {
1874 /* listen for per-location signals that require us to do any * global updates for marks */
1876 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1877 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1878 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1879 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1880 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1883 if (location->is_range_marker()) {
1884 /* listen for per-location signals that require us to do any * global updates for marks */
1886 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1887 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1888 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1889 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1890 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1893 if (location->is_skip()) {
1894 /* listen for per-location signals that require us to update skip-locate events */
1896 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1897 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1898 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1899 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1900 location->PositionLockStyleChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1902 update_skips (location, true);
1909 Session::location_removed (Location *location)
1911 if (location->is_auto_loop()) {
1912 set_auto_loop_location (0);
1913 set_track_loop (false);
1916 if (location->is_auto_punch()) {
1917 set_auto_punch_location (0);
1920 if (location->is_session_range()) {
1921 /* this is never supposed to happen */
1922 error << _("programming error: session range removed!") << endl;
1925 if (location->is_skip()) {
1927 update_skips (location, false);
1934 Session::locations_changed ()
1936 _locations->apply (*this, &Session::_locations_changed);
1940 Session::_locations_changed (const Locations::LocationList& locations)
1942 /* There was some mass-change in the Locations object.
1944 We might be re-adding a location here but it doesn't actually matter
1945 for all the locations that the Session takes an interest in.
1949 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1950 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1951 location_added (*i);
1955 update_skips (NULL, false);
1959 Session::enable_record ()
1961 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1962 /* no recording at anything except normal speed */
1967 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1969 if (rs == Recording) {
1973 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1975 _last_record_location = _transport_frame;
1976 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1978 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1979 set_track_monitor_input_status (true);
1982 RecordStateChanged ();
1989 Session::set_all_tracks_record_enabled (bool enable )
1991 boost::shared_ptr<RouteList> rl = routes.reader();
1992 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1996 Session::disable_record (bool rt_context, bool force)
2000 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
2002 if (!Config->get_latched_record_enable () || force) {
2003 g_atomic_int_set (&_record_status, Disabled);
2004 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
2006 if (rs == Recording) {
2007 g_atomic_int_set (&_record_status, Enabled);
2011 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2012 set_track_monitor_input_status (false);
2015 RecordStateChanged (); /* emit signal */
2018 remove_pending_capture_state ();
2020 unset_preroll_record_punch ();
2025 Session::step_back_from_record ()
2027 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
2029 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
2030 set_track_monitor_input_status (false);
2033 RecordStateChanged (); /* emit signal */
2038 Session::maybe_enable_record (bool rt_context)
2040 if (_step_editors > 0) {
2044 g_atomic_int_set (&_record_status, Enabled);
2046 /* This function is currently called from somewhere other than an RT thread.
2047 * (except maybe lua scripts, which can use rt_context = true)
2048 * This save_state() call therefore doesn't impact anything. Doing it here
2049 * means that we save pending state of which sources the next record will use,
2050 * which gives us some chance of recovering from a crash during the record.
2054 save_state ("", true);
2057 if (_transport_speed) {
2058 if (!config.get_punch_in() && !preroll_record_punch_enabled ()) {
2062 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2063 RecordStateChanged (); /* EMIT SIGNAL */
2070 Session::audible_frame () const
2074 frameoffset_t offset = worst_playback_latency (); // - _engine.samples_since_cycle_start ();
2075 offset *= transport_speed ();
2077 if (synced_to_engine()) {
2078 /* Note: this is basically just sync-to-JACK */
2079 ret = _engine.transport_frame();
2081 ret = _transport_frame;
2084 if (transport_rolling()) {
2087 /* Check to see if we have passed the first guaranteed
2088 * audible frame past our last start position. if not,
2089 * return that last start point because in terms
2090 * of audible frames, we have not moved yet.
2092 * `Start position' in this context means the time we last
2093 * either started, located, or changed transport direction.
2096 if (_transport_speed > 0.0f) {
2098 if (!play_loop || !have_looped) {
2099 if (ret < _last_roll_or_reversal_location) {
2100 return _last_roll_or_reversal_location;
2104 Location *location = _locations->auto_loop_location();
2105 frameoffset_t lo = location->start() - ret;
2107 ret = location->end () - lo;
2111 } else if (_transport_speed < 0.0f) {
2113 /* XXX wot? no backward looping? */
2115 if (ret > _last_roll_or_reversal_location) {
2116 return _last_roll_or_reversal_location;
2121 return std::max ((framepos_t)0, ret);
2126 Session::preroll_samples (framepos_t pos) const
2128 const float pr = Config->get_preroll_seconds();
2129 if (pos >= 0 && pr < 0) {
2130 const Tempo& tempo = _tempo_map->tempo_at_frame (pos);
2131 const Meter& meter = _tempo_map->meter_at_frame (pos);
2132 return meter.frames_per_bar (tempo, frame_rate()) * -pr;
2137 return pr * frame_rate();
2141 Session::set_frame_rate (framecnt_t frames_per_second)
2143 /** \fn void Session::set_frame_size(framecnt_t)
2144 the AudioEngine object that calls this guarantees
2145 that it will not be called while we are also in
2146 ::process(). Its fine to do things that block
2150 if (_base_frame_rate == 0) {
2151 _base_frame_rate = frames_per_second;
2153 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2154 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2156 _nominal_frame_rate = frames_per_second;
2161 reset_write_sources (false);
2163 // XXX we need some equivalent to this, somehow
2164 // SndFileSource::setup_standard_crossfades (frames_per_second);
2168 /* XXX need to reset/reinstantiate all LADSPA plugins */
2172 Session::set_block_size (pframes_t nframes)
2174 /* the AudioEngine guarantees
2175 that it will not be called while we are also in
2176 ::process(). It is therefore fine to do things that block
2181 current_block_size = nframes;
2185 boost::shared_ptr<RouteList> r = routes.reader ();
2187 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2188 (*i)->set_block_size (nframes);
2191 boost::shared_ptr<RouteList> rl = routes.reader ();
2192 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2193 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2195 tr->set_block_size (nframes);
2199 set_worst_io_latencies ();
2205 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2207 boost::shared_ptr<Route> r2;
2209 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2210 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2214 /* make a copy of the existing list of routes that feed r1 */
2216 Route::FedBy existing (r1->fed_by());
2218 /* for each route that feeds r1, recurse, marking it as feeding
2222 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2223 if (!(r2 = i->r.lock ())) {
2224 /* (*i) went away, ignore it */
2228 /* r2 is a route that feeds r1 which somehow feeds base. mark
2229 base as being fed by r2
2232 rbase->add_fed_by (r2, i->sends_only);
2236 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2240 if (r1->feeds (r2) && r2->feeds (r1)) {
2244 /* now recurse, so that we can mark base as being fed by
2245 all routes that feed r2
2248 trace_terminal (r2, rbase);
2255 Session::resort_routes ()
2257 /* don't do anything here with signals emitted
2258 by Routes during initial setup or while we
2259 are being destroyed.
2262 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2266 if (_route_deletion_in_progress) {
2271 RCUWriter<RouteList> writer (routes);
2272 boost::shared_ptr<RouteList> r = writer.get_copy ();
2273 resort_routes_using (r);
2274 /* writer goes out of scope and forces update */
2278 if (DEBUG_ENABLED(DEBUG::Graph)) {
2279 boost::shared_ptr<RouteList> rl = routes.reader ();
2280 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2281 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2283 const Route::FedBy& fb ((*i)->fed_by());
2285 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2286 boost::shared_ptr<Route> sf = f->r.lock();
2288 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2297 /** This is called whenever we need to rebuild the graph of how we will process
2299 * @param r List of routes, in any order.
2303 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2305 /* We are going to build a directed graph of our routes;
2306 this is where the edges of that graph are put.
2311 /* Go through all routes doing two things:
2313 * 1. Collect the edges of the route graph. Each of these edges
2314 * is a pair of routes, one of which directly feeds the other
2315 * either by a JACK connection or by an internal send.
2317 * 2. Begin the process of making routes aware of which other
2318 * routes directly or indirectly feed them. This information
2319 * is used by the solo code.
2322 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2324 /* Clear out the route's list of direct or indirect feeds */
2325 (*i)->clear_fed_by ();
2327 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2329 bool via_sends_only;
2331 /* See if this *j feeds *i according to the current state of the JACK
2332 connections and internal sends.
2334 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2335 /* add the edge to the graph (part #1) */
2336 edges.add (*j, *i, via_sends_only);
2337 /* tell the route (for part #2) */
2338 (*i)->add_fed_by (*j, via_sends_only);
2343 /* Attempt a topological sort of the route graph */
2344 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2346 if (sorted_routes) {
2347 /* We got a satisfactory topological sort, so there is no feedback;
2350 Note: the process graph rechain does not require a
2351 topologically-sorted list, but hey ho.
2353 if (_process_graph) {
2354 _process_graph->rechain (sorted_routes, edges);
2357 _current_route_graph = edges;
2359 /* Complete the building of the routes' lists of what directly
2360 or indirectly feeds them.
2362 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2363 trace_terminal (*i, *i);
2366 *r = *sorted_routes;
2369 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2370 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2375 SuccessfulGraphSort (); /* EMIT SIGNAL */
2378 /* The topological sort failed, so we have a problem. Tell everyone
2379 and stick to the old graph; this will continue to be processed, so
2380 until the feedback is fixed, what is played back will not quite
2381 reflect what is actually connected. Note also that we do not
2382 do trace_terminal here, as it would fail due to an endless recursion,
2383 so the solo code will think that everything is still connected
2387 FeedbackDetected (); /* EMIT SIGNAL */
2392 /** Find a route name starting with \a base, maybe followed by the
2393 * lowest \a id. \a id will always be added if \a definitely_add_number
2394 * is true on entry; otherwise it will only be added if required
2395 * to make the name unique.
2397 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2398 * The available route name with the lowest ID will be used, and \a id
2399 * will be set to the ID.
2401 * \return false if a route name could not be found, and \a track_name
2402 * and \a id do not reflect a free route name.
2405 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2407 /* the base may conflict with ports that do not belong to existing
2408 routes, but hidden objects like the click track. So check port names
2409 before anything else.
2412 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2413 if (base == reserved->first) {
2414 /* Check if this reserved name already exists, and if
2415 so, disallow it without a numeric suffix.
2417 if (!reserved->second || route_by_name (reserved->first)) {
2418 definitely_add_number = true;
2427 /* if we have "base 1" already, it doesn't make sense to add "base"
2428 * if "base 1" has been deleted, adding "base" is no worse than "base 1"
2430 if (!definitely_add_number && route_by_name (base) == 0 && (route_by_name (string_compose("%1 1", base)) == 0)) {
2431 /* just use the base */
2437 name = string_compose ("%1 %2", base, id);
2439 if (route_by_name (name) == 0) {
2445 } while (id < (UINT_MAX-1));
2450 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2452 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2454 in = ChanCount::ZERO;
2455 out = ChanCount::ZERO;
2457 boost::shared_ptr<RouteList> r = routes.reader ();
2459 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2460 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2461 if (tr && !tr->is_auditioner()) {
2462 in += tr->n_inputs();
2463 out += tr->n_outputs();
2469 Session::default_track_name_pattern (DataType t)
2472 case DataType::AUDIO:
2473 if (Profile->get_trx()) {
2480 case DataType::MIDI:
2487 /** Caller must not hold process lock
2488 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2489 * @param instrument plugin info for the instrument to insert pre-fader, if any
2491 list<boost::shared_ptr<MidiTrack> >
2492 Session::new_midi_track (const ChanCount& input, const ChanCount& output, bool strict_io,
2493 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2494 RouteGroup* route_group, uint32_t how_many,
2495 string name_template, PresentationInfo::order_t order,
2499 uint32_t track_id = 0;
2501 RouteList new_routes;
2502 list<boost::shared_ptr<MidiTrack> > ret;
2504 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2505 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2508 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2509 error << "cannot find name for new midi track" << endmsg;
2513 boost::shared_ptr<MidiTrack> track;
2516 track.reset (new MidiTrack (*this, track_name, mode));
2518 if (track->init ()) {
2523 track->set_strict_io (true);
2526 track->use_new_diskstream();
2528 BOOST_MARK_TRACK (track);
2531 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2532 if (track->input()->ensure_io (input, false, this)) {
2533 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2537 if (track->output()->ensure_io (output, false, this)) {
2538 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2543 track->non_realtime_input_change();
2546 route_group->add (track);
2549 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2551 new_routes.push_back (track);
2552 ret.push_back (track);
2555 catch (failed_constructor &err) {
2556 error << _("Session: could not create new midi track.") << endmsg;
2560 catch (AudioEngine::PortRegistrationFailure& pfe) {
2562 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;
2570 if (!new_routes.empty()) {
2571 StateProtector sp (this);
2572 if (Profile->get_trx()) {
2573 add_routes (new_routes, false, false, false, order);
2575 add_routes (new_routes, true, true, false, order);
2579 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2580 PluginPtr plugin = instrument->load (*this);
2582 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2586 plugin->load_preset (*pset);
2588 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2590 pi->set_strict_io (true);
2593 (*r)->add_processor (pi, PreFader);
2595 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2596 (*r)->move_instrument_down (false);
2606 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, bool strict_io,
2607 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2608 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2611 uint32_t bus_id = 0;
2615 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2618 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2619 error << "cannot find name for new midi bus" << endmsg;
2624 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2631 bus->set_strict_io (true);
2634 BOOST_MARK_ROUTE(bus);
2637 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2639 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2640 error << _("cannot configure new midi bus input") << endmsg;
2645 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2646 error << _("cannot configure new midi bus output") << endmsg;
2652 route_group->add (bus);
2655 bus->add_internal_return ();
2656 ret.push_back (bus);
2659 catch (failed_constructor &err) {
2660 error << _("Session: could not create new audio route.") << endmsg;
2664 catch (AudioEngine::PortRegistrationFailure& pfe) {
2665 error << pfe.what() << endmsg;
2675 StateProtector sp (this);
2676 add_routes (ret, false, false, false, order);
2679 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2680 PluginPtr plugin = instrument->load (*this);
2682 warning << "Failed to add Synth Plugin to newly created track." << endmsg;
2686 plugin->load_preset (*pset);
2688 boost::shared_ptr<PluginInsert> pi (new PluginInsert (*this, plugin));
2690 pi->set_strict_io (true);
2693 (*r)->add_processor (pi, PreFader);
2695 if (Profile->get_mixbus () && pi->configured () && pi->output_streams().n_audio() > 2) {
2696 (*r)->move_instrument_down (false);
2708 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2710 boost::shared_ptr<Route> midi_track (wmt.lock());
2716 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2718 if (change.after.n_audio() <= change.before.n_audio()) {
2722 /* new audio ports: make sure the audio goes somewhere useful,
2723 * unless the user has no-auto-connect selected.
2725 * The existing ChanCounts don't matter for this call as they are only
2726 * to do with matching input and output indices, and we are only changing
2729 auto_connect_route (midi_track, false, ChanCount(), change.before);
2733 #ifdef USE_TRACKS_CODE_FEATURES
2736 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2738 return route1->remote_control_id() < route2->remote_control_id();
2742 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2744 // it is not allowed to perform connection
2745 if (!IO::connecting_legal) {
2749 // if we are deleting routes we will call this once at the end
2750 if (_route_deletion_in_progress) {
2754 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2760 // We need to disconnect the route's inputs and outputs first
2761 // basing on autoconnect configuration
2762 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2763 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2765 ChanCount existing_inputs;
2766 ChanCount existing_outputs;
2767 count_existing_track_channels (existing_inputs, existing_outputs);
2769 //ChanCount inputs = ChanCount::ZERO;
2770 //ChanCount outputs = ChanCount::ZERO;
2772 RouteList existing_routes = *routes.reader ();
2773 existing_routes.sort (compare_routes_by_remote_id);
2776 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2778 vector<string> physinputs;
2779 vector<string> physoutputs;
2781 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2782 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2784 uint32_t input_n = 0;
2785 uint32_t output_n = 0;
2786 RouteList::iterator rIter = existing_routes.begin();
2787 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2788 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2789 for (; rIter != existing_routes.end(); ++rIter) {
2790 if (*rIter == _master_out || *rIter == _monitor_out ) {
2794 if (current_output_auto_connection == AutoConnectPhysical) {
2795 (*rIter)->amp()->deactivate();
2796 } else if (current_output_auto_connection == AutoConnectMaster) {
2797 (*rIter)->amp()->activate();
2800 if (reconnectIputs) {
2801 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2803 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2805 if (current_input_auto_connection & AutoConnectPhysical) {
2807 if ( input_n == physinputs.size() ) {
2811 string port = physinputs[input_n];
2813 if (port.empty() ) {
2814 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2817 //GZ: check this; could be heavy
2818 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2824 if (reconnectOutputs) {
2826 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2827 if (current_output_auto_connection & AutoConnectPhysical) {
2829 //GZ: check this; could be heavy
2830 (*rIter)->output()->disconnect (this);
2831 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2833 //GZ: check this; could be heavy
2834 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2836 } else if (current_output_auto_connection & AutoConnectMaster){
2838 if (!reconnect_master) {
2842 //GZ: check this; could be heavy
2843 (*rIter)->output()->disconnect (this);
2846 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2847 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2849 error << error << "Master bus is not available" << endmsg;
2854 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2855 if (current_output_auto_connection & AutoConnectPhysical) {
2857 if ( output_n == physoutputs.size() ) {
2861 string port = physoutputs[output_n];
2863 if (port.empty() ) {
2864 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2867 //GZ: check this; could be heavy
2868 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2871 } else if (current_output_auto_connection & AutoConnectMaster) {
2873 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2877 // connect to master bus
2878 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2880 if (port.empty() ) {
2881 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2885 //GZ: check this; could be heavy
2886 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2893 _master_out->output()->disconnect (this);
2894 auto_connect_master_bus ();
2899 session_routes_reconnected (); /* EMIT SIGNAL */
2903 Session::reconnect_midi_scene_ports(bool inputs)
2907 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2909 scene_in_ptr->disconnect_all ();
2911 std::vector<EngineStateController::MidiPortState> midi_port_states;
2912 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2914 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2916 for (; state_iter != midi_port_states.end(); ++state_iter) {
2917 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2918 scene_in_ptr->connect (state_iter->name);
2925 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2927 if (scene_out_ptr ) {
2928 scene_out_ptr->disconnect_all ();
2930 std::vector<EngineStateController::MidiPortState> midi_port_states;
2931 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2933 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2935 for (; state_iter != midi_port_states.end(); ++state_iter) {
2936 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2937 scene_out_ptr->connect (state_iter->name);
2945 Session::reconnect_mtc_ports ()
2947 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2953 mtc_in_ptr->disconnect_all ();
2955 std::vector<EngineStateController::MidiPortState> midi_port_states;
2956 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2958 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2960 for (; state_iter != midi_port_states.end(); ++state_iter) {
2961 if (state_iter->available && state_iter->mtc_in) {
2962 mtc_in_ptr->connect (state_iter->name);
2966 if (!_midi_ports->mtc_input_port ()->connected () &&
2967 config.get_external_sync () &&
2968 (Config->get_sync_source () == MTC) ) {
2969 config.set_external_sync (false);
2972 if ( ARDOUR::Profile->get_trx () ) {
2973 // Tracks need this signal to update timecode_source_dropdown
2974 MtcOrLtcInputPortChanged (); //emit signal
2979 Session::reconnect_mmc_ports(bool inputs)
2981 if (inputs ) { // get all enabled midi input ports
2983 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2985 mmc_in_ptr->disconnect_all ();
2986 std::vector<std::string> enabled_midi_inputs;
2987 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2989 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2991 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2992 mmc_in_ptr->connect (*port_iter);
2996 } else { // get all enabled midi output ports
2998 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
3000 mmc_out_ptr->disconnect_all ();
3001 std::vector<std::string> enabled_midi_outputs;
3002 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
3004 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
3006 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
3007 mmc_out_ptr->connect (*port_iter);
3016 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
3018 if (first_new_order == PresentationInfo::max_order) {
3019 /* adding at end, no worries */
3023 /* create a gap in the presentation info to accomodate @param how_many
3027 get_stripables (sl);
3029 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
3030 boost::shared_ptr<Stripable> s (*si);
3032 if (s->is_monitor() || s->is_auditioner()) {
3036 if (s->presentation_info().order () >= first_new_order) {
3037 s->set_presentation_order (s->presentation_info().order () + how_many);
3042 /** Caller must not hold process lock
3043 * @param name_template string to use for the start of the name, or "" to use "Audio".
3045 list< boost::shared_ptr<AudioTrack> >
3046 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
3047 uint32_t how_many, string name_template, PresentationInfo::order_t order,
3051 uint32_t track_id = 0;
3053 RouteList new_routes;
3054 list<boost::shared_ptr<AudioTrack> > ret;
3056 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
3057 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
3061 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
3062 error << "cannot find name for new audio track" << endmsg;
3066 boost::shared_ptr<AudioTrack> track;
3069 track.reset (new AudioTrack (*this, track_name, mode));
3071 if (track->init ()) {
3075 if (Profile->get_mixbus ()) {
3076 track->set_strict_io (true);
3079 if (ARDOUR::Profile->get_trx ()) {
3080 // TRACKS considers it's not a USE CASE, it's
3081 // a piece of behavior of the session model:
3083 // Gain for a newly created route depends on
3084 // the current output_auto_connect mode:
3086 // 0 for Stereo Out mode
3088 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3089 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3093 track->use_new_diskstream();
3095 BOOST_MARK_TRACK (track);
3098 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3100 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3101 error << string_compose (
3102 _("cannot configure %1 in/%2 out configuration for new audio track"),
3103 input_channels, output_channels)
3108 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3109 error << string_compose (
3110 _("cannot configure %1 in/%2 out configuration for new audio track"),
3111 input_channels, output_channels)
3118 route_group->add (track);
3121 track->non_realtime_input_change();
3123 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3125 new_routes.push_back (track);
3126 ret.push_back (track);
3129 catch (failed_constructor &err) {
3130 error << _("Session: could not create new audio track.") << endmsg;
3134 catch (AudioEngine::PortRegistrationFailure& pfe) {
3136 error << pfe.what() << endmsg;
3144 if (!new_routes.empty()) {
3145 StateProtector sp (this);
3146 if (Profile->get_trx()) {
3147 add_routes (new_routes, false, false, false, order);
3149 add_routes (new_routes, true, true, false, order);
3156 /** Caller must not hold process lock.
3157 * @param name_template string to use for the start of the name, or "" to use "Bus".
3160 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3161 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3164 uint32_t bus_id = 0;
3168 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3171 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3172 error << "cannot find name for new audio bus" << endmsg;
3177 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3183 if (Profile->get_mixbus ()) {
3184 bus->set_strict_io (true);
3187 BOOST_MARK_ROUTE(bus);
3190 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3192 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3193 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3194 input_channels, output_channels)
3200 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3201 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3202 input_channels, output_channels)
3209 route_group->add (bus);
3212 bus->add_internal_return ();
3213 ret.push_back (bus);
3216 catch (failed_constructor &err) {
3217 error << _("Session: could not create new audio route.") << endmsg;
3221 catch (AudioEngine::PortRegistrationFailure& pfe) {
3222 error << pfe.what() << endmsg;
3232 StateProtector sp (this);
3233 if (Profile->get_trx()) {
3234 add_routes (ret, false, false, false, order);
3236 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3245 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name_base,
3246 PlaylistDisposition pd)
3250 if (!tree.read (template_path.c_str())) {
3254 return new_route_from_template (how_many, insert_at, *tree.root(), name_base, pd);
3258 Session::new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3261 uint32_t number = 0;
3262 const uint32_t being_added = how_many;
3263 /* This will prevent the use of any existing XML-provided PBD::ID
3266 Stateful::ForceIDRegeneration force_ids;
3267 IO::disable_connecting ();
3271 /* We're going to modify the node contents a bit so take a
3272 * copy. The node may be re-used when duplicating more than once.
3275 XMLNode node_copy (node);
3280 if (!name_base.empty()) {
3282 /* if we're adding more than one routes, force
3283 * all the names of the new routes to be
3284 * numbered, via the final parameter.
3287 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3288 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3294 string const route_name = node_copy.property(X_("name"))->value ();
3296 /* generate a new name by adding a number to the end of the template name */
3297 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3298 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3299 abort(); /*NOTREACHED*/
3303 /* set this name in the XML description that we are about to use */
3305 if (pd == CopyPlaylist) {
3306 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3308 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3309 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3310 // Use same name as Route::set_name_in_state so playlist copy
3311 // is picked up when creating the Route in XMLRouteFactory below
3312 playlist = PlaylistFactory::create (playlist, string_compose ("%1.1", name));
3313 playlist->reset_shares ();
3315 } else if (pd == SharePlaylist) {
3316 XMLNode* ds_node = find_named_node (node_copy, "Diskstream");
3318 const std::string playlist_name = ds_node->property (X_("playlist"))->value ();
3319 boost::shared_ptr<Playlist> playlist = playlists->by_name (playlist_name);
3320 playlist->share_with ((node_copy.property (X_("id")))->value());
3324 bool rename_playlist = (pd == CopyPlaylist || pd == NewPlaylist);
3326 Route::set_name_in_state (node_copy, name, rename_playlist);
3328 /* trim bitslots from listen sends so that new ones are used */
3329 XMLNodeList children = node_copy.children ();
3330 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3331 if ((*i)->name() == X_("Processor")) {
3332 /* ForceIDRegeneration does not catch the following */
3333 XMLProperty const * role = (*i)->property (X_("role"));
3334 XMLProperty const * type = (*i)->property (X_("type"));
3335 if (role && role->value() == X_("Aux")) {
3336 /* check if the target bus exists.
3337 * we should not save aux-sends in templates.
3339 XMLProperty const * target = (*i)->property (X_("target"));
3341 (*i)->add_property ("type", "dangling-aux-send");
3344 boost::shared_ptr<Route> r = route_by_id (target->value());
3345 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3346 (*i)->add_property ("type", "dangling-aux-send");
3350 if (role && role->value() == X_("Listen")) {
3351 (*i)->remove_property (X_("bitslot"));
3353 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3355 Delivery::Role xrole;
3356 uint32_t bitslot = 0;
3357 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3358 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3359 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3360 (*i)->remove_property (X_("bitslot"));
3361 (*i)->remove_property (X_("name"));
3362 (*i)->add_property ("bitslot", buf);
3363 (*i)->add_property ("name", name);
3365 else if (type && type->value() == X_("intreturn")) {
3366 (*i)->remove_property (X_("bitslot"));
3367 (*i)->add_property ("ignore-bitslot", "1");
3369 else if (type && type->value() == X_("return")) {
3370 // Return::set_state() generates a new one
3371 (*i)->remove_property (X_("bitslot"));
3373 else if (type && type->value() == X_("port")) {
3374 // PortInsert::set_state() handles the bitslot
3375 (*i)->remove_property (X_("bitslot"));
3376 (*i)->add_property ("ignore-name", "1");
3381 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3384 error << _("Session: cannot create track/bus from template description") << endmsg;
3388 if (boost::dynamic_pointer_cast<Track>(route)) {
3389 /* force input/output change signals so that the new diskstream
3390 picks up the configuration of the route. During session
3391 loading this normally happens in a different way.
3394 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3396 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3397 change.after = route->input()->n_ports();
3398 route->input()->changed (change, this);
3399 change.after = route->output()->n_ports();
3400 route->output()->changed (change, this);
3403 ret.push_back (route);
3406 catch (failed_constructor &err) {
3407 error << _("Session: could not create new route from template") << endmsg;
3411 catch (AudioEngine::PortRegistrationFailure& pfe) {
3412 error << pfe.what() << endmsg;
3421 StateProtector sp (this);
3422 if (Profile->get_trx()) {
3423 add_routes (ret, false, false, false, insert_at);
3425 add_routes (ret, true, true, false, insert_at);
3427 IO::enable_connecting ();
3434 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3437 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3438 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3441 error << _("Adding new tracks/busses failed") << endmsg;
3446 update_latency (true);
3447 update_latency (false);
3452 save_state (_current_snapshot_name);
3455 update_route_record_state ();
3457 RouteAdded (new_routes); /* EMIT SIGNAL */
3461 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3463 ChanCount existing_inputs;
3464 ChanCount existing_outputs;
3468 count_existing_track_channels (existing_inputs, existing_outputs);
3471 RCUWriter<RouteList> writer (routes);
3472 boost::shared_ptr<RouteList> r = writer.get_copy ();
3473 r->insert (r->end(), new_routes.begin(), new_routes.end());
3474 n_routes = r->size();
3476 /* if there is no control out and we're not in the middle of loading,
3477 * resort the graph here. if there is a control out, we will resort
3478 * toward the end of this method. if we are in the middle of loading,
3479 * we will resort when done.
3482 if (!_monitor_out && IO::connecting_legal) {
3483 resort_routes_using (r);
3487 /* auditioner and monitor routes are not part of the order */
3489 assert (n_routes > 0);
3493 assert (n_routes > 0);
3497 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3498 ensure_route_presentation_info_gap (order, new_routes.size());
3501 PresentationInfo::ChangeSuspender cs;
3503 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3505 boost::weak_ptr<Route> wpr (*x);
3506 boost::shared_ptr<Route> r (*x);
3508 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3509 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3510 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3512 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3513 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3514 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3516 if (r->is_master()) {
3520 if (r->is_monitor()) {
3524 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3526 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3527 track_playlist_changed (boost::weak_ptr<Track> (tr));
3528 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3530 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3532 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3533 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3534 mt->presentation_info().PropertyChanged.connect_same_thread (*this, boost::bind (&Session::midi_track_presentation_info_changed, this, _1, boost::weak_ptr<MidiTrack>(mt)));
3538 if (!r->presentation_info().special()) {
3540 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3542 /* presentation info order may already have been set from XML */
3544 if (!r->presentation_info().order_set()) {
3545 /* this is only useful for headless sessions,
3546 * Editor::add_routes() and Mixer_UI::add_routes() will
3547 * override it following the RouteAdded signal.
3549 * Also routes should be sorted before VCAs (like the GUI does).
3550 * Session::ensure_route_presentation_info_gap() does not special case VCAs either.
3552 * ... but not to worry, the GUI's
3553 * gtk2_ardour/route_sorter.h and various ::sync_presentation_info_from_treeview()
3557 if (order == PresentationInfo::max_order) {
3558 /* just add to the end */
3559 r->set_presentation_order (n_routes + added);
3560 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3562 r->set_presentation_order (order + added);
3563 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3566 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3570 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3571 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3572 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3574 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3576 r->presentation_info().order(),
3577 enum_2_string (r->presentation_info().flags()),
3578 r->presentation_info()));
3582 if (input_auto_connect || output_auto_connect) {
3583 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3584 existing_inputs += r->n_inputs();
3585 existing_outputs += r->n_outputs();
3592 if (_monitor_out && IO::connecting_legal) {
3593 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3595 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3596 if ((*x)->is_monitor()) {
3598 } else if ((*x)->is_master()) {
3601 (*x)->enable_monitor_send ();
3606 reassign_track_numbers ();
3610 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3612 boost::shared_ptr<RouteList> r = routes.reader ();
3613 boost::shared_ptr<Send> s;
3615 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3616 if ((s = (*i)->internal_send_for (dest)) != 0) {
3617 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3623 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3625 boost::shared_ptr<RouteList> r = routes.reader ();
3626 boost::shared_ptr<Send> s;
3628 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3629 if ((s = (*i)->internal_send_for (dest)) != 0) {
3630 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3636 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3638 boost::shared_ptr<RouteList> r = routes.reader ();
3639 boost::shared_ptr<Send> s;
3641 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3642 if ((s = (*i)->internal_send_for (dest)) != 0) {
3643 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3648 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3650 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3652 boost::shared_ptr<RouteList> r = routes.reader ();
3653 boost::shared_ptr<RouteList> t (new RouteList);
3655 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3656 /* no MIDI sends because there are no MIDI busses yet */
3657 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3662 add_internal_sends (dest, p, t);
3666 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3668 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3669 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3674 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3676 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3680 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3682 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3686 if (!dest->internal_return()) {
3687 dest->add_internal_return ();
3690 sender->add_aux_send (dest, before);
3696 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3698 { // RCU Writer scope
3699 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3700 RCUWriter<RouteList> writer (routes);
3701 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3704 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3706 if (*iter == _master_out) {
3710 /* speed up session deletion, don't do the solo dance */
3711 if (0 == (_state_of_the_state & Deletion)) {
3712 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3717 /* deleting the master out seems like a dumb
3718 idea, but its more of a UI policy issue
3722 if (*iter == _master_out) {
3723 _master_out = boost::shared_ptr<Route> ();
3726 if (*iter == _monitor_out) {
3727 _monitor_out.reset ();
3730 // We need to disconnect the route's inputs and outputs
3732 (*iter)->input()->disconnect (0);
3733 (*iter)->output()->disconnect (0);
3735 /* if the route had internal sends sending to it, remove them */
3736 if ((*iter)->internal_return()) {
3738 boost::shared_ptr<RouteList> r = routes.reader ();
3739 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3740 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3742 (*i)->remove_processor (s);
3747 /* if the monitoring section had a pointer to this route, remove it */
3748 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3749 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3750 ProcessorChangeBlocker pcb (this, false);
3751 (*iter)->remove_aux_or_listen (_monitor_out);
3754 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3755 if (mt && mt->step_editing()) {
3756 if (_step_editors > 0) {
3762 /* writer goes out of scope, forces route list update */
3764 } // end of RCU Writer scope
3766 update_route_solo_state ();
3767 update_latency_compensation ();
3770 /* Re-sort routes to remove the graph's current references to the one that is
3771 * going away, then flush old references out of the graph.
3772 * Wave Tracks: reconnect routes
3775 #ifdef USE_TRACKS_CODE_FEATURES
3776 reconnect_existing_routes(true, false);
3778 routes.flush (); // maybe unsafe, see below.
3782 if (_process_graph && !(_state_of_the_state & Deletion)) {
3783 _process_graph->clear_other_chain ();
3786 /* get rid of it from the dead wood collection in the route list manager */
3787 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3791 /* try to cause everyone to drop their references
3792 * and unregister ports from the backend
3795 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3796 cerr << "Drop references to " << (*iter)->name() << endl;
3797 (*iter)->drop_references ();
3800 if (_state_of_the_state & Deletion) {
3805 so.add (Properties::selected);
3806 so.add (Properties::order);
3807 PresentationInfo::Change (PropertyChange (so));
3809 /* save the new state of the world */
3811 if (save_state (_current_snapshot_name)) {
3812 save_history (_current_snapshot_name);
3815 update_route_record_state ();
3819 Session::remove_route (boost::shared_ptr<Route> route)
3821 boost::shared_ptr<RouteList> rl (new RouteList);
3822 rl->push_back (route);
3827 Session::route_mute_changed ()
3833 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3835 boost::shared_ptr<Route> route (wpr.lock());
3841 assert (Config->get_solo_control_is_listen_control());
3843 if (route->solo_control()->soloed_by_self_or_masters()) {
3845 if (Config->get_exclusive_solo()) {
3847 RouteGroup* rg = route->route_group ();
3848 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3850 boost::shared_ptr<RouteList> r = routes.reader ();
3852 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3853 if ((*i) == route) {
3854 /* already changed */
3858 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3859 /* route does not get solo propagated to it */
3863 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3864 /* this route is a part of the same solo group as the route
3865 * that was changed. Changing that route did change or will
3866 * change all group members appropriately, so we can ignore it
3871 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3877 } else if (_listen_cnt > 0) {
3884 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3886 boost::shared_ptr<Route> route (wpr.lock());
3892 bool send_changed = false;
3894 if (route->solo_isolate_control()->solo_isolated()) {
3895 if (_solo_isolated_cnt == 0) {
3896 send_changed = true;
3898 _solo_isolated_cnt++;
3899 } else if (_solo_isolated_cnt > 0) {
3900 _solo_isolated_cnt--;
3901 if (_solo_isolated_cnt == 0) {
3902 send_changed = true;
3907 IsolatedChanged (); /* EMIT SIGNAL */
3912 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3914 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1, update\n", self_solo_changed));
3916 boost::shared_ptr<Route> route (wpr.lock());
3922 if (Config->get_solo_control_is_listen_control()) {
3923 route_listen_changed (group_override, wpr);
3927 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()));
3929 if (route->solo_control()->transitioned_into_solo() == 0) {
3930 /* route solo changed by upstream/downstream or clear all solo state; not interesting
3933 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()));
3937 boost::shared_ptr<RouteList> r = routes.reader ();
3938 int32_t delta = route->solo_control()->transitioned_into_solo ();
3940 /* the route may be a member of a group that has shared-solo
3941 * semantics. If so, then all members of that group should follow the
3942 * solo of the changed route. But ... this is optional, controlled by a
3943 * Controllable::GroupControlDisposition.
3945 * The first argument to the signal that this method is connected to is the
3946 * GroupControlDisposition value that was used to change solo.
3948 * If the solo change was done with group semantics (either InverseGroup
3949 * (force the entire group to change even if the group shared solo is
3950 * disabled) or UseGroup (use the group, which may or may not have the
3951 * shared solo property enabled)) then as we propagate the change to
3952 * the entire session we should IGNORE THE GROUP that the changed route
3956 RouteGroup* rg = route->route_group ();
3957 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3959 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate to session, group accounted for ? %1\n", group_already_accounted_for));
3961 if (delta == 1 && Config->get_exclusive_solo()) {
3963 /* new solo: disable all other solos, but not the group if its solo-enabled */
3965 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3967 if ((*i) == route) {
3968 /* already changed */
3972 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3973 /* route does not get solo propagated to it */
3977 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3978 /* this route is a part of the same solo group as the route
3979 * that was changed. Changing that route did change or will
3980 * change all group members appropriately, so we can ignore it
3986 (*i)->solo_control()->set_value (0.0, group_override);
3990 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3992 RouteList uninvolved;
3994 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3996 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3997 bool via_sends_only;
3998 bool in_signal_flow;
4000 if ((*i) == route) {
4001 /* already changed */
4005 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
4006 /* route does not get solo propagated to it */
4007 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(),
4012 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
4013 /* this route is a part of the same solo group as the route
4014 * that was changed. Changing that route did change or will
4015 * change all group members appropriately, so we can ignore it
4021 in_signal_flow = false;
4023 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
4025 if ((*i)->feeds (route, &via_sends_only)) {
4026 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
4027 if (!via_sends_only) {
4028 if (!route->soloed_by_others_upstream()) {
4029 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
4031 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
4034 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
4036 in_signal_flow = true;
4038 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
4041 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
4043 if (route->feeds (*i, &via_sends_only)) {
4044 /* propagate solo upstream only if routing other than
4045 sends is involved, but do consider the other route
4046 (*i) to be part of the signal flow even if only
4049 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
4053 route->soloed_by_others_downstream(),
4054 route->soloed_by_others_upstream()));
4055 if (!via_sends_only) {
4056 //NB. Triggers Invert Push, which handles soloed by downstream
4057 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
4058 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
4060 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
4062 in_signal_flow = true;
4064 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
4067 if (!in_signal_flow) {
4068 uninvolved.push_back (*i);
4072 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
4074 /* now notify that the mute state of the routes not involved in the signal
4075 pathway of the just-solo-changed route may have altered.
4078 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
4079 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
4080 (*i)->act_on_mute ();
4081 /* Session will emit SoloChanged() after all solo changes are
4082 * complete, which should be used by UIs to update mute status
4088 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
4090 /* now figure out if anything that matters is soloed (or is "listening")*/
4092 bool something_soloed = false;
4093 bool something_listening = false;
4094 uint32_t listeners = 0;
4095 uint32_t isolated = 0;
4098 r = routes.reader();
4101 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4102 if ((*i)->can_solo()) {
4103 if (Config->get_solo_control_is_listen_control()) {
4104 if ((*i)->solo_control()->soloed_by_self_or_masters()) {
4106 something_listening = true;
4109 (*i)->set_listen (false);
4110 if ((*i)->can_solo() && (*i)->solo_control()->soloed_by_self_or_masters()) {
4111 something_soloed = true;
4116 if ((*i)->solo_isolate_control()->solo_isolated()) {
4121 if (something_soloed != _non_soloed_outs_muted) {
4122 _non_soloed_outs_muted = something_soloed;
4123 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4126 if (something_listening != _listening) {
4127 _listening = something_listening;
4128 SoloActive (_listening);
4131 _listen_cnt = listeners;
4133 if (isolated != _solo_isolated_cnt) {
4134 _solo_isolated_cnt = isolated;
4135 IsolatedChanged (); /* EMIT SIGNAL */
4138 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4139 something_soloed, listeners, isolated));
4142 SoloChanged (); /* EMIT SIGNAL */
4147 Session::get_stripables (StripableList& sl) const
4149 boost::shared_ptr<RouteList> r = routes.reader ();
4150 sl.insert (sl.end(), r->begin(), r->end());
4152 VCAList v = _vca_manager->vcas ();
4153 sl.insert (sl.end(), v.begin(), v.end());
4156 boost::shared_ptr<RouteList>
4157 Session::get_routes_with_internal_returns() const
4159 boost::shared_ptr<RouteList> r = routes.reader ();
4160 boost::shared_ptr<RouteList> rl (new RouteList);
4162 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4163 if ((*i)->internal_return ()) {
4171 Session::io_name_is_legal (const std::string& name) const
4173 boost::shared_ptr<RouteList> r = routes.reader ();
4175 for (map<string,bool>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4176 if (name == reserved->first) {
4177 if (!route_by_name (reserved->first)) {
4178 /* first instance of a reserved name is allowed */
4181 /* all other instances of a reserved name are not allowed */
4186 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4187 if ((*i)->name() == name) {
4191 if ((*i)->has_io_processor_named (name)) {
4200 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4203 vector<string> connections;
4205 /* if we are passed only a single route and we're not told to turn
4206 * others off, then just do the simple thing.
4209 if (flip_others == false && rl->size() == 1) {
4210 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4212 mt->set_input_active (onoff);
4217 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4219 PortSet& ps ((*rt)->input()->ports());
4221 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4222 p->get_connections (connections);
4225 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4226 routes_using_input_from (*s, rl2);
4229 /* scan all relevant routes to see if others are on or off */
4231 bool others_are_already_on = false;
4233 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4235 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4241 if ((*r) != (*rt)) {
4242 if (mt->input_active()) {
4243 others_are_already_on = true;
4246 /* this one needs changing */
4247 mt->set_input_active (onoff);
4253 /* globally reverse other routes */
4255 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4256 if ((*r) != (*rt)) {
4257 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4259 mt->set_input_active (!others_are_already_on);
4268 Session::routes_using_input_from (const string& str, RouteList& rl)
4270 boost::shared_ptr<RouteList> r = routes.reader();
4272 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4273 if ((*i)->input()->connected_to (str)) {
4279 boost::shared_ptr<Route>
4280 Session::route_by_name (string name) const
4282 boost::shared_ptr<RouteList> r = routes.reader ();
4284 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4285 if ((*i)->name() == name) {
4290 return boost::shared_ptr<Route> ((Route*) 0);
4293 boost::shared_ptr<Route>
4294 Session::route_by_id (PBD::ID id) const
4296 boost::shared_ptr<RouteList> r = routes.reader ();
4298 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4299 if ((*i)->id() == id) {
4304 return boost::shared_ptr<Route> ((Route*) 0);
4307 boost::shared_ptr<Processor>
4308 Session::processor_by_id (PBD::ID id) const
4310 boost::shared_ptr<RouteList> r = routes.reader ();
4312 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4313 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4319 return boost::shared_ptr<Processor> ();
4322 boost::shared_ptr<Track>
4323 Session::track_by_diskstream_id (PBD::ID id) const
4325 boost::shared_ptr<RouteList> r = routes.reader ();
4327 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4328 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4329 if (t && t->using_diskstream_id (id)) {
4334 return boost::shared_ptr<Track> ();
4337 boost::shared_ptr<Route>
4338 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4340 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4343 boost::shared_ptr<Stripable>
4344 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4347 PresentationInfo::order_t match_cnt = 0;
4349 get_stripables (sl);
4350 sl.sort (Stripable::PresentationOrderSorter());
4352 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4354 if ((*s)->presentation_info().hidden()) {
4355 /* if the caller didn't explicitly ask for hidden
4356 stripables, ignore hidden ones. This matches
4357 the semantics of the pre-PresentationOrder
4358 "get by RID" logic of Ardour 4.x and earlier.
4360 XXX at some point we should likely reverse
4361 the logic of the flags, because asking for "the
4362 hidden stripables" is not going to be common,
4363 whereas asking for visible ones is normal.
4366 if (! (flags & PresentationInfo::Hidden)) {
4371 if ((*s)->presentation_info().flag_match (flags)) {
4372 if (match_cnt++ == n) {
4378 /* there is no nth stripable that matches the given flags */
4379 return boost::shared_ptr<Stripable>();
4382 struct PresentationOrderSorter {
4383 bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4384 if (a->presentation_info().special() && !b->presentation_info().special()) {
4385 /* a is not ordered, b is; b comes before a */
4387 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4388 /* b is not ordered, a is; a comes before b */
4391 return a->presentation_info().order() < b->presentation_info().order();
4396 boost::shared_ptr<Route>
4397 Session::route_by_selected_count (uint32_t id) const
4399 RouteList r (*(routes.reader ()));
4400 PresentationOrderSorter sorter;
4403 RouteList::iterator i;
4405 for (i = r.begin(); i != r.end(); ++i) {
4406 if ((*i)->presentation_info().selected()) {
4414 return boost::shared_ptr<Route> ();
4418 Session::reassign_track_numbers ()
4422 RouteList r (*(routes.reader ()));
4423 PresentationOrderSorter sorter;
4426 StateProtector sp (this);
4428 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4429 if (boost::dynamic_pointer_cast<Track> (*i)) {
4430 (*i)->set_track_number(++tn);
4432 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4433 (*i)->set_track_number(--bn);
4436 const uint32_t decimals = ceilf (log10f (tn + 1));
4437 const bool decimals_changed = _track_number_decimals != decimals;
4438 _track_number_decimals = decimals;
4440 if (decimals_changed && config.get_track_name_number ()) {
4441 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4442 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4444 t->resync_track_name();
4447 // trigger GUI re-layout
4448 config.ParameterChanged("track-name-number");
4452 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4453 boost::shared_ptr<RouteList> rl = routes.reader ();
4454 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4455 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4463 Session::playlist_region_added (boost::weak_ptr<Region> w)
4465 boost::shared_ptr<Region> r = w.lock ();
4470 /* These are the operations that are currently in progress... */
4471 list<GQuark> curr = _current_trans_quarks;
4474 /* ...and these are the operations during which we want to update
4475 the session range location markers.
4478 ops.push_back (Operations::capture);
4479 ops.push_back (Operations::paste);
4480 ops.push_back (Operations::duplicate_region);
4481 ops.push_back (Operations::insert_file);
4482 ops.push_back (Operations::insert_region);
4483 ops.push_back (Operations::drag_region_brush);
4484 ops.push_back (Operations::region_drag);
4485 ops.push_back (Operations::selection_grab);
4486 ops.push_back (Operations::region_fill);
4487 ops.push_back (Operations::fill_selection);
4488 ops.push_back (Operations::create_region);
4489 ops.push_back (Operations::region_copy);
4490 ops.push_back (Operations::fixed_time_region_copy);
4493 /* See if any of the current operations match the ones that we want */
4495 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4497 /* If so, update the session range markers */
4499 maybe_update_session_range (r->position (), r->last_frame ());
4503 /** Update the session range markers if a is before the current start or
4504 * b is after the current end.
4507 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4509 if (_state_of_the_state & Loading) {
4513 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4515 if (_session_range_location == 0) {
4517 set_session_range_location (a, b + session_end_marker_shift_samples);
4521 if (a < _session_range_location->start()) {
4522 _session_range_location->set_start (a);
4525 if (_session_range_end_is_free && (b > _session_range_location->end())) {
4526 _session_range_location->set_end (b);
4532 Session::set_end_is_free (bool yn)
4534 _session_range_end_is_free = yn;
4538 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4540 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4541 maybe_update_session_range (i->to, i->to + i->length);
4546 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4548 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4549 maybe_update_session_range (i->from, i->to);
4553 /* Region management */
4555 boost::shared_ptr<Region>
4556 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4558 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4559 RegionFactory::RegionMap::const_iterator i;
4560 boost::shared_ptr<Region> region;
4562 Glib::Threads::Mutex::Lock lm (region_lock);
4564 for (i = regions.begin(); i != regions.end(); ++i) {
4568 if (region->whole_file()) {
4570 if (child->source_equivalent (region)) {
4576 return boost::shared_ptr<Region> ();
4580 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4582 set<boost::shared_ptr<Region> > relevant_regions;
4584 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4585 RegionFactory::get_regions_using_source (*s, relevant_regions);
4588 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4589 set<boost::shared_ptr<Region> >::iterator tmp;
4594 playlists->destroy_region (*r);
4595 RegionFactory::map_remove (*r);
4597 (*r)->drop_sources ();
4598 (*r)->drop_references ();
4600 relevant_regions.erase (r);
4605 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4608 Glib::Threads::Mutex::Lock ls (source_lock);
4609 /* remove from the main source list */
4610 sources.erase ((*s)->id());
4613 (*s)->mark_for_remove ();
4614 (*s)->drop_references ();
4623 Session::remove_last_capture ()
4625 list<boost::shared_ptr<Source> > srcs;
4627 boost::shared_ptr<RouteList> rl = routes.reader ();
4628 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4629 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4634 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4637 srcs.insert (srcs.end(), l.begin(), l.end());
4642 destroy_sources (srcs);
4644 save_state (_current_snapshot_name);
4649 /* Source Management */
4652 Session::add_source (boost::shared_ptr<Source> source)
4654 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4655 pair<SourceMap::iterator,bool> result;
4657 entry.first = source->id();
4658 entry.second = source;
4661 Glib::Threads::Mutex::Lock lm (source_lock);
4662 result = sources.insert (entry);
4665 if (result.second) {
4667 /* yay, new source */
4669 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4672 if (!fs->within_session()) {
4673 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4679 boost::shared_ptr<AudioFileSource> afs;
4681 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4682 if (Config->get_auto_analyse_audio()) {
4683 Analyser::queue_source_for_analysis (source, false);
4687 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4692 Session::remove_source (boost::weak_ptr<Source> src)
4694 if (_state_of_the_state & Deletion) {
4698 SourceMap::iterator i;
4699 boost::shared_ptr<Source> source = src.lock();
4706 Glib::Threads::Mutex::Lock lm (source_lock);
4708 if ((i = sources.find (source->id())) != sources.end()) {
4713 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4715 /* save state so we don't end up with a session file
4716 referring to non-existent sources.
4719 save_state (_current_snapshot_name);
4723 boost::shared_ptr<Source>
4724 Session::source_by_id (const PBD::ID& id)
4726 Glib::Threads::Mutex::Lock lm (source_lock);
4727 SourceMap::iterator i;
4728 boost::shared_ptr<Source> source;
4730 if ((i = sources.find (id)) != sources.end()) {
4737 boost::shared_ptr<AudioFileSource>
4738 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4740 /* Restricted to audio files because only audio sources have channel
4744 Glib::Threads::Mutex::Lock lm (source_lock);
4746 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4747 boost::shared_ptr<AudioFileSource> afs
4748 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4750 if (afs && afs->path() == path && chn == afs->channel()) {
4755 return boost::shared_ptr<AudioFileSource>();
4758 boost::shared_ptr<MidiSource>
4759 Session::midi_source_by_path (const std::string& path) const
4761 /* Restricted to MIDI files because audio sources require a channel
4762 for unique identification, in addition to a path.
4765 Glib::Threads::Mutex::Lock lm (source_lock);
4767 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4768 boost::shared_ptr<MidiSource> ms
4769 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4770 boost::shared_ptr<FileSource> fs
4771 = boost::dynamic_pointer_cast<FileSource>(s->second);
4773 if (ms && fs && fs->path() == path) {
4778 return boost::shared_ptr<MidiSource>();
4782 Session::count_sources_by_origin (const string& path)
4785 Glib::Threads::Mutex::Lock lm (source_lock);
4787 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4788 boost::shared_ptr<FileSource> fs
4789 = boost::dynamic_pointer_cast<FileSource>(i->second);
4791 if (fs && fs->origin() == path) {
4800 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4802 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4803 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4805 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4810 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4812 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4814 if (Glib::path_is_absolute (filepath)) {
4816 /* rip the session dir from the audiofile source */
4818 string session_path;
4819 bool in_another_session = true;
4821 if (filepath.find (interchange_dir_string) != string::npos) {
4823 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4824 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4825 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4826 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4828 /* see if it is within our session */
4830 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4831 if (i->path == session_path) {
4832 in_another_session = false;
4837 in_another_session = false;
4841 if (in_another_session) {
4842 SessionDirectory sd (session_path);
4843 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4847 /* 1) if file belongs to this session
4848 * it may be a relative path (interchange/...)
4849 * or just basename (session_state, remove source)
4850 * -> just use the basename
4852 std::string filename = Glib::path_get_basename (filepath);
4855 /* 2) if the file is outside our session dir:
4856 * (imported but not copied) add the path for check-summming */
4858 path = Glib::path_get_dirname (filepath);
4861 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4865 Session::new_audio_source_path_for_embedded (const std::string& path)
4869 * we know that the filename is already unique because it exists
4870 * out in the filesystem.
4872 * However, when we bring it into the session, we could get a
4875 * Eg. two embedded files:
4880 * When merged into session, these collide.
4882 * There will not be a conflict with in-memory sources
4883 * because when the source was created we already picked
4884 * a unique name for it.
4886 * This collision is not likely to be common, but we have to guard
4887 * against it. So, if there is a collision, take the md5 hash of the
4888 * the path, and use that as the filename instead.
4891 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4892 string base = Glib::path_get_basename (path);
4893 string newpath = Glib::build_filename (sdir.sound_path(), base);
4895 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4899 md5.digestString (path.c_str());
4900 md5.writeToString ();
4901 base = md5.digestChars;
4903 string ext = get_suffix (path);
4910 newpath = Glib::build_filename (sdir.sound_path(), base);
4912 /* if this collides, we're screwed */
4914 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4915 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4924 /** Return true if there are no audio file sources that use @param name as
4925 * the filename component of their path.
4927 * Return false otherwise.
4929 * This method MUST ONLY be used to check in-session, mono files since it
4930 * hard-codes the channel of the audio file source we are looking for as zero.
4932 * If/when Ardour supports native files in non-mono formats, the logic here
4933 * will need to be revisited.
4936 Session::audio_source_name_is_unique (const string& name)
4938 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4939 vector<space_and_path>::iterator i;
4940 uint32_t existing = 0;
4942 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4944 /* note that we search *without* the extension so that
4945 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4946 in the event that this new name is required for
4947 a file format change.
4950 const string spath = *i;
4952 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4957 /* it is possible that we have the path already
4958 * assigned to a source that has not yet been written
4959 * (ie. the write source for a diskstream). we have to
4960 * check this in order to make sure that our candidate
4961 * path isn't used again, because that can lead to
4962 * two Sources point to the same file with different
4963 * notions of their removability.
4967 string possible_path = Glib::build_filename (spath, name);
4969 if (audio_source_by_path_and_channel (possible_path, 0)) {
4975 return (existing == 0);
4979 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)
4982 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4984 if (Profile->get_trx() && destructive) {
4986 sstr << setfill ('0') << setw (4) << cnt;
4987 sstr << legalized_base;
4989 sstr << legalized_base;
4991 if (take_required || related_exists) {
5003 } else if (nchan > 2) {
5008 /* XXX what? more than 26 channels! */
5019 /** Return a unique name based on \a base for a new internal audio source */
5021 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
5024 string possible_name;
5025 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
5027 bool some_related_source_name_exists = false;
5029 legalized = legalize_for_path (base);
5031 // Find a "version" of the base name that doesn't exist in any of the possible directories.
5033 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
5035 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
5037 if (audio_source_name_is_unique (possible_name)) {
5041 some_related_source_name_exists = true;
5044 error << string_compose(
5045 _("There are already %1 recordings for %2, which I consider too many."),
5046 limit, base) << endmsg;
5048 throw failed_constructor();
5052 /* We've established that the new name does not exist in any session
5053 * directory, so now find out which one we should use for this new
5057 SessionDirectory sdir (get_best_session_directory_for_new_audio());
5059 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
5064 /** Return a unique name based on `base` for a new internal MIDI source */
5066 Session::new_midi_source_path (const string& base)
5069 char buf[PATH_MAX+1];
5070 const uint32_t limit = 10000;
5072 string possible_path;
5073 string possible_name;
5076 legalized = legalize_for_path (base);
5078 // Find a "version" of the file name that doesn't exist in any of the possible directories.
5079 std::vector<string> sdirs = source_search_path(DataType::MIDI);
5081 /* - the main session folder is the first in the vector.
5082 * - after checking all locations for file-name uniqueness,
5083 * we keep the one from the last iteration as new file name
5084 * - midi files are small and should just be kept in the main session-folder
5086 * -> reverse the array, check main session folder last and use that as location
5089 std::reverse(sdirs.begin(), sdirs.end());
5091 for (cnt = 1; cnt <= limit; ++cnt) {
5093 vector<space_and_path>::iterator i;
5094 uint32_t existing = 0;
5096 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
5098 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
5099 possible_name = buf;
5101 possible_path = Glib::build_filename (*i, possible_name);
5103 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
5107 if (midi_source_by_path (possible_path)) {
5112 if (existing == 0) {
5117 error << string_compose(
5118 _("There are already %1 recordings for %2, which I consider too many."),
5119 limit, base) << endmsg;
5125 /* No need to "find best location" for software/app-based RAID, because
5126 MIDI is so small that we always put it in the same place.
5129 return possible_path;
5133 /** Create a new within-session audio source */
5134 boost::shared_ptr<AudioFileSource>
5135 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
5137 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
5139 if (!path.empty()) {
5140 return boost::dynamic_pointer_cast<AudioFileSource> (
5141 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5143 throw failed_constructor ();
5147 /** Create a new within-session MIDI source */
5148 boost::shared_ptr<MidiSource>
5149 Session::create_midi_source_for_session (string const & basic_name)
5151 const string path = new_midi_source_path (basic_name);
5153 if (!path.empty()) {
5154 return boost::dynamic_pointer_cast<SMFSource> (
5155 SourceFactory::createWritable (
5156 DataType::MIDI, *this, path, false, frame_rate()));
5158 throw failed_constructor ();
5162 /** Create a new within-session MIDI source */
5163 boost::shared_ptr<MidiSource>
5164 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5166 /* the caller passes in the track the source will be used in,
5167 so that we can keep the numbering sane.
5169 Rationale: a track with the name "Foo" that has had N
5170 captures carried out so far will ALREADY have a write source
5171 named "Foo-N+1.mid" waiting to be used for the next capture.
5173 If we call new_midi_source_name() we will get "Foo-N+2". But
5174 there is no region corresponding to "Foo-N+1", so when
5175 "Foo-N+2" appears in the track, the gap presents the user
5176 with odd behaviour - why did it skip past Foo-N+1?
5178 We could explain this to the user in some odd way, but
5179 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5182 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5185 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5187 std::string name = track->steal_write_source_name ();
5190 return boost::shared_ptr<MidiSource>();
5193 /* MIDI files are small, just put them in the first location of the
5194 session source search path.
5197 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5199 return boost::dynamic_pointer_cast<SMFSource> (
5200 SourceFactory::createWritable (
5201 DataType::MIDI, *this, path, false, frame_rate()));
5206 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5208 if (playlist->hidden()) {
5212 playlists->add (playlist);
5215 playlist->release();
5222 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5224 if (_state_of_the_state & Deletion) {
5228 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5234 playlists->remove (playlist);
5240 Session::set_audition (boost::shared_ptr<Region> r)
5242 pending_audition_region = r;
5243 add_post_transport_work (PostTransportAudition);
5244 _butler->schedule_transport_work ();
5248 Session::audition_playlist ()
5250 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5251 ev->region.reset ();
5257 Session::register_lua_function (
5258 const std::string& name,
5259 const std::string& script,
5260 const LuaScriptParamList& args
5263 Glib::Threads::Mutex::Lock lm (lua_lock);
5265 lua_State* L = lua.getState();
5267 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5268 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5269 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5270 if ((*i)->optional && !(*i)->is_set) { continue; }
5271 tbl_arg[(*i)->name] = (*i)->value;
5273 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5276 LuaScriptsChanged (); /* EMIT SIGNAL */
5281 Session::unregister_lua_function (const std::string& name)
5283 Glib::Threads::Mutex::Lock lm (lua_lock);
5284 (*_lua_del)(name); // throws luabridge::LuaException
5285 lua.collect_garbage ();
5288 LuaScriptsChanged (); /* EMIT SIGNAL */
5292 std::vector<std::string>
5293 Session::registered_lua_functions ()
5295 Glib::Threads::Mutex::Lock lm (lua_lock);
5296 std::vector<std::string> rv;
5299 luabridge::LuaRef list ((*_lua_list)());
5300 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5301 if (!i.key ().isString ()) { assert(0); continue; }
5302 rv.push_back (i.key ().cast<std::string> ());
5304 } catch (luabridge::LuaException const& e) { }
5309 static void _lua_print (std::string s) {
5310 std::cout << "SessionLua: " << s << "\n";
5315 Session::try_run_lua (pframes_t nframes)
5317 if (_n_lua_scripts == 0) return;
5318 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5320 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5321 lua.collect_garbage_step ();
5326 Session::setup_lua ()
5329 lua.Print.connect (&_lua_print);
5333 "function ArdourSession ()"
5334 " local self = { scripts = {}, instances = {} }"
5336 " local remove = function (n)"
5337 " self.scripts[n] = nil"
5338 " self.instances[n] = nil"
5339 " Session:scripts_changed()" // call back
5342 " local addinternal = function (n, f, a)"
5343 " assert(type(n) == 'string', 'function-name must be string')"
5344 " assert(type(f) == 'function', 'Given script is a not a function')"
5345 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5346 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5347 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5348 " 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"
5349 " 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 }"
5350 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5351 " Session:scripts_changed()" // call back
5354 " local add = function (n, b, a)"
5355 " assert(type(b) == 'string', 'ByteCode must be string')"
5356 " load (b)()" // assigns f
5357 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5358 " addinternal (n, load(f), a)"
5361 " local run = function (...)"
5362 " for n, s in pairs (self.instances) do"
5363 " local status, err = pcall (s, ...)"
5364 " if not status then"
5365 " print ('fn \"'.. n .. '\": ', err)"
5372 " local cleanup = function ()"
5373 " self.scripts = nil"
5374 " self.instances = nil"
5377 " local list = function ()"
5379 " for n, _ in pairs (self.scripts) do"
5385 " local function basic_serialize (o)"
5386 " if type(o) == \"number\" then"
5387 " return tostring(o)"
5389 " return string.format(\"%q\", o)"
5393 " local function serialize (name, value)"
5394 " local rv = name .. ' = '"
5396 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5397 " return rv .. basic_serialize(value) .. ' '"
5398 " elseif type(value) == \"table\" then"
5400 " for k,v in pairs(value) do"
5401 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5402 " rv = rv .. serialize(fieldname, v) .. ' '"
5403 " collectgarbage()" // string concatenation allocates a new string :(
5406 " elseif type(value) == \"function\" then"
5407 " return rv .. string.format(\"%q\", string.dump(value, true))"
5409 " error('cannot save a ' .. type(value))"
5414 " local save = function ()"
5415 " return (serialize('scripts', self.scripts))"
5418 " local restore = function (state)"
5419 " self.scripts = {}"
5421 " for n, s in pairs (scripts) do"
5422 " addinternal (n, load(s['f']), s['a'])"
5426 " return { run = run, add = add, remove = remove,"
5427 " list = list, restore = restore, save = save, cleanup = cleanup}"
5430 " sess = ArdourSession ()"
5431 " ArdourSession = nil"
5433 "function ardour () end"
5436 lua_State* L = lua.getState();
5439 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5440 lua.do_command ("sess = nil"); // hide it.
5441 lua.do_command ("collectgarbage()");
5443 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5444 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5445 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5446 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5447 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5448 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5449 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5450 } catch (luabridge::LuaException const& e) {
5451 fatal << string_compose (_("programming error: %1"),
5452 X_("Failed to setup Lua interpreter"))
5454 abort(); /*NOTREACHED*/
5457 LuaBindings::stddef (L);
5458 LuaBindings::common (L);
5459 LuaBindings::dsp (L);
5460 luabridge::push <Session *> (L, this);
5461 lua_setglobal (L, "Session");
5465 Session::scripts_changed ()
5467 assert (!lua_lock.trylock()); // must hold lua_lock
5470 luabridge::LuaRef list ((*_lua_list)());
5472 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5473 if (!i.key ().isString ()) { assert(0); continue; }
5476 _n_lua_scripts = cnt;
5477 } catch (luabridge::LuaException const& e) {
5478 fatal << string_compose (_("programming error: %1"),
5479 X_("Indexing Lua Session Scripts failed."))
5481 abort(); /*NOTREACHED*/
5486 Session::non_realtime_set_audition ()
5488 assert (pending_audition_region);
5489 auditioner->audition_region (pending_audition_region);
5490 pending_audition_region.reset ();
5491 AuditionActive (true); /* EMIT SIGNAL */
5495 Session::audition_region (boost::shared_ptr<Region> r)
5497 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5503 Session::cancel_audition ()
5508 if (auditioner->auditioning()) {
5509 auditioner->cancel_audition ();
5510 AuditionActive (false); /* EMIT SIGNAL */
5515 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5517 if (a->is_monitor()) {
5520 if (b->is_monitor()) {
5523 return a->presentation_info().order() < b->presentation_info().order();
5527 Session::is_auditioning () const
5529 /* can be called before we have an auditioner object */
5531 return auditioner->auditioning();
5538 Session::graph_reordered ()
5540 /* don't do this stuff if we are setting up connections
5541 from a set_state() call or creating new tracks. Ditto for deletion.
5544 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5548 /* every track/bus asked for this to be handled but it was deferred because
5549 we were connecting. do it now.
5552 request_input_change_handling ();
5556 /* force all diskstreams to update their capture offset values to
5557 reflect any changes in latencies within the graph.
5560 boost::shared_ptr<RouteList> rl = routes.reader ();
5561 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5562 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5564 tr->set_capture_offset ();
5569 /** @return Number of frames that there is disk space available to write,
5572 boost::optional<framecnt_t>
5573 Session::available_capture_duration ()
5575 Glib::Threads::Mutex::Lock lm (space_lock);
5577 if (_total_free_4k_blocks_uncertain) {
5578 return boost::optional<framecnt_t> ();
5581 float sample_bytes_on_disk = 4.0; // keep gcc happy
5583 switch (config.get_native_file_data_format()) {
5585 sample_bytes_on_disk = 4.0;
5589 sample_bytes_on_disk = 3.0;
5593 sample_bytes_on_disk = 2.0;
5597 /* impossible, but keep some gcc versions happy */
5598 fatal << string_compose (_("programming error: %1"),
5599 X_("illegal native file data format"))
5601 abort(); /*NOTREACHED*/
5604 double scale = 4096.0 / sample_bytes_on_disk;
5606 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5607 return max_framecnt;
5610 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5614 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5617 RCUWriter<BundleList> writer (_bundles);
5618 boost::shared_ptr<BundleList> b = writer.get_copy ();
5619 b->push_back (bundle);
5623 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5630 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5632 bool removed = false;
5635 RCUWriter<BundleList> writer (_bundles);
5636 boost::shared_ptr<BundleList> b = writer.get_copy ();
5637 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5639 if (i != b->end()) {
5646 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5652 boost::shared_ptr<Bundle>
5653 Session::bundle_by_name (string name) const
5655 boost::shared_ptr<BundleList> b = _bundles.reader ();
5657 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5658 if ((*i)->name() == name) {
5663 return boost::shared_ptr<Bundle> ();
5667 Session::tempo_map_changed (const PropertyChange&)
5671 playlists->update_after_tempo_map_change ();
5673 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5679 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5681 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5682 (*i)->recompute_frames_from_beat ();
5686 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5687 * the given count with the current block size.
5690 Session::ensure_buffers (ChanCount howmany)
5692 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5696 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5698 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5699 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5704 Session::next_insert_id ()
5706 /* this doesn't really loop forever. just think about it */
5709 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5710 if (!insert_bitset[n]) {
5711 insert_bitset[n] = true;
5717 /* none available, so resize and try again */
5719 insert_bitset.resize (insert_bitset.size() + 16, false);
5724 Session::next_send_id ()
5726 /* this doesn't really loop forever. just think about it */
5729 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5730 if (!send_bitset[n]) {
5731 send_bitset[n] = true;
5737 /* none available, so resize and try again */
5739 send_bitset.resize (send_bitset.size() + 16, false);
5744 Session::next_aux_send_id ()
5746 /* this doesn't really loop forever. just think about it */
5749 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5750 if (!aux_send_bitset[n]) {
5751 aux_send_bitset[n] = true;
5757 /* none available, so resize and try again */
5759 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5764 Session::next_return_id ()
5766 /* this doesn't really loop forever. just think about it */
5769 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5770 if (!return_bitset[n]) {
5771 return_bitset[n] = true;
5777 /* none available, so resize and try again */
5779 return_bitset.resize (return_bitset.size() + 16, false);
5784 Session::mark_send_id (uint32_t id)
5786 if (id >= send_bitset.size()) {
5787 send_bitset.resize (id+16, false);
5789 if (send_bitset[id]) {
5790 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5792 send_bitset[id] = true;
5796 Session::mark_aux_send_id (uint32_t id)
5798 if (id >= aux_send_bitset.size()) {
5799 aux_send_bitset.resize (id+16, false);
5801 if (aux_send_bitset[id]) {
5802 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5804 aux_send_bitset[id] = true;
5808 Session::mark_return_id (uint32_t id)
5810 if (id >= return_bitset.size()) {
5811 return_bitset.resize (id+16, false);
5813 if (return_bitset[id]) {
5814 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5816 return_bitset[id] = true;
5820 Session::mark_insert_id (uint32_t id)
5822 if (id >= insert_bitset.size()) {
5823 insert_bitset.resize (id+16, false);
5825 if (insert_bitset[id]) {
5826 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5828 insert_bitset[id] = true;
5832 Session::unmark_send_id (uint32_t id)
5834 if (id < send_bitset.size()) {
5835 send_bitset[id] = false;
5840 Session::unmark_aux_send_id (uint32_t id)
5842 if (id < aux_send_bitset.size()) {
5843 aux_send_bitset[id] = false;
5848 Session::unmark_return_id (uint32_t id)
5850 if (_state_of_the_state & Deletion) { return; }
5851 if (id < return_bitset.size()) {
5852 return_bitset[id] = false;
5857 Session::unmark_insert_id (uint32_t id)
5859 if (id < insert_bitset.size()) {
5860 insert_bitset[id] = false;
5865 Session::reset_native_file_format ()
5867 boost::shared_ptr<RouteList> rl = routes.reader ();
5869 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5870 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5872 /* don't save state as we do this, there's no point
5874 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5875 tr->reset_write_sources (false);
5876 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5882 Session::route_name_unique (string n) const
5884 boost::shared_ptr<RouteList> r = routes.reader ();
5886 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5887 if ((*i)->name() == n) {
5896 Session::route_name_internal (string n) const
5898 if (auditioner && auditioner->name() == n) {
5902 if (_click_io && _click_io->name() == n) {
5910 Session::freeze_all (InterThreadInfo& itt)
5912 boost::shared_ptr<RouteList> r = routes.reader ();
5914 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5916 boost::shared_ptr<Track> t;
5918 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5919 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5929 boost::shared_ptr<Region>
5930 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5931 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5932 InterThreadInfo& itt,
5933 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5934 bool for_export, bool for_freeze)
5936 boost::shared_ptr<Region> result;
5937 boost::shared_ptr<Playlist> playlist;
5938 boost::shared_ptr<Source> source;
5939 ChanCount diskstream_channels (track.n_channels());
5940 framepos_t position;
5941 framecnt_t this_chunk;
5943 framepos_t latency_skip;
5945 framepos_t len = end - start;
5946 bool need_block_size_reset = false;
5947 ChanCount const max_proc = track.max_processor_streams ();
5948 string legal_playlist_name;
5949 string possible_path;
5952 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5953 end, start) << endmsg;
5957 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5958 include_endpoint, for_export, for_freeze);
5960 if (diskstream_channels.n(track.data_type()) < 1) {
5961 error << _("Cannot write a range with no data.") << endmsg;
5965 // block all process callback handling
5967 block_processing ();
5970 // synchronize with AudioEngine::process_callback()
5971 // make sure processing is not currently running
5972 // and processing_blocked() is honored before
5973 // acquiring thread buffers
5974 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5977 _bounce_processing_active = true;
5979 /* call tree *MUST* hold route_lock */
5981 if ((playlist = track.playlist()) == 0) {
5985 legal_playlist_name = legalize_for_path (playlist->name());
5987 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5989 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5990 string path = ((track.data_type() == DataType::AUDIO)
5991 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5992 : new_midi_source_path (legal_playlist_name));
5999 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
6002 catch (failed_constructor& err) {
6003 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
6007 srcs.push_back (source);
6010 /* tell redirects that care that we are about to use a much larger
6011 * blocksize. this will flush all plugins too, so that they are ready
6012 * to be used for this process.
6015 need_block_size_reset = true;
6016 track.set_block_size (bounce_chunk_size);
6017 _engine.main_thread()->get_buffers ();
6021 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6023 /* create a set of reasonably-sized buffers */
6024 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6025 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
6027 buffers.set_count (max_proc);
6029 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6030 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6031 boost::shared_ptr<MidiSource> ms;
6033 afs->prepare_for_peakfile_writes ();
6034 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6035 Source::Lock lock(ms->mutex());
6036 ms->mark_streaming_write_started(lock);
6040 while (to_do && !itt.cancel) {
6042 this_chunk = min (to_do, bounce_chunk_size);
6044 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
6048 start += this_chunk;
6049 to_do -= this_chunk;
6050 itt.progress = (float) (1.0 - ((double) to_do / len));
6052 if (latency_skip >= bounce_chunk_size) {
6053 latency_skip -= bounce_chunk_size;
6057 const framecnt_t current_chunk = this_chunk - latency_skip;
6060 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6061 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6062 boost::shared_ptr<MidiSource> ms;
6065 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
6068 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6069 Source::Lock lock(ms->mutex());
6071 const MidiBuffer& buf = buffers.get_midi(0);
6072 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
6073 Evoral::Event<framepos_t> ev = *i;
6074 ev.set_time(ev.time() - position);
6075 ms->append_event_frames(lock, ev, ms->timeline_position());
6082 /* post-roll, pick up delayed processor output */
6083 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
6085 while (latency_skip && !itt.cancel) {
6086 this_chunk = min (latency_skip, bounce_chunk_size);
6087 latency_skip -= this_chunk;
6089 buffers.silence (this_chunk, 0);
6090 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
6093 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
6094 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6097 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
6109 xnow = localtime (&now);
6111 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
6112 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6113 boost::shared_ptr<MidiSource> ms;
6116 afs->update_header (position, *xnow, now);
6117 afs->flush_header ();
6118 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
6119 Source::Lock lock(ms->mutex());
6120 ms->mark_streaming_write_completed(lock);
6124 /* construct a region to represent the bounced material */
6128 plist.add (Properties::start, 0);
6129 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
6130 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
6132 result = RegionFactory::create (srcs, plist);
6138 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6139 (*src)->mark_for_remove ();
6140 (*src)->drop_references ();
6144 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6145 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6148 afs->done_with_peakfile_writes ();
6152 _bounce_processing_active = false;
6154 if (need_block_size_reset) {
6155 _engine.main_thread()->drop_buffers ();
6156 track.set_block_size (get_block_size());
6159 unblock_processing ();
6165 Session::gain_automation_buffer() const
6167 return ProcessThread::gain_automation_buffer ();
6171 Session::trim_automation_buffer() const
6173 return ProcessThread::trim_automation_buffer ();
6177 Session::send_gain_automation_buffer() const
6179 return ProcessThread::send_gain_automation_buffer ();
6183 Session::pan_automation_buffer() const
6185 return ProcessThread::pan_automation_buffer ();
6189 Session::get_silent_buffers (ChanCount count)
6191 return ProcessThread::get_silent_buffers (count);
6195 Session::get_scratch_buffers (ChanCount count, bool silence)
6197 return ProcessThread::get_scratch_buffers (count, silence);
6201 Session::get_noinplace_buffers (ChanCount count)
6203 return ProcessThread::get_noinplace_buffers (count);
6207 Session::get_route_buffers (ChanCount count, bool silence)
6209 return ProcessThread::get_route_buffers (count, silence);
6214 Session::get_mix_buffers (ChanCount count)
6216 return ProcessThread::get_mix_buffers (count);
6220 Session::ntracks () const
6223 boost::shared_ptr<RouteList> r = routes.reader ();
6225 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6226 if (boost::dynamic_pointer_cast<Track> (*i)) {
6235 Session::nbusses () const
6238 boost::shared_ptr<RouteList> r = routes.reader ();
6240 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6241 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6250 Session::add_automation_list(AutomationList *al)
6252 automation_lists[al->id()] = al;
6255 /** @return true if there is at least one record-enabled track, otherwise false */
6257 Session::have_rec_enabled_track () const
6259 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6263 Session::have_rec_disabled_track () const
6265 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6268 /** Update the state of our rec-enabled tracks flag */
6270 Session::update_route_record_state ()
6272 boost::shared_ptr<RouteList> rl = routes.reader ();
6273 RouteList::iterator i = rl->begin();
6274 while (i != rl->end ()) {
6276 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6277 if (tr && tr->rec_enable_control()->get_value()) {
6284 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6286 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6288 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6289 RecordStateChanged (); /* EMIT SIGNAL */
6292 for (i = rl->begin(); i != rl->end (); ++i) {
6293 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6294 if (tr && !tr->rec_enable_control()->get_value()) {
6299 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6301 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6303 if (record_status() == Recording && record_arm_state_changed ) {
6304 RecordArmStateChanged ();
6310 Session::listen_position_changed ()
6312 ProcessorChangeBlocker pcb (this);
6313 boost::shared_ptr<RouteList> r = routes.reader ();
6314 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6315 (*i)->listen_position_changed ();
6320 Session::solo_control_mode_changed ()
6322 if (soloing() || listening()) {
6324 /* We can't use ::clear_all_solo_state() here because during
6325 session loading at program startup, that will queue a call
6326 to rt_clear_all_solo_state() that will not execute until
6327 AFTER solo states have been established (thus throwing away
6328 the session's saved solo state). So just explicitly turn
6331 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6333 clear_all_solo_state (get_routes());
6338 /** Called when a property of one of our route groups changes */
6340 Session::route_group_property_changed (RouteGroup* rg)
6342 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6345 /** Called when a route is added to one of our route groups */
6347 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6349 RouteAddedToRouteGroup (rg, r);
6352 /** Called when a route is removed from one of our route groups */
6354 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6356 update_route_record_state ();
6357 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6359 if (!rg->has_control_master () && !rg->has_subgroup () && rg->empty()) {
6360 remove_route_group (*rg);
6364 boost::shared_ptr<RouteList>
6365 Session::get_tracks () const
6367 boost::shared_ptr<RouteList> rl = routes.reader ();
6368 boost::shared_ptr<RouteList> tl (new RouteList);
6370 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6371 if (boost::dynamic_pointer_cast<Track> (*r)) {
6372 if (!(*r)->is_auditioner()) {
6380 boost::shared_ptr<RouteList>
6381 Session::get_routes_with_regions_at (framepos_t const p) const
6383 boost::shared_ptr<RouteList> r = routes.reader ();
6384 boost::shared_ptr<RouteList> rl (new RouteList);
6386 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6387 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6392 boost::shared_ptr<Playlist> pl = tr->playlist ();
6397 if (pl->has_region_at (p)) {
6406 Session::goto_end ()
6408 if (_session_range_location) {
6409 request_locate (_session_range_location->end(), false);
6411 request_locate (0, false);
6416 Session::goto_start (bool and_roll)
6418 if (_session_range_location) {
6419 request_locate (_session_range_location->start(), and_roll);
6421 request_locate (0, and_roll);
6426 Session::current_start_frame () const
6428 return _session_range_location ? _session_range_location->start() : 0;
6432 Session::current_end_frame () const
6434 return _session_range_location ? _session_range_location->end() : 0;
6438 Session::set_session_range_location (framepos_t start, framepos_t end)
6440 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange, 0);
6441 _locations->add (_session_range_location);
6445 Session::step_edit_status_change (bool yn)
6451 send = (_step_editors == 0);
6456 send = (_step_editors == 1);
6459 if (_step_editors > 0) {
6465 StepEditStatusChange (val);
6471 Session::start_time_changed (framepos_t old)
6473 /* Update the auto loop range to match the session range
6474 (unless the auto loop range has been changed by the user)
6477 Location* s = _locations->session_range_location ();
6482 Location* l = _locations->auto_loop_location ();
6484 if (l && l->start() == old) {
6485 l->set_start (s->start(), true);
6491 Session::end_time_changed (framepos_t old)
6493 /* Update the auto loop range to match the session range
6494 (unless the auto loop range has been changed by the user)
6497 Location* s = _locations->session_range_location ();
6502 Location* l = _locations->auto_loop_location ();
6504 if (l && l->end() == old) {
6505 l->set_end (s->end(), true);
6510 std::vector<std::string>
6511 Session::source_search_path (DataType type) const
6515 if (session_dirs.size() == 1) {
6517 case DataType::AUDIO:
6518 sp.push_back (_session_dir->sound_path());
6520 case DataType::MIDI:
6521 sp.push_back (_session_dir->midi_path());
6525 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6526 SessionDirectory sdir (i->path);
6528 case DataType::AUDIO:
6529 sp.push_back (sdir.sound_path());
6531 case DataType::MIDI:
6532 sp.push_back (sdir.midi_path());
6538 if (type == DataType::AUDIO) {
6539 const string sound_path_2X = _session_dir->sound_path_2X();
6540 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6541 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6542 sp.push_back (sound_path_2X);
6547 // now check the explicit (possibly user-specified) search path
6550 case DataType::AUDIO:
6551 sp += Searchpath(config.get_audio_search_path ());
6553 case DataType::MIDI:
6554 sp += Searchpath(config.get_midi_search_path ());
6562 Session::ensure_search_path_includes (const string& path, DataType type)
6571 case DataType::AUDIO:
6572 sp += Searchpath(config.get_audio_search_path ());
6574 case DataType::MIDI:
6575 sp += Searchpath (config.get_midi_search_path ());
6579 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6580 /* No need to add this new directory if it has the same inode as
6581 an existing one; checking inode rather than name prevents duplicated
6582 directories when we are using symlinks.
6584 On Windows, I think we could just do if (*i == path) here.
6586 if (PBD::equivalent_paths (*i, path)) {
6594 case DataType::AUDIO:
6595 config.set_audio_search_path (sp.to_string());
6597 case DataType::MIDI:
6598 config.set_midi_search_path (sp.to_string());
6604 Session::remove_dir_from_search_path (const string& dir, DataType type)
6609 case DataType::AUDIO:
6610 sp = Searchpath(config.get_audio_search_path ());
6612 case DataType::MIDI:
6613 sp = Searchpath (config.get_midi_search_path ());
6620 case DataType::AUDIO:
6621 config.set_audio_search_path (sp.to_string());
6623 case DataType::MIDI:
6624 config.set_midi_search_path (sp.to_string());
6630 boost::shared_ptr<Speakers>
6631 Session::get_speakers()
6637 Session::unknown_processors () const
6641 boost::shared_ptr<RouteList> r = routes.reader ();
6642 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6643 list<string> t = (*i)->unknown_processors ();
6644 copy (t.begin(), t.end(), back_inserter (p));
6654 Session::update_latency (bool playback)
6657 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6659 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6663 boost::shared_ptr<RouteList> r = routes.reader ();
6664 framecnt_t max_latency = 0;
6667 /* reverse the list so that we work backwards from the last route to run to the first */
6668 RouteList* rl = routes.reader().get();
6669 r.reset (new RouteList (*rl));
6670 reverse (r->begin(), r->end());
6673 /* compute actual latency values for the given direction and store them all in per-port
6674 structures. this will also publish the same values (to JACK) so that computation of latency
6675 for routes can consistently use public latency values.
6678 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6679 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6682 /* because we latency compensate playback, our published playback latencies should
6683 be the same for all output ports - all material played back by ardour has
6684 the same latency, whether its caused by plugins or by latency compensation. since
6685 these may differ from the values computed above, reset all playback port latencies
6689 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6691 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6692 (*i)->set_public_port_latencies (max_latency, playback);
6697 post_playback_latency ();
6701 post_capture_latency ();
6704 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6708 Session::post_playback_latency ()
6710 set_worst_playback_latency ();
6712 boost::shared_ptr<RouteList> r = routes.reader ();
6714 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6715 if (!(*i)->is_auditioner() && ((*i)->active())) {
6716 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6721 (*i)->set_latency_compensation (_worst_track_latency);
6726 Session::post_capture_latency ()
6728 set_worst_capture_latency ();
6730 /* reflect any changes in capture latencies into capture offsets
6733 boost::shared_ptr<RouteList> rl = routes.reader();
6734 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6735 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6737 tr->set_capture_offset ();
6743 Session::initialize_latencies ()
6746 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6747 update_latency (false);
6748 update_latency (true);
6751 set_worst_io_latencies ();
6755 Session::set_worst_io_latencies ()
6757 set_worst_playback_latency ();
6758 set_worst_capture_latency ();
6762 Session::set_worst_playback_latency ()
6764 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6768 _worst_output_latency = 0;
6770 if (!_engine.connected()) {
6774 boost::shared_ptr<RouteList> r = routes.reader ();
6776 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6777 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6780 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6784 Session::set_worst_capture_latency ()
6786 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6790 _worst_input_latency = 0;
6792 if (!_engine.connected()) {
6796 boost::shared_ptr<RouteList> r = routes.reader ();
6798 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6799 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6802 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6806 Session::update_latency_compensation (bool force_whole_graph)
6808 bool some_track_latency_changed = false;
6810 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6814 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6816 _worst_track_latency = 0;
6818 boost::shared_ptr<RouteList> r = routes.reader ();
6820 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6821 if (!(*i)->is_auditioner() && ((*i)->active())) {
6823 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6824 some_track_latency_changed = true;
6826 _worst_track_latency = max (tl, _worst_track_latency);
6830 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6831 (some_track_latency_changed ? "yes" : "no")));
6833 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6835 if (some_track_latency_changed || force_whole_graph) {
6836 _engine.update_latencies ();
6840 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6841 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6845 tr->set_capture_offset ();
6850 Session::session_name_is_legal (const string& path)
6852 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6854 for (int i = 0; illegal_chars[i]; ++i) {
6855 if (path.find (illegal_chars[i]) != string::npos) {
6856 return illegal_chars[i];
6864 Session::notify_presentation_info_change ()
6866 if (deletion_in_progress()) {
6870 reassign_track_numbers();
6872 #ifdef USE_TRACKS_CODE_FEATURES
6873 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6874 * if track order has been changed by user
6876 reconnect_existing_routes(true, true);
6882 Session::operation_in_progress (GQuark op) const
6884 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6887 boost::shared_ptr<Port>
6888 Session::ltc_input_port () const
6890 return _ltc_input->nth (0);
6893 boost::shared_ptr<Port>
6894 Session::ltc_output_port () const
6896 return _ltc_output->nth (0);
6900 Session::reconnect_ltc_input ()
6904 string src = Config->get_ltc_source_port();
6906 _ltc_input->disconnect (this);
6908 if (src != _("None") && !src.empty()) {
6909 _ltc_input->nth (0)->connect (src);
6912 if ( ARDOUR::Profile->get_trx () ) {
6913 // Tracks need this signal to update timecode_source_dropdown
6914 MtcOrLtcInputPortChanged (); //emit signal
6920 Session::reconnect_ltc_output ()
6924 string src = Config->get_ltc_output_port();
6926 _ltc_output->disconnect (this);
6928 if (src != _("None") && !src.empty()) {
6929 _ltc_output->nth (0)->connect (src);
6935 Session::set_range_selection (framepos_t start, framepos_t end)
6937 _range_selection = Evoral::Range<framepos_t> (start, end);
6938 #ifdef USE_TRACKS_CODE_FEATURES
6939 follow_playhead_priority ();
6944 Session::set_object_selection (framepos_t start, framepos_t end)
6946 _object_selection = Evoral::Range<framepos_t> (start, end);
6947 #ifdef USE_TRACKS_CODE_FEATURES
6948 follow_playhead_priority ();
6953 Session::clear_range_selection ()
6955 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6956 #ifdef USE_TRACKS_CODE_FEATURES
6957 follow_playhead_priority ();
6962 Session::clear_object_selection ()
6964 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6965 #ifdef USE_TRACKS_CODE_FEATURES
6966 follow_playhead_priority ();
6971 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6972 const ChanCount& input_start,
6973 const ChanCount& output_start,
6974 const ChanCount& input_offset,
6975 const ChanCount& output_offset)
6977 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6978 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6979 input_start, output_start,
6980 input_offset, output_offset));
6982 auto_connect_thread_wakeup ();
6986 Session::auto_connect_thread_wakeup ()
6988 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6989 pthread_cond_signal (&_auto_connect_cond);
6990 pthread_mutex_unlock (&_auto_connect_mutex);
6995 Session::queue_latency_recompute ()
6997 g_atomic_int_inc (&_latency_recompute_pending);
6998 auto_connect_thread_wakeup ();
7002 Session::auto_connect (const AutoConnectRequest& ar)
7004 boost::shared_ptr<Route> route = ar.route.lock();
7006 if (!route) { return; }
7008 if (!IO::connecting_legal) {
7012 /* If both inputs and outputs are auto-connected to physical ports,
7013 * use the max of input and output offsets to ensure auto-connected
7014 * port numbers always match up (e.g. the first audio input and the
7015 * first audio output of the route will have the same physical
7016 * port number). Otherwise just use the lowest input or output
7020 const bool in_out_physical =
7021 (Config->get_input_auto_connect() & AutoConnectPhysical)
7022 && (Config->get_output_auto_connect() & AutoConnectPhysical)
7023 && ar.connect_inputs;
7025 const ChanCount in_offset = in_out_physical
7026 ? ChanCount::max(ar.input_offset, ar.output_offset)
7029 const ChanCount out_offset = in_out_physical
7030 ? ChanCount::max(ar.input_offset, ar.output_offset)
7033 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
7034 vector<string> physinputs;
7035 vector<string> physoutputs;
7038 /* for connecting track inputs we only want MIDI ports marked
7042 get_physical_ports (physinputs, physoutputs, *t, MidiPortMusic);
7044 if (!physinputs.empty() && ar.connect_inputs) {
7045 uint32_t nphysical_in = physinputs.size();
7047 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
7050 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
7051 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
7054 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
7060 if (!physoutputs.empty()) {
7061 uint32_t nphysical_out = physoutputs.size();
7062 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
7066 * do not create new connections if we reached the limit of physical outputs
7069 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
7070 ARDOUR::Profile->get_trx () &&
7071 ar.output_offset.get(*t) == nphysical_out ) {
7075 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
7076 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
7077 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
7078 /* master bus is audio only */
7079 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
7080 port = _master_out->input()->ports().port(*t,
7081 i % _master_out->input()->n_ports().get(*t))->name();
7085 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
7094 Session::auto_connect_thread_start ()
7096 if (g_atomic_int_get (&_ac_thread_active)) {
7100 while (!_auto_connect_queue.empty ()) {
7101 _auto_connect_queue.pop ();
7104 g_atomic_int_set (&_ac_thread_active, 1);
7105 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
7106 g_atomic_int_set (&_ac_thread_active, 0);
7111 Session::auto_connect_thread_terminate ()
7113 if (!g_atomic_int_get (&_ac_thread_active)) {
7118 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7119 while (!_auto_connect_queue.empty ()) {
7120 _auto_connect_queue.pop ();
7124 /* cannot use auto_connect_thread_wakeup() because that is allowed to
7125 * fail to wakeup the thread.
7128 pthread_mutex_lock (&_auto_connect_mutex);
7129 g_atomic_int_set (&_ac_thread_active, 0);
7130 pthread_cond_signal (&_auto_connect_cond);
7131 pthread_mutex_unlock (&_auto_connect_mutex);
7134 pthread_join (_auto_connect_thread, &status);
7138 Session::auto_connect_thread (void *arg)
7140 Session *s = static_cast<Session *>(arg);
7141 s->auto_connect_thread_run ();
7147 Session::auto_connect_thread_run ()
7149 pthread_set_name (X_("autoconnect"));
7150 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
7151 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
7152 pthread_mutex_lock (&_auto_connect_mutex);
7153 while (g_atomic_int_get (&_ac_thread_active)) {
7155 if (!_auto_connect_queue.empty ()) {
7156 // Why would we need the process lock ??
7157 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7158 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7159 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7160 // We have control over those, but what does jack do?
7161 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7163 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7164 while (!_auto_connect_queue.empty ()) {
7165 const AutoConnectRequest ar (_auto_connect_queue.front());
7166 _auto_connect_queue.pop ();
7173 if (!actively_recording ()) { // might not be needed,
7174 /* this is only used for updating plugin latencies, the
7175 * graph does not change. so it's safe in general.
7177 * .. update_latency_compensation () entails set_capture_offset()
7178 * which calls Diskstream::set_capture_offset () which
7179 * modifies the capture offset... which can be a proplem
7180 * in "prepare_to_stop"
7182 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7183 update_latency_compensation ();
7188 // this may call ARDOUR::Port::drop ... jack_port_unregister ()
7189 // jack1 cannot cope with removing ports while processing
7190 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7191 AudioEngine::instance()->clear_pending_port_deletions ();
7194 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7196 pthread_mutex_unlock (&_auto_connect_mutex);
7200 Session::cancel_all_solo ()
7204 get_stripables (sl);
7206 set_controls (stripable_list_to_control_list (sl, &Stripable::solo_control), 0.0, Controllable::NoGroup);
7207 clear_all_solo_state (routes.reader());