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/convert.h"
41 #include "pbd/error.h"
42 #include "pbd/file_utils.h"
44 #include "pbd/pthread_utils.h"
45 #include "pbd/search_path.h"
46 #include "pbd/stacktrace.h"
47 #include "pbd/stl_delete.h"
48 #include "pbd/replace_all.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/boost_debug.h"
62 #include "ardour/buffer_manager.h"
63 #include "ardour/buffer_set.h"
64 #include "ardour/bundle.h"
65 #include "ardour/butler.h"
66 #include "ardour/click.h"
67 #include "ardour/control_protocol_manager.h"
68 #include "ardour/data_type.h"
69 #include "ardour/debug.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
74 #include "ardour/filename_extensions.h"
75 #include "ardour/gain_control.h"
76 #include "ardour/graph.h"
77 #include "ardour/luabindings.h"
78 #include "ardour/midiport_manager.h"
79 #include "ardour/scene_changer.h"
80 #include "ardour/midi_patch_manager.h"
81 #include "ardour/midi_track.h"
82 #include "ardour/midi_ui.h"
83 #include "ardour/operations.h"
84 #include "ardour/playlist.h"
85 #include "ardour/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"
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)
183 , _transport_speed (0)
184 , _default_transport_speed (1.0)
185 , _last_transport_speed (0)
186 , _target_transport_speed (0.0)
187 , auto_play_legal (false)
188 , _last_slave_transport_frame (0)
189 , maximum_output_latency (0)
190 , _requested_return_frame (-1)
191 , current_block_size (0)
192 , _worst_output_latency (0)
193 , _worst_input_latency (0)
194 , _worst_track_latency (0)
195 , _have_captured (false)
196 , _non_soloed_outs_muted (false)
199 , _solo_isolated_cnt (0)
201 , _was_seamless (Config->get_seamless_loop ())
202 , _under_nsm_control (false)
204 , delta_accumulator_cnt (0)
205 , average_slave_delta (1800) // !!! why 1800 ???
207 , have_first_delta_accumulator (false)
208 , _slave_state (Stopped)
209 , _mtc_active (false)
210 , _ltc_active (false)
211 , post_export_sync (false)
212 , post_export_position (0)
214 , _export_rolling (false)
215 , _export_preroll (0)
216 , _pre_export_mmc_enabled (false)
217 , _name (snapshot_name)
219 , _send_qf_mtc (false)
220 , _pframes_since_last_mtc (0)
221 , session_midi_feedback (0)
223 , loop_changing (false)
225 , _session_dir (new SessionDirectory (fullpath))
226 , _current_snapshot_name (snapshot_name)
228 , state_was_pending (false)
229 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
231 , _save_queued (false)
232 , _last_roll_location (0)
233 , _last_roll_or_reversal_location (0)
234 , _last_record_location (0)
235 , pending_locate_roll (false)
236 , pending_locate_frame (0)
237 , pending_locate_flush (false)
238 , pending_abort (false)
239 , pending_auto_loop (false)
240 , _mempool ("Session", 2097152)
241 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
243 , _butler (new Butler (*this))
244 , _post_transport_work (0)
245 , cumulative_rf_motion (0)
247 , _locations (new Locations (*this))
248 , _ignore_skips_updates (false)
249 , _rt_thread_active (false)
250 , _rt_emit_pending (false)
251 , _ac_thread_active (false)
253 , outbound_mtc_timecode_frame (0)
254 , next_quarter_frame_to_send (-1)
255 , _frames_per_timecode_frame (0)
256 , _frames_per_hour (0)
257 , _timecode_frames_per_hour (0)
258 , last_timecode_valid (false)
259 , last_timecode_when (0)
260 , _send_timecode_update (false)
272 , ltc_timecode_offset (0)
273 , ltc_timecode_negative_offset (false)
274 , midi_control_ui (0)
276 , _all_route_group (new RouteGroup (*this, "all"))
277 , routes (new RouteList)
278 , _adding_routes_in_progress (false)
279 , _reconnecting_routes_in_progress (false)
280 , _route_deletion_in_progress (false)
281 , destructive_index (0)
282 , _latency_recompute_pending (0)
283 , _track_number_decimals(1)
284 , default_fade_steepness (0)
285 , default_fade_msecs (0)
286 , _total_free_4k_blocks (0)
287 , _total_free_4k_blocks_uncertain (false)
288 , no_questions_about_missing_files (false)
291 , _bundles (new BundleList)
292 , _bundle_xml_node (0)
296 , click_emphasis_data (0)
298 , click_emphasis_length (0)
299 , _clicks_cleared (0)
300 , _play_range (false)
301 , _range_selection (-1,-1)
302 , _object_selection (-1,-1)
304 , first_file_data_format_reset (true)
305 , first_file_header_format_reset (true)
306 , have_looped (false)
307 , _have_rec_enabled_track (false)
308 , _have_rec_disabled_track (true)
310 , _suspend_timecode_transmission (0)
311 , _speakers (new Speakers)
312 , ignore_route_processor_changes (false)
317 , _vca_manager (new VCAManager (*this))
321 created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
323 pthread_mutex_init (&_rt_emit_mutex, 0);
324 pthread_cond_init (&_rt_emit_cond, 0);
326 pthread_mutex_init (&_auto_connect_mutex, 0);
327 pthread_cond_init (&_auto_connect_cond, 0);
329 init_name_id_counter (1); // reset for new sessions, start at 1
330 VCA::set_next_vca_number (1); // reset for new sessions, start at 1
332 pre_engine_init (fullpath);
338 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
340 #ifdef USE_TRACKS_CODE_FEATURES
341 sr = EngineStateController::instance()->get_current_sample_rate();
343 if (ensure_engine (sr, true)) {
345 throw SessionException (_("Cannot connect to audio/midi engine"));
348 // set samplerate for plugins added early
349 // e.g from templates or MB channelstrip
350 set_block_size (_engine.samples_per_cycle());
351 set_frame_rate (_engine.sample_rate());
353 if (create (mix_template, bus_profile)) {
355 throw SessionException (_("Session initialization failed"));
358 /* if a mix template was provided, then ::create() will
359 * have copied it into the session and we need to load it
360 * so that we have the state ready for ::set_state()
361 * after the engine is started.
363 * Note that we do NOT try to get the sample rate from
364 * the template at this time, though doing so would
365 * be easy if we decided this was an appropriate part
369 if (!mix_template.empty()) {
370 if (load_state (_current_snapshot_name)) {
371 throw SessionException (_("Failed to load template/snapshot state"));
373 store_recent_templates (mix_template);
376 /* load default session properties - if any */
381 if (load_state (_current_snapshot_name)) {
382 throw SessionException (_("Failed to load state"));
385 /* try to get sample rate from XML state so that we
386 * can influence the SR if we set up the audio
391 XMLProperty const * prop;
392 XMLNode const * root (state_tree->root());
393 if ((prop = root->property (X_("sample-rate"))) != 0) {
394 sr = atoi (prop->value());
398 if (ensure_engine (sr, false)) {
400 throw SessionException (_("Cannot connect to audio/midi engine"));
404 if (post_engine_init ()) {
406 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
409 store_recent_sessions (_name, _path);
411 bool was_dirty = dirty();
413 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
415 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
416 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
419 DirtyChanged (); /* EMIT SIGNAL */
422 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
423 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
425 emit_thread_start ();
426 auto_connect_thread_start ();
428 /* hook us up to the engine since we are now completely constructed */
430 BootMessage (_("Connect to engine"));
432 _engine.set_session (this);
433 _engine.reset_timebase ();
435 #ifdef USE_TRACKS_CODE_FEATURES
437 EngineStateController::instance()->set_session(this);
440 if ( ARDOUR::Profile->get_trx () ) {
442 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
443 * each available input must have corresponding track when session starts.
446 uint32_t how_many (0);
448 std::vector<std::string> inputs;
449 EngineStateController::instance()->get_physical_audio_inputs(inputs);
451 how_many = inputs.size();
453 list<boost::shared_ptr<AudioTrack> > tracks;
455 // Track names after driver
456 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
457 string track_name = "";
458 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
460 track_name = inputs[i];
461 replace_all (track_name, "system:capture", "");
463 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
464 tracks.insert(tracks.begin(), single_track.front());
466 } else { // Default track names
467 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
470 if (tracks.size() != how_many) {
472 throw failed_constructor ();
481 BootMessage (_("Session loading complete"));
493 Session::next_name_id ()
495 return g_atomic_int_add (&_name_id_counter, 1);
499 Session::name_id_counter ()
501 return g_atomic_int_get (&_name_id_counter);
505 Session::init_name_id_counter (guint n)
507 g_atomic_int_set (&_name_id_counter, n);
511 Session::ensure_engine (uint32_t desired_sample_rate, bool isnew)
513 if (_engine.current_backend() == 0) {
514 /* backend is unknown ... */
515 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
516 if (r.get_value_or (-1) != 0) {
519 } else if (!isnew && _engine.running() && _engine.sample_rate () == desired_sample_rate) {
521 } else if (_engine.setup_required()) {
522 /* backend is known, but setup is needed */
523 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
524 if (r.get_value_or (-1) != 0) {
527 } else if (!_engine.running()) {
528 if (_engine.start()) {
533 /* at this point the engine should be running */
535 if (!_engine.running()) {
539 return immediately_post_engine ();
544 Session::immediately_post_engine ()
546 /* Do various initializations that should take place directly after we
547 * know that the engine is running, but before we either create a
548 * session or set state for an existing one.
551 if (how_many_dsp_threads () > 1) {
552 /* For now, only create the graph if we are using >1 DSP threads, as
553 it is a bit slower than the old code with 1 thread.
555 _process_graph.reset (new Graph (*this));
558 /* every time we reconnect, recompute worst case output latencies */
560 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
562 if (synced_to_engine()) {
563 _engine.transport_stop ();
566 if (config.get_jack_time_master()) {
567 _engine.transport_locate (_transport_frame);
572 BootMessage (_("Set up LTC"));
574 BootMessage (_("Set up Click"));
576 BootMessage (_("Set up standard connections"));
580 catch (failed_constructor& err) {
584 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
586 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
594 vector<void*> debug_pointers;
596 /* if we got to here, leaving pending capture state around
600 remove_pending_capture_state ();
604 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
606 /* stop autoconnecting */
607 auto_connect_thread_terminate ();
609 /* disconnect from any and all signals that we are connected to */
611 Port::PortSignalDrop (); /* EMIT SIGNAL */
614 /* shutdown control surface protocols while we still have ports
615 and the engine to move data to any devices.
618 ControlProtocolManager::instance().drop_protocols ();
620 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
622 _engine.remove_session ();
624 #ifdef USE_TRACKS_CODE_FEATURES
625 EngineStateController::instance()->remove_session();
628 /* deregister all ports - there will be no process or any other
629 * callbacks from the engine any more.
632 Port::PortDrop (); /* EMIT SIGNAL */
636 /* clear history so that no references to objects are held any more */
640 /* clear state tree so that no references to objects are held any more */
645 // unregister all lua functions, drop held references (if any)
647 lua.do_command ("Session = nil");
655 lua.collect_garbage ();
657 /* reset dynamic state version back to default */
658 Stateful::loading_state_version = 0;
660 _butler->drop_references ();
664 delete _all_route_group;
666 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
667 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
671 if (click_data != default_click) {
672 delete [] click_data;
675 if (click_emphasis_data != default_click_emphasis) {
676 delete [] click_emphasis_data;
681 /* need to remove auditioner before monitoring section
682 * otherwise it is re-connected */
685 /* drop references to routes held by the monitoring section
686 * specifically _monitor_out aux/listen references */
687 remove_monitor_section();
689 /* clear out any pending dead wood from RCU managed objects */
694 AudioDiskstream::free_working_buffers();
696 /* tell everyone who is still standing that we're about to die */
699 /* tell everyone to drop references and delete objects as we go */
701 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
702 RegionFactory::delete_all_regions ();
704 /* Do this early so that VCAs no longer hold references to routes */
706 DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
709 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
711 /* reset these three references to special routes before we do the usual route delete thing */
713 _master_out.reset ();
714 _monitor_out.reset ();
717 RCUWriter<RouteList> writer (routes);
718 boost::shared_ptr<RouteList> r = writer.get_copy ();
720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
721 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
722 (*i)->drop_references ();
726 /* writer goes out of scope and updates master */
731 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
732 Glib::Threads::Mutex::Lock lm (source_lock);
733 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
734 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
735 i->second->drop_references ();
741 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
744 emit_thread_terminate ();
746 pthread_cond_destroy (&_rt_emit_cond);
747 pthread_mutex_destroy (&_rt_emit_mutex);
749 pthread_cond_destroy (&_auto_connect_cond);
750 pthread_mutex_destroy (&_auto_connect_mutex);
752 delete _scene_changer; _scene_changer = 0;
753 delete midi_control_ui; midi_control_ui = 0;
755 delete _mmc; _mmc = 0;
756 delete _midi_ports; _midi_ports = 0;
757 delete _locations; _locations = 0;
762 /* clear event queue, the session is gone, nobody is interested in
763 * those anymore, but they do leak memory if not removed
765 while (!immediate_events.empty ()) {
766 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
767 SessionEvent *ev = immediate_events.front ();
768 DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
769 immediate_events.pop_front ();
773 case SessionEvent::AutoLoop:
774 case SessionEvent::AutoLoopDeclick:
775 case SessionEvent::Skip:
776 case SessionEvent::PunchIn:
777 case SessionEvent::PunchOut:
778 case SessionEvent::StopOnce:
779 case SessionEvent::RangeStop:
780 case SessionEvent::RangeLocate:
784 case SessionEvent::RealTimeOperation:
791 del = del && !_remove_event (ev);
798 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
800 BOOST_SHOW_POINTERS ();
804 Session::setup_ltc ()
808 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
809 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
811 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
812 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
815 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
816 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
818 reconnect_ltc_input ();
821 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
822 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
825 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
826 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
828 reconnect_ltc_output ();
831 /* fix up names of LTC ports because we don't want the normal
832 * IO style of NAME/TYPE-{in,out}N
835 _ltc_input->nth (0)->set_name (X_("LTC-in"));
836 _ltc_output->nth (0)->set_name (X_("LTC-out"));
840 Session::setup_click ()
844 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
845 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
847 _click_io.reset (new ClickIO (*this, X_("Click")));
848 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
849 _click_gain->activate ();
851 setup_click_state (state_tree->root());
853 setup_click_state (0);
858 Session::setup_click_state (const XMLNode* node)
860 const XMLNode* child = 0;
862 if (node && (child = find_named_node (*node, "Click")) != 0) {
864 /* existing state for Click */
867 if (Stateful::loading_state_version < 3000) {
868 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
870 const XMLNodeList& children (child->children());
871 XMLNodeList::const_iterator i = children.begin();
872 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
874 if (i != children.end()) {
875 c = _click_gain->set_state (**i, Stateful::loading_state_version);
881 _clicking = Config->get_clicking ();
885 error << _("could not setup Click I/O") << endmsg;
892 /* default state for Click: dual-mono to first 2 physical outputs */
895 _engine.get_physical_outputs (DataType::AUDIO, outs);
897 for (uint32_t physport = 0; physport < 2; ++physport) {
898 if (outs.size() > physport) {
899 if (_click_io->add_port (outs[physport], this)) {
900 // relax, even though its an error
905 if (_click_io->n_ports () > ChanCount::ZERO) {
906 _clicking = Config->get_clicking ();
912 Session::setup_bundles ()
916 RCUWriter<BundleList> writer (_bundles);
917 boost::shared_ptr<BundleList> b = writer.get_copy ();
918 for (BundleList::iterator i = b->begin(); i != b->end();) {
919 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
927 vector<string> inputs[DataType::num_types];
928 vector<string> outputs[DataType::num_types];
929 for (uint32_t i = 0; i < DataType::num_types; ++i) {
930 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
931 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
934 /* Create a set of Bundle objects that map
935 to the physical I/O currently available. We create both
936 mono and stereo bundles, so that the common cases of mono
937 and stereo tracks get bundles to put in their mixer strip
938 in / out menus. There may be a nicer way of achieving that;
939 it doesn't really scale that well to higher channel counts
942 /* mono output bundles */
944 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
946 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
948 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
950 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
953 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
954 c->add_channel (_("mono"), DataType::AUDIO);
955 c->set_port (0, outputs[DataType::AUDIO][np]);
957 add_bundle (c, false);
960 /* stereo output bundles */
962 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
963 if (np + 1 < outputs[DataType::AUDIO].size()) {
965 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
966 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
967 c->add_channel (_("L"), DataType::AUDIO);
968 c->set_port (0, outputs[DataType::AUDIO][np]);
969 c->add_channel (_("R"), DataType::AUDIO);
970 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
972 add_bundle (c, false);
976 /* mono input bundles */
978 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
980 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
982 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
984 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
987 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
988 c->add_channel (_("mono"), DataType::AUDIO);
989 c->set_port (0, inputs[DataType::AUDIO][np]);
991 add_bundle (c, false);
994 /* stereo input bundles */
996 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
997 if (np + 1 < inputs[DataType::AUDIO].size()) {
999 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
1001 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
1002 c->add_channel (_("L"), DataType::AUDIO);
1003 c->set_port (0, inputs[DataType::AUDIO][np]);
1004 c->add_channel (_("R"), DataType::AUDIO);
1005 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
1007 add_bundle (c, false);
1011 /* MIDI input bundles */
1013 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
1014 string n = inputs[DataType::MIDI][np];
1015 std::string pn = _engine.get_pretty_name_by_name (n);
1019 boost::erase_first (n, X_("alsa_pcm:"));
1021 boost::shared_ptr<Bundle> c (new Bundle (n, false));
1022 c->add_channel ("", DataType::MIDI);
1023 c->set_port (0, inputs[DataType::MIDI][np]);
1024 add_bundle (c, false);
1027 /* MIDI output bundles */
1029 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
1030 string n = outputs[DataType::MIDI][np];
1031 std::string pn = _engine.get_pretty_name_by_name (n);
1035 boost::erase_first (n, X_("alsa_pcm:"));
1037 boost::shared_ptr<Bundle> c (new Bundle (n, true));
1038 c->add_channel ("", DataType::MIDI);
1039 c->set_port (0, outputs[DataType::MIDI][np]);
1040 add_bundle (c, false);
1043 // we trust the backend to only calls us if there's a change
1044 BundleAddedOrRemoved (); /* EMIT SIGNAL */
1048 Session::auto_connect_master_bus ()
1050 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1054 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1055 // In this case it means "Multi Out" output mode
1056 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1060 /* if requested auto-connect the outputs to the first N physical ports.
1063 uint32_t limit = _master_out->n_outputs().n_total();
1064 vector<string> outputs[DataType::num_types];
1066 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1067 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1070 for (uint32_t n = 0; n < limit; ++n) {
1071 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1073 if (outputs[p->type()].size() > n) {
1074 connect_to = outputs[p->type()][n];
1077 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1078 if (_master_out->output()->connect (p, connect_to, this)) {
1079 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1088 Session::remove_monitor_section ()
1090 if (!_monitor_out || Profile->get_trx()) {
1094 /* force reversion to Solo-In-Place */
1095 Config->set_solo_control_is_listen_control (false);
1097 /* if we are auditioning, cancel it ... this is a workaround
1098 to a problem (auditioning does not execute the process graph,
1099 which is needed to remove routes when using >1 core for processing)
1104 /* Hold process lock while doing this so that we don't hear bits and
1105 * pieces of audio as we work on each route.
1108 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1110 /* Connect tracks to monitor section. Note that in an
1111 existing session, the internal sends will already exist, but we want the
1112 routes to notice that they connect to the control out specifically.
1116 boost::shared_ptr<RouteList> r = routes.reader ();
1117 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1119 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1121 if ((*x)->is_monitor()) {
1123 } else if ((*x)->is_master()) {
1126 (*x)->remove_aux_or_listen (_monitor_out);
1131 remove_route (_monitor_out);
1132 if (_state_of_the_state & Deletion) {
1136 auto_connect_master_bus ();
1139 auditioner->connect ();
1142 Config->ParameterChanged ("use-monitor-bus");
1146 Session::add_monitor_section ()
1150 if (_monitor_out || !_master_out || Profile->get_trx()) {
1154 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), PresentationInfo::MonitorOut, DataType::AUDIO));
1160 BOOST_MARK_ROUTE(r);
1163 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1164 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1165 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1167 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1172 add_routes (rl, false, false, false, 0);
1174 assert (_monitor_out);
1176 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1177 are undefined, at best.
1180 uint32_t limit = _monitor_out->n_inputs().n_audio();
1184 /* connect the inputs to the master bus outputs. this
1185 * represents a separate data feed from the internal sends from
1186 * each route. as of jan 2011, it allows the monitor section to
1187 * conditionally ignore either the internal sends or the normal
1188 * input feed, but we should really find a better way to do
1192 _master_out->output()->disconnect (this);
1194 for (uint32_t n = 0; n < limit; ++n) {
1195 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1196 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1199 string connect_to = o->name();
1200 if (_monitor_out->input()->connect (p, connect_to, this)) {
1201 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1209 /* if monitor section is not connected, connect it to physical outs
1212 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1214 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1216 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1219 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1221 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1222 Config->get_monitor_bus_preferred_bundle())
1228 /* Monitor bus is audio only */
1230 vector<string> outputs[DataType::num_types];
1232 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1233 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1236 uint32_t mod = outputs[DataType::AUDIO].size();
1237 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1241 for (uint32_t n = 0; n < limit; ++n) {
1243 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1245 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1246 connect_to = outputs[DataType::AUDIO][n % mod];
1249 if (!connect_to.empty()) {
1250 if (_monitor_out->output()->connect (p, connect_to, this)) {
1251 error << string_compose (
1252 _("cannot connect control output %1 to %2"),
1263 /* Hold process lock while doing this so that we don't hear bits and
1264 * pieces of audio as we work on each route.
1267 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1269 /* Connect tracks to monitor section. Note that in an
1270 existing session, the internal sends will already exist, but we want the
1271 routes to notice that they connect to the control out specifically.
1275 boost::shared_ptr<RouteList> rls = routes.reader ();
1277 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1279 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1281 if ((*x)->is_monitor()) {
1283 } else if ((*x)->is_master()) {
1286 (*x)->enable_monitor_send ();
1291 auditioner->connect ();
1293 Config->ParameterChanged ("use-monitor-bus");
1297 Session::reset_monitor_section ()
1299 /* Process lock should be held by the caller.*/
1301 if (!_monitor_out || Profile->get_trx()) {
1305 uint32_t limit = _master_out->n_outputs().n_audio();
1307 /* connect the inputs to the master bus outputs. this
1308 * represents a separate data feed from the internal sends from
1309 * each route. as of jan 2011, it allows the monitor section to
1310 * conditionally ignore either the internal sends or the normal
1311 * input feed, but we should really find a better way to do
1315 _master_out->output()->disconnect (this);
1316 _monitor_out->output()->disconnect (this);
1318 // monitor section follow master bus - except midi
1319 ChanCount mon_chn (_master_out->output()->n_ports());
1320 mon_chn.set_midi (0);
1322 _monitor_out->input()->ensure_io (mon_chn, false, this);
1323 _monitor_out->output()->ensure_io (mon_chn, false, this);
1325 for (uint32_t n = 0; n < limit; ++n) {
1326 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1327 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1330 string connect_to = o->name();
1331 if (_monitor_out->input()->connect (p, connect_to, this)) {
1332 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1339 /* connect monitor section to physical outs
1342 if (Config->get_auto_connect_standard_busses()) {
1344 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1346 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1349 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1351 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1352 Config->get_monitor_bus_preferred_bundle())
1358 /* Monitor bus is audio only */
1360 vector<string> outputs[DataType::num_types];
1362 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1363 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1366 uint32_t mod = outputs[DataType::AUDIO].size();
1367 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1371 for (uint32_t n = 0; n < limit; ++n) {
1373 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1375 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1376 connect_to = outputs[DataType::AUDIO][n % mod];
1379 if (!connect_to.empty()) {
1380 if (_monitor_out->output()->connect (p, connect_to, this)) {
1381 error << string_compose (
1382 _("cannot connect control output %1 to %2"),
1393 /* Connect tracks to monitor section. Note that in an
1394 existing session, the internal sends will already exist, but we want the
1395 routes to notice that they connect to the control out specifically.
1399 boost::shared_ptr<RouteList> rls = routes.reader ();
1401 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1403 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1405 if ((*x)->is_monitor()) {
1407 } else if ((*x)->is_master()) {
1410 (*x)->enable_monitor_send ();
1416 Session::hookup_io ()
1418 /* stop graph reordering notifications from
1419 causing resorts, etc.
1422 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1426 /* we delay creating the auditioner till now because
1427 it makes its own connections to ports.
1431 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1433 throw failed_constructor ();
1435 a->use_new_diskstream ();
1439 catch (failed_constructor& err) {
1440 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1444 /* load bundles, which we may have postponed earlier on */
1445 if (_bundle_xml_node) {
1446 load_bundles (*_bundle_xml_node);
1447 delete _bundle_xml_node;
1450 /* Tell all IO objects to connect themselves together */
1452 IO::enable_connecting ();
1454 /* Now tell all "floating" ports to connect to whatever
1455 they should be connected to.
1458 AudioEngine::instance()->reconnect_ports ();
1460 /* Anyone who cares about input state, wake up and do something */
1462 IOConnectionsComplete (); /* EMIT SIGNAL */
1464 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1466 /* now handle the whole enchilada as if it was one
1467 graph reorder event.
1472 /* update the full solo state, which can't be
1473 correctly determined on a per-route basis, but
1474 needs the global overview that only the session
1478 update_route_solo_state ();
1482 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1484 boost::shared_ptr<Track> track = wp.lock ();
1489 boost::shared_ptr<Playlist> playlist;
1491 if ((playlist = track->playlist()) != 0) {
1492 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1493 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1494 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1499 Session::record_enabling_legal () const
1501 /* this used to be in here, but survey says.... we don't need to restrict it */
1502 // if (record_status() == Recording) {
1506 if (Config->get_all_safe()) {
1513 Session::set_track_monitor_input_status (bool yn)
1515 boost::shared_ptr<RouteList> rl = routes.reader ();
1516 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1517 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1518 if (tr && tr->rec_enable_control()->get_value()) {
1519 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1520 tr->request_input_monitoring (yn);
1526 Session::auto_punch_start_changed (Location* location)
1528 replace_event (SessionEvent::PunchIn, location->start());
1530 if (get_record_enabled() && config.get_punch_in()) {
1531 /* capture start has been changed, so save new pending state */
1532 save_state ("", true);
1537 Session::auto_punch_end_changed (Location* location)
1539 framepos_t when_to_stop = location->end();
1540 // when_to_stop += _worst_output_latency + _worst_input_latency;
1541 replace_event (SessionEvent::PunchOut, when_to_stop);
1545 Session::auto_punch_changed (Location* location)
1547 framepos_t when_to_stop = location->end();
1549 replace_event (SessionEvent::PunchIn, location->start());
1550 //when_to_stop += _worst_output_latency + _worst_input_latency;
1551 replace_event (SessionEvent::PunchOut, when_to_stop);
1554 /** @param loc A loop location.
1555 * @param pos Filled in with the start time of the required fade-out (in session frames).
1556 * @param length Filled in with the length of the required fade-out.
1559 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1561 pos = max (loc->start(), loc->end() - 64);
1562 length = loc->end() - pos;
1566 Session::auto_loop_changed (Location* location)
1568 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1571 auto_loop_declick_range (location, dcp, dcl);
1573 if (transport_rolling() && play_loop) {
1575 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1577 // if (_transport_frame > location->end()) {
1579 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1580 // relocate to beginning of loop
1581 clear_events (SessionEvent::LocateRoll);
1583 request_locate (location->start(), true);
1586 else if (Config->get_seamless_loop() && !loop_changing) {
1588 // schedule a locate-roll to refill the diskstreams at the
1589 // previous loop end
1590 loop_changing = true;
1592 if (location->end() > last_loopend) {
1593 clear_events (SessionEvent::LocateRoll);
1594 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1600 clear_events (SessionEvent::AutoLoopDeclick);
1601 clear_events (SessionEvent::AutoLoop);
1604 /* possibly move playhead if not rolling; if we are rolling we'll move
1605 to the loop start on stop if that is appropriate.
1610 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1611 if (pos == location->start()) {
1612 request_locate (pos);
1617 last_loopend = location->end();
1622 Session::set_auto_punch_location (Location* location)
1626 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1627 punch_connections.drop_connections();
1628 existing->set_auto_punch (false, this);
1629 remove_event (existing->start(), SessionEvent::PunchIn);
1630 clear_events (SessionEvent::PunchOut);
1631 auto_punch_location_changed (0);
1636 if (location == 0) {
1640 if (location->end() <= location->start()) {
1641 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1645 punch_connections.drop_connections ();
1647 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1648 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1649 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1651 location->set_auto_punch (true, this);
1653 auto_punch_changed (location);
1655 auto_punch_location_changed (location);
1659 Session::set_session_extents (framepos_t start, framepos_t end)
1662 if ((existing = _locations->session_range_location()) == 0) {
1663 //if there is no existing session, we need to make a new session location (should never happen)
1664 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1668 error << _("Session: you can't use that location for session start/end)") << endmsg;
1672 existing->set( start, end );
1678 Session::set_auto_loop_location (Location* location)
1682 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1683 loop_connections.drop_connections ();
1684 existing->set_auto_loop (false, this);
1685 remove_event (existing->end(), SessionEvent::AutoLoop);
1688 auto_loop_declick_range (existing, dcp, dcl);
1689 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1690 auto_loop_location_changed (0);
1695 if (location == 0) {
1699 if (location->end() <= location->start()) {
1700 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1704 last_loopend = location->end();
1706 loop_connections.drop_connections ();
1708 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1709 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1710 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1711 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1713 location->set_auto_loop (true, this);
1715 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1716 // set all tracks to use internal looping
1717 boost::shared_ptr<RouteList> rl = routes.reader ();
1718 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1719 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1720 if (tr && !tr->hidden()) {
1721 tr->set_loop (location);
1726 /* take care of our stuff first */
1728 auto_loop_changed (location);
1730 /* now tell everyone else */
1732 auto_loop_location_changed (location);
1736 Session::update_marks (Location*)
1742 Session::update_skips (Location* loc, bool consolidate)
1744 if (_ignore_skips_updates) {
1748 Locations::LocationList skips;
1751 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1752 consolidate_skips (loc);
1755 sync_locations_to_skips ();
1761 Session::consolidate_skips (Location* loc)
1763 Locations::LocationList all_locations = _locations->list ();
1765 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1767 if (!(*l)->is_skip ()) {
1772 /* don't test against self */
1779 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1780 case Evoral::OverlapInternal:
1781 case Evoral::OverlapExternal:
1782 case Evoral::OverlapStart:
1783 case Evoral::OverlapEnd:
1784 /* adjust new location to cover existing one */
1785 loc->set_start (min (loc->start(), (*l)->start()));
1786 loc->set_end (max (loc->end(), (*l)->end()));
1787 /* we don't need this one any more */
1788 _locations->remove (*l);
1789 /* the location has been deleted, so remove reference to it in our local list */
1790 l = all_locations.erase (l);
1793 case Evoral::OverlapNone:
1801 Session::sync_locations_to_skips ()
1803 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1804 * Session::_sync_locations_to_skips() from the audioengine thread.
1806 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1810 Session::_sync_locations_to_skips ()
1812 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1814 Locations::LocationList const & locs (_locations->list());
1816 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1818 Location* location = *i;
1820 if (location->is_skip() && location->is_skipping()) {
1821 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1829 Session::location_added (Location *location)
1831 if (location->is_auto_punch()) {
1832 set_auto_punch_location (location);
1835 if (location->is_auto_loop()) {
1836 set_auto_loop_location (location);
1839 if (location->is_session_range()) {
1840 /* no need for any signal handling or event setting with the session range,
1841 because we keep a direct reference to it and use its start/end directly.
1843 _session_range_location = location;
1846 if (location->is_mark()) {
1847 /* listen for per-location signals that require us to do any * global updates for marks */
1849 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1850 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1851 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1852 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1855 if (location->is_skip()) {
1856 /* listen for per-location signals that require us to update skip-locate events */
1858 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1859 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1860 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1861 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1863 update_skips (location, true);
1870 Session::location_removed (Location *location)
1872 if (location->is_auto_loop()) {
1873 set_auto_loop_location (0);
1874 set_track_loop (false);
1877 if (location->is_auto_punch()) {
1878 set_auto_punch_location (0);
1881 if (location->is_session_range()) {
1882 /* this is never supposed to happen */
1883 error << _("programming error: session range removed!") << endl;
1886 if (location->is_skip()) {
1888 update_skips (location, false);
1895 Session::locations_changed ()
1897 _locations->apply (*this, &Session::_locations_changed);
1901 Session::_locations_changed (const Locations::LocationList& locations)
1903 /* There was some mass-change in the Locations object.
1905 We might be re-adding a location here but it doesn't actually matter
1906 for all the locations that the Session takes an interest in.
1910 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1911 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1912 location_added (*i);
1916 update_skips (NULL, false);
1920 Session::enable_record ()
1922 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1923 /* no recording at anything except normal speed */
1928 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1930 if (rs == Recording) {
1934 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1936 _last_record_location = _transport_frame;
1937 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1939 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1940 set_track_monitor_input_status (true);
1943 RecordStateChanged ();
1950 Session::set_all_tracks_record_enabled (bool enable )
1952 boost::shared_ptr<RouteList> rl = routes.reader();
1953 set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), enable, Controllable::NoGroup);
1957 Session::disable_record (bool rt_context, bool force)
1961 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1963 if (!Config->get_latched_record_enable () || force) {
1964 g_atomic_int_set (&_record_status, Disabled);
1965 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1967 if (rs == Recording) {
1968 g_atomic_int_set (&_record_status, Enabled);
1972 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1973 set_track_monitor_input_status (false);
1976 RecordStateChanged (); /* emit signal */
1979 remove_pending_capture_state ();
1985 Session::step_back_from_record ()
1987 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1989 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1990 set_track_monitor_input_status (false);
1993 RecordStateChanged (); /* emit signal */
1998 Session::maybe_enable_record ()
2000 if (_step_editors > 0) {
2004 g_atomic_int_set (&_record_status, Enabled);
2006 /* This function is currently called from somewhere other than an RT thread.
2007 This save_state() call therefore doesn't impact anything. Doing it here
2008 means that we save pending state of which sources the next record will use,
2009 which gives us some chance of recovering from a crash during the record.
2012 save_state ("", true);
2014 if (_transport_speed) {
2015 if (!config.get_punch_in()) {
2019 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
2020 RecordStateChanged (); /* EMIT SIGNAL */
2027 Session::audible_frame () const
2033 offset = worst_playback_latency ();
2035 if (synced_to_engine()) {
2036 /* Note: this is basically just sync-to-JACK */
2037 tf = _engine.transport_frame();
2039 tf = _transport_frame;
2044 if (!non_realtime_work_pending()) {
2048 /* Check to see if we have passed the first guaranteed
2049 audible frame past our last start position. if not,
2050 return that last start point because in terms
2051 of audible frames, we have not moved yet.
2053 `Start position' in this context means the time we last
2054 either started, located, or changed transport direction.
2057 if (_transport_speed > 0.0f) {
2059 if (!play_loop || !have_looped) {
2060 if (tf < _last_roll_or_reversal_location + offset) {
2061 return _last_roll_or_reversal_location;
2069 } else if (_transport_speed < 0.0f) {
2071 /* XXX wot? no backward looping? */
2073 if (tf > _last_roll_or_reversal_location - offset) {
2074 return _last_roll_or_reversal_location;
2086 Session::set_frame_rate (framecnt_t frames_per_second)
2088 /** \fn void Session::set_frame_size(framecnt_t)
2089 the AudioEngine object that calls this guarantees
2090 that it will not be called while we are also in
2091 ::process(). Its fine to do things that block
2095 if (_base_frame_rate == 0) {
2096 _base_frame_rate = frames_per_second;
2098 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2099 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2101 _nominal_frame_rate = frames_per_second;
2106 reset_write_sources (false);
2108 // XXX we need some equivalent to this, somehow
2109 // SndFileSource::setup_standard_crossfades (frames_per_second);
2113 /* XXX need to reset/reinstantiate all LADSPA plugins */
2117 Session::set_block_size (pframes_t nframes)
2119 /* the AudioEngine guarantees
2120 that it will not be called while we are also in
2121 ::process(). It is therefore fine to do things that block
2126 current_block_size = nframes;
2130 boost::shared_ptr<RouteList> r = routes.reader ();
2132 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2133 (*i)->set_block_size (nframes);
2136 boost::shared_ptr<RouteList> rl = routes.reader ();
2137 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2138 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2140 tr->set_block_size (nframes);
2144 set_worst_io_latencies ();
2150 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2152 boost::shared_ptr<Route> r2;
2154 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2155 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2159 /* make a copy of the existing list of routes that feed r1 */
2161 Route::FedBy existing (r1->fed_by());
2163 /* for each route that feeds r1, recurse, marking it as feeding
2167 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2168 if (!(r2 = i->r.lock ())) {
2169 /* (*i) went away, ignore it */
2173 /* r2 is a route that feeds r1 which somehow feeds base. mark
2174 base as being fed by r2
2177 rbase->add_fed_by (r2, i->sends_only);
2181 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2185 if (r1->feeds (r2) && r2->feeds (r1)) {
2189 /* now recurse, so that we can mark base as being fed by
2190 all routes that feed r2
2193 trace_terminal (r2, rbase);
2200 Session::resort_routes ()
2202 /* don't do anything here with signals emitted
2203 by Routes during initial setup or while we
2204 are being destroyed.
2207 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2211 if (_route_deletion_in_progress) {
2216 RCUWriter<RouteList> writer (routes);
2217 boost::shared_ptr<RouteList> r = writer.get_copy ();
2218 resort_routes_using (r);
2219 /* writer goes out of scope and forces update */
2223 if (DEBUG_ENABLED(DEBUG::Graph)) {
2224 boost::shared_ptr<RouteList> rl = routes.reader ();
2225 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2226 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2228 const Route::FedBy& fb ((*i)->fed_by());
2230 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2231 boost::shared_ptr<Route> sf = f->r.lock();
2233 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2242 /** This is called whenever we need to rebuild the graph of how we will process
2244 * @param r List of routes, in any order.
2248 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2250 /* We are going to build a directed graph of our routes;
2251 this is where the edges of that graph are put.
2256 /* Go through all routes doing two things:
2258 * 1. Collect the edges of the route graph. Each of these edges
2259 * is a pair of routes, one of which directly feeds the other
2260 * either by a JACK connection or by an internal send.
2262 * 2. Begin the process of making routes aware of which other
2263 * routes directly or indirectly feed them. This information
2264 * is used by the solo code.
2267 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2269 /* Clear out the route's list of direct or indirect feeds */
2270 (*i)->clear_fed_by ();
2272 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2274 bool via_sends_only;
2276 /* See if this *j feeds *i according to the current state of the JACK
2277 connections and internal sends.
2279 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2280 /* add the edge to the graph (part #1) */
2281 edges.add (*j, *i, via_sends_only);
2282 /* tell the route (for part #2) */
2283 (*i)->add_fed_by (*j, via_sends_only);
2288 /* Attempt a topological sort of the route graph */
2289 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2291 if (sorted_routes) {
2292 /* We got a satisfactory topological sort, so there is no feedback;
2295 Note: the process graph rechain does not require a
2296 topologically-sorted list, but hey ho.
2298 if (_process_graph) {
2299 _process_graph->rechain (sorted_routes, edges);
2302 _current_route_graph = edges;
2304 /* Complete the building of the routes' lists of what directly
2305 or indirectly feeds them.
2307 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2308 trace_terminal (*i, *i);
2311 *r = *sorted_routes;
2314 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2315 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2316 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 presentation order %2\n", (*i)->name(), (*i)->presentation_info().order()));
2320 SuccessfulGraphSort (); /* EMIT SIGNAL */
2323 /* The topological sort failed, so we have a problem. Tell everyone
2324 and stick to the old graph; this will continue to be processed, so
2325 until the feedback is fixed, what is played back will not quite
2326 reflect what is actually connected. Note also that we do not
2327 do trace_terminal here, as it would fail due to an endless recursion,
2328 so the solo code will think that everything is still connected
2332 FeedbackDetected (); /* EMIT SIGNAL */
2337 /** Find a route name starting with \a base, maybe followed by the
2338 * lowest \a id. \a id will always be added if \a definitely_add_number
2339 * is true on entry; otherwise it will only be added if required
2340 * to make the name unique.
2342 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2343 * The available route name with the lowest ID will be used, and \a id
2344 * will be set to the ID.
2346 * \return false if a route name could not be found, and \a track_name
2347 * and \a id do not reflect a free route name.
2350 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2352 /* the base may conflict with ports that do not belong to existing
2353 routes, but hidden objects like the click track. So check port names
2354 before anything else.
2357 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2358 if (base == *reserved) {
2359 /* Check if this reserved name already exists, and if
2360 so, disallow it without a numeric suffix.
2362 if (route_by_name (*reserved)) {
2363 definitely_add_number = true;
2372 if (!definitely_add_number && route_by_name (base) == 0) {
2373 /* juse use the base */
2379 name = string_compose ("%1 %2", base, id);
2381 if (route_by_name (name) == 0) {
2387 } while (id < (UINT_MAX-1));
2392 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2394 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2396 in = ChanCount::ZERO;
2397 out = ChanCount::ZERO;
2399 boost::shared_ptr<RouteList> r = routes.reader ();
2401 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2402 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2403 if (tr && !tr->is_auditioner()) {
2404 in += tr->n_inputs();
2405 out += tr->n_outputs();
2411 Session::default_track_name_pattern (DataType t)
2414 case DataType::AUDIO:
2415 if (Profile->get_trx()) {
2422 case DataType::MIDI:
2429 /** Caller must not hold process lock
2430 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2431 * @param instrument plugin info for the instrument to insert pre-fader, if any
2433 list<boost::shared_ptr<MidiTrack> >
2434 Session::new_midi_track (const ChanCount& input, const ChanCount& output,
2435 boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2436 RouteGroup* route_group, uint32_t how_many, string name_template, PresentationInfo::order_t order,
2440 uint32_t track_id = 0;
2442 RouteList new_routes;
2443 list<boost::shared_ptr<MidiTrack> > ret;
2445 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2446 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2449 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2450 error << "cannot find name for new midi track" << endmsg;
2454 boost::shared_ptr<MidiTrack> track;
2457 track.reset (new MidiTrack (*this, track_name, mode));
2459 if (track->init ()) {
2463 if (Profile->get_mixbus ()) {
2464 track->set_strict_io (true);
2467 track->use_new_diskstream();
2469 BOOST_MARK_TRACK (track);
2472 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2473 if (track->input()->ensure_io (input, false, this)) {
2474 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2478 if (track->output()->ensure_io (output, false, this)) {
2479 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2484 track->non_realtime_input_change();
2487 route_group->add (track);
2490 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2492 new_routes.push_back (track);
2493 ret.push_back (track);
2496 catch (failed_constructor &err) {
2497 error << _("Session: could not create new midi track.") << endmsg;
2501 catch (AudioEngine::PortRegistrationFailure& pfe) {
2503 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;
2511 if (!new_routes.empty()) {
2512 StateProtector sp (this);
2513 if (Profile->get_trx()) {
2514 add_routes (new_routes, false, false, false, order);
2516 add_routes (new_routes, true, true, false, order);
2520 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2521 PluginPtr plugin = instrument->load (*this);
2523 plugin->load_preset (*pset);
2525 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2526 (*r)->add_processor (p, PreFader);
2536 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord* pset,
2537 PresentationInfo::Flag flag, PresentationInfo::order_t order)
2540 uint32_t bus_id = 0;
2544 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2547 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2548 error << "cannot find name for new midi bus" << endmsg;
2553 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flag, DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2559 if (Profile->get_mixbus ()) {
2560 bus->set_strict_io (true);
2563 BOOST_MARK_ROUTE(bus);
2566 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2568 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2569 error << _("cannot configure new midi bus input") << endmsg;
2574 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2575 error << _("cannot configure new midi bus output") << endmsg;
2581 route_group->add (bus);
2584 bus->add_internal_return ();
2585 ret.push_back (bus);
2588 catch (failed_constructor &err) {
2589 error << _("Session: could not create new audio route.") << endmsg;
2593 catch (AudioEngine::PortRegistrationFailure& pfe) {
2594 error << pfe.what() << endmsg;
2604 StateProtector sp (this);
2605 add_routes (ret, false, false, false, order);
2608 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2609 PluginPtr plugin = instrument->load (*this);
2611 plugin->load_preset (*pset);
2613 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2614 (*r)->add_processor (p, PreFader);
2625 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2627 boost::shared_ptr<Route> midi_track (wmt.lock());
2633 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2635 if (change.after.n_audio() <= change.before.n_audio()) {
2639 /* new audio ports: make sure the audio goes somewhere useful,
2640 * unless the user has no-auto-connect selected.
2642 * The existing ChanCounts don't matter for this call as they are only
2643 * to do with matching input and output indices, and we are only changing
2646 auto_connect_route (midi_track, false, ChanCount(), change.before);
2650 #ifdef USE_TRACKS_CODE_FEATURES
2653 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2655 return route1->remote_control_id() < route2->remote_control_id();
2659 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2661 // it is not allowed to perform connection
2662 if (!IO::connecting_legal) {
2666 // if we are deleting routes we will call this once at the end
2667 if (_route_deletion_in_progress) {
2671 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2677 // We need to disconnect the route's inputs and outputs first
2678 // basing on autoconnect configuration
2679 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2680 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2682 ChanCount existing_inputs;
2683 ChanCount existing_outputs;
2684 count_existing_track_channels (existing_inputs, existing_outputs);
2686 //ChanCount inputs = ChanCount::ZERO;
2687 //ChanCount outputs = ChanCount::ZERO;
2689 RouteList existing_routes = *routes.reader ();
2690 existing_routes.sort (compare_routes_by_remote_id);
2693 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2695 vector<string> physinputs;
2696 vector<string> physoutputs;
2698 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2699 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2701 uint32_t input_n = 0;
2702 uint32_t output_n = 0;
2703 RouteList::iterator rIter = existing_routes.begin();
2704 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2705 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2706 for (; rIter != existing_routes.end(); ++rIter) {
2707 if (*rIter == _master_out || *rIter == _monitor_out ) {
2711 if (current_output_auto_connection == AutoConnectPhysical) {
2712 (*rIter)->amp()->deactivate();
2713 } else if (current_output_auto_connection == AutoConnectMaster) {
2714 (*rIter)->amp()->activate();
2717 if (reconnectIputs) {
2718 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2720 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2722 if (current_input_auto_connection & AutoConnectPhysical) {
2724 if ( input_n == physinputs.size() ) {
2728 string port = physinputs[input_n];
2730 if (port.empty() ) {
2731 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2734 //GZ: check this; could be heavy
2735 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2741 if (reconnectOutputs) {
2743 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2744 if (current_output_auto_connection & AutoConnectPhysical) {
2746 //GZ: check this; could be heavy
2747 (*rIter)->output()->disconnect (this);
2748 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2750 //GZ: check this; could be heavy
2751 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2753 } else if (current_output_auto_connection & AutoConnectMaster){
2755 if (!reconnect_master) {
2759 //GZ: check this; could be heavy
2760 (*rIter)->output()->disconnect (this);
2763 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2764 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2766 error << error << "Master bus is not available" << endmsg;
2771 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2772 if (current_output_auto_connection & AutoConnectPhysical) {
2774 if ( output_n == physoutputs.size() ) {
2778 string port = physoutputs[output_n];
2780 if (port.empty() ) {
2781 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2784 //GZ: check this; could be heavy
2785 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2788 } else if (current_output_auto_connection & AutoConnectMaster) {
2790 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2794 // connect to master bus
2795 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2797 if (port.empty() ) {
2798 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2802 //GZ: check this; could be heavy
2803 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2810 _master_out->output()->disconnect (this);
2811 auto_connect_master_bus ();
2816 session_routes_reconnected (); /* EMIT SIGNAL */
2820 Session::reconnect_midi_scene_ports(bool inputs)
2824 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2826 scene_in_ptr->disconnect_all ();
2828 std::vector<EngineStateController::MidiPortState> midi_port_states;
2829 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2831 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2833 for (; state_iter != midi_port_states.end(); ++state_iter) {
2834 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2835 scene_in_ptr->connect (state_iter->name);
2842 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2844 if (scene_out_ptr ) {
2845 scene_out_ptr->disconnect_all ();
2847 std::vector<EngineStateController::MidiPortState> midi_port_states;
2848 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2850 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2852 for (; state_iter != midi_port_states.end(); ++state_iter) {
2853 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2854 scene_out_ptr->connect (state_iter->name);
2862 Session::reconnect_mtc_ports ()
2864 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2870 mtc_in_ptr->disconnect_all ();
2872 std::vector<EngineStateController::MidiPortState> midi_port_states;
2873 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2875 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2877 for (; state_iter != midi_port_states.end(); ++state_iter) {
2878 if (state_iter->available && state_iter->mtc_in) {
2879 mtc_in_ptr->connect (state_iter->name);
2883 if (!_midi_ports->mtc_input_port ()->connected () &&
2884 config.get_external_sync () &&
2885 (Config->get_sync_source () == MTC) ) {
2886 config.set_external_sync (false);
2889 if ( ARDOUR::Profile->get_trx () ) {
2890 // Tracks need this signal to update timecode_source_dropdown
2891 MtcOrLtcInputPortChanged (); //emit signal
2896 Session::reconnect_mmc_ports(bool inputs)
2898 if (inputs ) { // get all enabled midi input ports
2900 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2902 mmc_in_ptr->disconnect_all ();
2903 std::vector<std::string> enabled_midi_inputs;
2904 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2906 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2908 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2909 mmc_in_ptr->connect (*port_iter);
2913 } else { // get all enabled midi output ports
2915 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2917 mmc_out_ptr->disconnect_all ();
2918 std::vector<std::string> enabled_midi_outputs;
2919 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2921 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2923 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2924 mmc_out_ptr->connect (*port_iter);
2933 Session::ensure_route_presentation_info_gap (PresentationInfo::order_t first_new_order, uint32_t how_many)
2935 if (first_new_order == PresentationInfo::max_order) {
2936 /* adding at end, no worries */
2940 /* create a gap in the presentation info to accomodate @param how_many
2944 get_stripables (sl);
2946 for (StripableList::iterator si = sl.begin(); si != sl.end(); ++si) {
2947 boost::shared_ptr<Stripable> s (*si);
2949 if (s->is_monitor() || s->is_auditioner()) {
2953 if (s->presentation_info().order () >= first_new_order) {
2954 s->set_presentation_order (s->presentation_info().order () + how_many);
2959 /** Caller must not hold process lock
2960 * @param name_template string to use for the start of the name, or "" to use "Audio".
2962 list< boost::shared_ptr<AudioTrack> >
2963 Session::new_audio_track (int input_channels, int output_channels, RouteGroup* route_group,
2964 uint32_t how_many, string name_template, PresentationInfo::order_t order,
2968 uint32_t track_id = 0;
2970 RouteList new_routes;
2971 list<boost::shared_ptr<AudioTrack> > ret;
2973 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2974 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2978 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2979 error << "cannot find name for new audio track" << endmsg;
2983 boost::shared_ptr<AudioTrack> track;
2986 track.reset (new AudioTrack (*this, track_name, mode));
2988 if (track->init ()) {
2992 if (Profile->get_mixbus ()) {
2993 track->set_strict_io (true);
2996 if (ARDOUR::Profile->get_trx ()) {
2997 // TRACKS considers it's not a USE CASE, it's
2998 // a piece of behavior of the session model:
3000 // Gain for a newly created route depends on
3001 // the current output_auto_connect mode:
3003 // 0 for Stereo Out mode
3005 if (Config->get_output_auto_connect() & AutoConnectMaster) {
3006 track->gain_control()->set_value (dB_to_coefficient (0), Controllable::NoGroup);
3010 track->use_new_diskstream();
3012 BOOST_MARK_TRACK (track);
3015 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3017 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3018 error << string_compose (
3019 _("cannot configure %1 in/%2 out configuration for new audio track"),
3020 input_channels, output_channels)
3025 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3026 error << string_compose (
3027 _("cannot configure %1 in/%2 out configuration for new audio track"),
3028 input_channels, output_channels)
3035 route_group->add (track);
3038 track->non_realtime_input_change();
3040 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
3042 new_routes.push_back (track);
3043 ret.push_back (track);
3046 catch (failed_constructor &err) {
3047 error << _("Session: could not create new audio track.") << endmsg;
3051 catch (AudioEngine::PortRegistrationFailure& pfe) {
3053 error << pfe.what() << endmsg;
3061 if (!new_routes.empty()) {
3062 StateProtector sp (this);
3063 if (Profile->get_trx()) {
3064 add_routes (new_routes, false, false, false, order);
3066 add_routes (new_routes, true, true, false, order);
3073 /** Caller must not hold process lock.
3074 * @param name_template string to use for the start of the name, or "" to use "Bus".
3077 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template,
3078 PresentationInfo::Flag flags, PresentationInfo::order_t order)
3081 uint32_t bus_id = 0;
3085 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3088 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3089 error << "cannot find name for new audio bus" << endmsg;
3094 boost::shared_ptr<Route> bus (new Route (*this, bus_name, flags, DataType::AUDIO));
3100 if (Profile->get_mixbus ()) {
3101 bus->set_strict_io (true);
3104 BOOST_MARK_ROUTE(bus);
3107 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3109 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3110 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3111 input_channels, output_channels)
3117 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3118 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3119 input_channels, output_channels)
3126 route_group->add (bus);
3129 bus->add_internal_return ();
3130 ret.push_back (bus);
3133 catch (failed_constructor &err) {
3134 error << _("Session: could not create new audio route.") << endmsg;
3138 catch (AudioEngine::PortRegistrationFailure& pfe) {
3139 error << pfe.what() << endmsg;
3149 StateProtector sp (this);
3150 if (Profile->get_trx()) {
3151 add_routes (ret, false, false, false, order);
3153 add_routes (ret, false, true, true, order); // autoconnect // outputs only
3162 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3166 if (!tree.read (template_path.c_str())) {
3170 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3174 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3177 uint32_t number = 0;
3178 const uint32_t being_added = how_many;
3179 /* This will prevent the use of any existing XML-provided PBD::ID
3182 Stateful::ForceIDRegeneration force_ids;
3183 IO::disable_connecting ();
3187 /* We're going to modify the node contents a bit so take a
3188 * copy. The node may be re-used when duplicating more than once.
3191 XMLNode node_copy (node);
3196 if (!name_base.empty()) {
3198 /* if we're adding more than one routes, force
3199 * all the names of the new routes to be
3200 * numbered, via the final parameter.
3203 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3204 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3210 string const route_name = node_copy.property(X_("name"))->value ();
3212 /* generate a new name by adding a number to the end of the template name */
3213 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3214 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3215 abort(); /*NOTREACHED*/
3219 /* set this name in the XML description that we are about to use */
3221 bool rename_playlist;
3224 rename_playlist = true;
3229 rename_playlist = false;
3232 Route::set_name_in_state (node_copy, name, rename_playlist);
3234 /* trim bitslots from listen sends so that new ones are used */
3235 XMLNodeList children = node_copy.children ();
3236 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3237 if ((*i)->name() == X_("Processor")) {
3238 /* ForceIDRegeneration does not catch the following */
3239 XMLProperty const * role = (*i)->property (X_("role"));
3240 XMLProperty const * type = (*i)->property (X_("type"));
3241 if (role && role->value() == X_("Aux")) {
3242 /* check if the target bus exists.
3243 * we should not save aux-sends in templates.
3245 XMLProperty const * target = (*i)->property (X_("target"));
3247 (*i)->add_property ("type", "dangling-aux-send");
3250 boost::shared_ptr<Route> r = route_by_id (target->value());
3251 if (!r || boost::dynamic_pointer_cast<Track>(r)) {
3252 (*i)->add_property ("type", "dangling-aux-send");
3256 if (role && role->value() == X_("Listen")) {
3257 (*i)->remove_property (X_("bitslot"));
3259 else if (role && (role->value() == X_("Send") || role->value() == X_("Aux"))) {
3261 Delivery::Role xrole;
3262 uint32_t bitslot = 0;
3263 xrole = Delivery::Role (string_2_enum (role->value(), xrole));
3264 std::string name = Send::name_and_id_new_send(*this, xrole, bitslot, false);
3265 snprintf (buf, sizeof (buf), "%" PRIu32, bitslot);
3266 (*i)->remove_property (X_("bitslot"));
3267 (*i)->remove_property (X_("name"));
3268 (*i)->add_property ("bitslot", buf);
3269 (*i)->add_property ("name", name);
3271 else if (type && type->value() == X_("intreturn")) {
3272 (*i)->remove_property (X_("bitslot"));
3273 (*i)->add_property ("ignore-bitslot", "1");
3275 else if (type && type->value() == X_("return")) {
3276 // Return::set_state() generates a new one
3277 (*i)->remove_property (X_("bitslot"));
3279 else if (type && type->value() == X_("port")) {
3280 // PortInsert::set_state() handles the bitslot
3281 (*i)->remove_property (X_("bitslot"));
3282 (*i)->add_property ("ignore-name", "1");
3287 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3290 error << _("Session: cannot create track/bus from template description") << endmsg;
3294 if (boost::dynamic_pointer_cast<Track>(route)) {
3295 /* force input/output change signals so that the new diskstream
3296 picks up the configuration of the route. During session
3297 loading this normally happens in a different way.
3300 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3302 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3303 change.after = route->input()->n_ports();
3304 route->input()->changed (change, this);
3305 change.after = route->output()->n_ports();
3306 route->output()->changed (change, this);
3309 boost::shared_ptr<Track> track;
3311 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3314 track->use_new_playlist ();
3317 track->use_copy_playlist ();
3324 ret.push_back (route);
3327 catch (failed_constructor &err) {
3328 error << _("Session: could not create new route from template") << endmsg;
3332 catch (AudioEngine::PortRegistrationFailure& pfe) {
3333 error << pfe.what() << endmsg;
3342 StateProtector sp (this);
3343 if (Profile->get_trx()) {
3344 add_routes (ret, false, false, false, PresentationInfo::max_order);
3346 add_routes (ret, true, true, false, PresentationInfo::max_order);
3348 IO::enable_connecting ();
3355 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t order)
3358 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3359 add_routes_inner (new_routes, input_auto_connect, output_auto_connect, order);
3362 error << _("Adding new tracks/busses failed") << endmsg;
3367 update_latency (true);
3368 update_latency (false);
3373 save_state (_current_snapshot_name);
3376 update_route_record_state ();
3378 RouteAdded (new_routes); /* EMIT SIGNAL */
3382 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t order)
3384 ChanCount existing_inputs;
3385 ChanCount existing_outputs;
3389 count_existing_track_channels (existing_inputs, existing_outputs);
3392 RCUWriter<RouteList> writer (routes);
3393 boost::shared_ptr<RouteList> r = writer.get_copy ();
3394 r->insert (r->end(), new_routes.begin(), new_routes.end());
3395 n_routes = r->size();
3397 /* if there is no control out and we're not in the middle of loading,
3398 * resort the graph here. if there is a control out, we will resort
3399 * toward the end of this method. if we are in the middle of loading,
3400 * we will resort when done.
3403 if (!_monitor_out && IO::connecting_legal) {
3404 resort_routes_using (r);
3408 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("ensure order gap starting at %1 for %2\n", order, new_routes.size()));
3409 ensure_route_presentation_info_gap (order, new_routes.size());
3411 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x, ++added) {
3413 boost::weak_ptr<Route> wpr (*x);
3414 boost::shared_ptr<Route> r (*x);
3416 r->solo_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2,wpr));
3417 r->solo_isolate_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3418 r->mute_control()->Changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3420 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3421 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3422 r->processor_latency_changed.connect_same_thread (*this, boost::bind (&Session::queue_latency_recompute, this));
3424 if (r->is_master()) {
3428 if (r->is_monitor()) {
3432 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3434 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3435 track_playlist_changed (boost::weak_ptr<Track> (tr));
3436 tr->rec_enable_control()->Changed.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3438 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3440 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3441 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3445 if (!r->presentation_info().special()) {
3447 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("checking PI state for %1\n", r->name()));
3449 /* presentation info order may already have been set from XML */
3451 if (!r->presentation_info().order_set()) {
3453 if (order == PresentationInfo::max_order) {
3454 /* just add to the end */
3455 r->set_presentation_order_explicit (n_routes + added);
3456 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to NR %1 + %2 = %3\n", n_routes, added, n_routes + added));
3458 r->set_presentation_order (order + added);
3459 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order not set, set to %1 + %2 = %3\n", order, added, order + added));
3462 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("group order already set to %1\n", r->presentation_info().order()));
3466 #if !defined(__APPLE__) && !defined(__FreeBSD__)
3467 /* clang complains: 'operator<<' should be declared prior to the call site or in an associated namespace of one of its
3468 * arguments std::ostream& operator<<(std::ostream& o, ARDOUR::PresentationInfo const& rid)"
3470 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("added route %1, group order %2 type %3 (summary: %4)\n",
3472 r->presentation_info().order(),
3473 enum_2_string (r->presentation_info().flags()),
3474 r->presentation_info()));
3478 if (input_auto_connect || output_auto_connect) {
3479 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3480 existing_inputs += r->n_inputs();
3481 existing_outputs += r->n_outputs();
3487 if (_monitor_out && IO::connecting_legal) {
3488 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3490 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3491 if ((*x)->is_monitor()) {
3493 } else if ((*x)->is_master()) {
3496 (*x)->enable_monitor_send ();
3501 reassign_track_numbers ();
3505 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3507 boost::shared_ptr<RouteList> r = routes.reader ();
3508 boost::shared_ptr<Send> s;
3510 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3511 if ((s = (*i)->internal_send_for (dest)) != 0) {
3512 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3518 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3520 boost::shared_ptr<RouteList> r = routes.reader ();
3521 boost::shared_ptr<Send> s;
3523 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3524 if ((s = (*i)->internal_send_for (dest)) != 0) {
3525 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3531 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3533 boost::shared_ptr<RouteList> r = routes.reader ();
3534 boost::shared_ptr<Send> s;
3536 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3537 if ((s = (*i)->internal_send_for (dest)) != 0) {
3538 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3543 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3545 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3547 boost::shared_ptr<RouteList> r = routes.reader ();
3548 boost::shared_ptr<RouteList> t (new RouteList);
3550 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3551 /* no MIDI sends because there are no MIDI busses yet */
3552 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3557 add_internal_sends (dest, p, t);
3561 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3563 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3564 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3569 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3571 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3575 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3577 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3581 if (!dest->internal_return()) {
3582 dest->add_internal_return ();
3585 sender->add_aux_send (dest, before);
3591 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3593 { // RCU Writer scope
3594 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3595 RCUWriter<RouteList> writer (routes);
3596 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3599 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3601 if (*iter == _master_out) {
3605 (*iter)->solo_control()->set_value (0.0, Controllable::NoGroup);
3609 /* deleting the master out seems like a dumb
3610 idea, but its more of a UI policy issue
3614 if (*iter == _master_out) {
3615 _master_out = boost::shared_ptr<Route> ();
3618 if (*iter == _monitor_out) {
3619 _monitor_out.reset ();
3622 // We need to disconnect the route's inputs and outputs
3624 (*iter)->input()->disconnect (0);
3625 (*iter)->output()->disconnect (0);
3627 /* if the route had internal sends sending to it, remove them */
3628 if ((*iter)->internal_return()) {
3630 boost::shared_ptr<RouteList> r = routes.reader ();
3631 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3632 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3634 (*i)->remove_processor (s);
3639 /* if the monitoring section had a pointer to this route, remove it */
3640 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3641 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3642 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3643 (*iter)->remove_aux_or_listen (_monitor_out);
3646 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3647 if (mt && mt->step_editing()) {
3648 if (_step_editors > 0) {
3654 /* writer goes out of scope, forces route list update */
3656 } // end of RCU Writer scope
3658 update_route_solo_state ();
3659 update_latency_compensation ();
3662 /* Re-sort routes to remove the graph's current references to the one that is
3663 * going away, then flush old references out of the graph.
3664 * Wave Tracks: reconnect routes
3667 #ifdef USE_TRACKS_CODE_FEATURES
3668 reconnect_existing_routes(true, false);
3670 routes.flush (); // maybe unsafe, see below.
3674 if (_process_graph && !(_state_of_the_state & Deletion)) {
3675 _process_graph->clear_other_chain ();
3678 /* get rid of it from the dead wood collection in the route list manager */
3679 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3683 /* try to cause everyone to drop their references
3684 * and unregister ports from the backend
3687 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3688 (*iter)->drop_references ();
3691 if (_state_of_the_state & Deletion) {
3695 PresentationInfo::Change(); /* EMIT SIGNAL */
3697 /* save the new state of the world */
3699 if (save_state (_current_snapshot_name)) {
3700 save_history (_current_snapshot_name);
3703 update_route_record_state ();
3707 Session::remove_route (boost::shared_ptr<Route> route)
3709 boost::shared_ptr<RouteList> rl (new RouteList);
3710 rl->push_back (route);
3715 Session::route_mute_changed ()
3721 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3723 boost::shared_ptr<Route> route (wpr.lock());
3729 assert (Config->get_solo_control_is_listen_control());
3731 if (route->solo_control()->soloed_by_self_or_masters()) {
3733 if (Config->get_exclusive_solo()) {
3735 RouteGroup* rg = route->route_group ();
3736 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3738 boost::shared_ptr<RouteList> r = routes.reader ();
3740 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3741 if ((*i) == route) {
3742 /* already changed */
3746 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3747 /* route does not get solo propagated to it */
3751 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3752 /* this route is a part of the same solo group as the route
3753 * that was changed. Changing that route did change or will
3754 * change all group members appropriately, so we can ignore it
3759 (*i)->solo_control()->set_value (0.0, Controllable::NoGroup);
3765 } else if (_listen_cnt > 0) {
3770 update_route_solo_state ();
3774 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3776 boost::shared_ptr<Route> route (wpr.lock());
3782 bool send_changed = false;
3784 if (route->solo_isolate_control()->solo_isolated()) {
3785 if (_solo_isolated_cnt == 0) {
3786 send_changed = true;
3788 _solo_isolated_cnt++;
3789 } else if (_solo_isolated_cnt > 0) {
3790 _solo_isolated_cnt--;
3791 if (_solo_isolated_cnt == 0) {
3792 send_changed = true;
3797 IsolatedChanged (); /* EMIT SIGNAL */
3802 Session::route_solo_changed (bool self_solo_changed, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3804 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_changed));
3806 boost::shared_ptr<Route> route (wpr.lock());
3812 if (Config->get_solo_control_is_listen_control()) {
3813 route_listen_changed (group_override, wpr);
3817 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()));
3819 if (route->solo_control()->transitioned_into_solo() == 0) {
3820 /* route solo changed by upstream/downstream; not interesting
3823 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()));
3827 if (route->solo_control()->transitioned_into_solo() == 0) {
3828 /* reason for being soloed changed (e.g. master went away, we
3829 * took over the master state), but actual status did
3830 * not. nothing to do.
3832 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1: solo change was change in reason, not status\n", route->name()));
3835 boost::shared_ptr<RouteList> r = routes.reader ();
3836 int32_t delta = route->solo_control()->transitioned_into_solo ();
3838 /* the route may be a member of a group that has shared-solo
3839 * semantics. If so, then all members of that group should follow the
3840 * solo of the changed route. But ... this is optional, controlled by a
3841 * Controllable::GroupControlDisposition.
3843 * The first argument to the signal that this method is connected to is the
3844 * GroupControlDisposition value that was used to change solo.
3846 * If the solo change was done with group semantics (either InverseGroup
3847 * (force the entire group to change even if the group shared solo is
3848 * disabled) or UseGroup (use the group, which may or may not have the
3849 * shared solo property enabled)) then as we propagate the change to
3850 * the entire session we should IGNORE THE GROUP that the changed route
3854 RouteGroup* rg = route->route_group ();
3855 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3857 if (delta == 1 && Config->get_exclusive_solo()) {
3859 /* new solo: disable all other solos, but not the group if its solo-enabled */
3861 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3863 if ((*i) == route) {
3864 /* already changed */
3868 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3869 /* route does not get solo propagated to it */
3873 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3874 /* this route is a part of the same solo group as the route
3875 * that was changed. Changing that route did change or will
3876 * change all group members appropriately, so we can ignore it
3882 (*i)->solo_control()->set_value (0.0, group_override);
3886 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3888 RouteList uninvolved;
3890 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3892 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3893 bool via_sends_only;
3894 bool in_signal_flow;
3896 if ((*i) == route) {
3897 /* already changed */
3901 if ((*i)->solo_isolate_control()->solo_isolated() || !(*i)->can_solo()) {
3902 /* route does not get solo propagated to it */
3906 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3907 /* this route is a part of the same solo group as the route
3908 * that was changed. Changing that route did change or will
3909 * change all group members appropriately, so we can ignore it
3915 in_signal_flow = false;
3917 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3919 if ((*i)->feeds (route, &via_sends_only)) {
3920 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3921 if (!via_sends_only) {
3922 if (!route->soloed_by_others_upstream()) {
3923 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3925 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3928 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3930 in_signal_flow = true;
3932 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3935 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3937 if (route->feeds (*i, &via_sends_only)) {
3938 /* propagate solo upstream only if routing other than
3939 sends is involved, but do consider the other route
3940 (*i) to be part of the signal flow even if only
3943 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3947 route->soloed_by_others_downstream(),
3948 route->soloed_by_others_upstream()));
3949 if (!via_sends_only) {
3950 //NB. Triggers Invert Push, which handles soloed by downstream
3951 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3952 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3954 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3956 in_signal_flow = true;
3958 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3961 if (!in_signal_flow) {
3962 uninvolved.push_back (*i);
3966 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3968 update_route_solo_state (r);
3970 /* now notify that the mute state of the routes not involved in the signal
3971 pathway of the just-solo-changed route may have altered.
3974 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3975 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3976 (*i)->act_on_mute ();
3977 (*i)->mute_control()->Changed (false, Controllable::NoGroup);
3980 SoloChanged (); /* EMIT SIGNAL */
3985 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3987 /* now figure out if anything that matters is soloed (or is "listening")*/
3989 bool something_soloed = false;
3990 bool something_listening = false;
3991 uint32_t listeners = 0;
3992 uint32_t isolated = 0;
3995 r = routes.reader();
3998 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3999 if ((*i)->can_solo()) {
4000 if (Config->get_solo_control_is_listen_control()) {
4001 if ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value()) {
4003 something_listening = true;
4006 (*i)->set_listen (false);
4007 if ((*i)->can_solo() && ((*i)->self_soloed() || (*i)->solo_control()->get_masters_value())) {
4008 something_soloed = true;
4013 if ((*i)->solo_isolate_control()->solo_isolated()) {
4018 if (something_soloed != _non_soloed_outs_muted) {
4019 _non_soloed_outs_muted = something_soloed;
4020 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
4023 if (something_listening != _listening) {
4024 _listening = something_listening;
4025 SoloActive (_listening);
4028 _listen_cnt = listeners;
4030 if (isolated != _solo_isolated_cnt) {
4031 _solo_isolated_cnt = isolated;
4032 IsolatedChanged (); /* EMIT SIGNAL */
4035 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
4036 something_soloed, listeners, isolated));
4040 Session::get_stripables (StripableList& sl) const
4042 boost::shared_ptr<RouteList> r = routes.reader ();
4043 sl.insert (sl.end(), r->begin(), r->end());
4045 VCAList v = _vca_manager->vcas ();
4046 sl.insert (sl.end(), v.begin(), v.end());
4049 boost::shared_ptr<RouteList>
4050 Session::get_routes_with_internal_returns() const
4052 boost::shared_ptr<RouteList> r = routes.reader ();
4053 boost::shared_ptr<RouteList> rl (new RouteList);
4055 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4056 if ((*i)->internal_return ()) {
4064 Session::io_name_is_legal (const std::string& name) const
4066 boost::shared_ptr<RouteList> r = routes.reader ();
4068 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
4069 if (name == *reserved) {
4070 if (!route_by_name (*reserved)) {
4071 /* first instance of a reserved name is allowed */
4074 /* all other instances of a reserved name are not allowed */
4079 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4080 if ((*i)->name() == name) {
4084 if ((*i)->has_io_processor_named (name)) {
4093 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
4096 vector<string> connections;
4098 /* if we are passed only a single route and we're not told to turn
4099 * others off, then just do the simple thing.
4102 if (flip_others == false && rl->size() == 1) {
4103 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
4105 mt->set_input_active (onoff);
4110 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
4112 PortSet& ps ((*rt)->input()->ports());
4114 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
4115 p->get_connections (connections);
4118 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
4119 routes_using_input_from (*s, rl2);
4122 /* scan all relevant routes to see if others are on or off */
4124 bool others_are_already_on = false;
4126 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4128 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4134 if ((*r) != (*rt)) {
4135 if (mt->input_active()) {
4136 others_are_already_on = true;
4139 /* this one needs changing */
4140 mt->set_input_active (onoff);
4146 /* globally reverse other routes */
4148 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4149 if ((*r) != (*rt)) {
4150 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4152 mt->set_input_active (!others_are_already_on);
4161 Session::routes_using_input_from (const string& str, RouteList& rl)
4163 boost::shared_ptr<RouteList> r = routes.reader();
4165 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4166 if ((*i)->input()->connected_to (str)) {
4172 boost::shared_ptr<Route>
4173 Session::route_by_name (string name) const
4175 boost::shared_ptr<RouteList> r = routes.reader ();
4177 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4178 if ((*i)->name() == name) {
4183 return boost::shared_ptr<Route> ((Route*) 0);
4186 boost::shared_ptr<Route>
4187 Session::route_by_id (PBD::ID id) const
4189 boost::shared_ptr<RouteList> r = routes.reader ();
4191 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4192 if ((*i)->id() == id) {
4197 return boost::shared_ptr<Route> ((Route*) 0);
4200 boost::shared_ptr<Processor>
4201 Session::processor_by_id (PBD::ID id) const
4203 boost::shared_ptr<RouteList> r = routes.reader ();
4205 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4206 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4212 return boost::shared_ptr<Processor> ();
4215 boost::shared_ptr<Track>
4216 Session::track_by_diskstream_id (PBD::ID id) const
4218 boost::shared_ptr<RouteList> r = routes.reader ();
4220 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4221 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4222 if (t && t->using_diskstream_id (id)) {
4227 return boost::shared_ptr<Track> ();
4230 boost::shared_ptr<Route>
4231 Session::get_remote_nth_route (PresentationInfo::order_t n) const
4233 return boost::dynamic_pointer_cast<Route> (get_remote_nth_stripable (n, PresentationInfo::Route));
4236 boost::shared_ptr<Stripable>
4237 Session::get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag flags) const
4240 PresentationInfo::order_t match_cnt = 0;
4242 get_stripables (sl);
4243 sl.sort (Stripable::PresentationOrderSorter());
4245 for (StripableList::const_iterator s = sl.begin(); s != sl.end(); ++s) {
4246 if ((*s)->presentation_info().flag_match (flags)) {
4247 if (match_cnt++ == n) {
4253 /* there is no nth stripable that matches the given flags */
4254 return boost::shared_ptr<Stripable>();
4257 boost::shared_ptr<Route>
4258 Session::route_by_selected_count (uint32_t id) const
4260 boost::shared_ptr<RouteList> r = routes.reader ();
4262 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4263 /* NOT IMPLEMENTED */
4266 return boost::shared_ptr<Route> ((Route*) 0);
4269 struct PresentationOrderSorter {
4270 bool operator() (boost::shared_ptr<Stripable> a, boost::shared_ptr<Stripable> b) {
4271 if (a->presentation_info().special() && !b->presentation_info().special()) {
4272 /* a is not ordered, b is; b comes before a */
4274 } else if (!b->presentation_info().order_set() && a->presentation_info().order_set()) {
4275 /* b is not ordered, a is; a comes before b */
4278 return a->presentation_info().order() < b->presentation_info().order();
4284 Session::reassign_track_numbers ()
4288 RouteList r (*(routes.reader ()));
4289 PresentationOrderSorter sorter;
4292 StateProtector sp (this);
4294 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4295 if (boost::dynamic_pointer_cast<Track> (*i)) {
4296 (*i)->set_track_number(++tn);
4298 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4299 (*i)->set_track_number(--bn);
4302 const uint32_t decimals = ceilf (log10f (tn + 1));
4303 const bool decimals_changed = _track_number_decimals != decimals;
4304 _track_number_decimals = decimals;
4306 if (decimals_changed && config.get_track_name_number ()) {
4307 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4308 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4310 t->resync_track_name();
4313 // trigger GUI re-layout
4314 config.ParameterChanged("track-name-number");
4318 if (DEBUG_ENABLED(DEBUG::OrderKeys)) {
4319 boost::shared_ptr<RouteList> rl = routes.reader ();
4320 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4321 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("%1 numbered %2\n", (*i)->name(), (*i)->track_number()));
4329 Session::playlist_region_added (boost::weak_ptr<Region> w)
4331 boost::shared_ptr<Region> r = w.lock ();
4336 /* These are the operations that are currently in progress... */
4337 list<GQuark> curr = _current_trans_quarks;
4340 /* ...and these are the operations during which we want to update
4341 the session range location markers.
4344 ops.push_back (Operations::capture);
4345 ops.push_back (Operations::paste);
4346 ops.push_back (Operations::duplicate_region);
4347 ops.push_back (Operations::insert_file);
4348 ops.push_back (Operations::insert_region);
4349 ops.push_back (Operations::drag_region_brush);
4350 ops.push_back (Operations::region_drag);
4351 ops.push_back (Operations::selection_grab);
4352 ops.push_back (Operations::region_fill);
4353 ops.push_back (Operations::fill_selection);
4354 ops.push_back (Operations::create_region);
4355 ops.push_back (Operations::region_copy);
4356 ops.push_back (Operations::fixed_time_region_copy);
4359 /* See if any of the current operations match the ones that we want */
4361 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4363 /* If so, update the session range markers */
4365 maybe_update_session_range (r->position (), r->last_frame ());
4369 /** Update the session range markers if a is before the current start or
4370 * b is after the current end.
4373 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4375 if (_state_of_the_state & Loading) {
4379 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4381 if (_session_range_location == 0) {
4383 set_session_range_location (a, b + session_end_marker_shift_samples);
4387 if (a < _session_range_location->start()) {
4388 _session_range_location->set_start (a);
4391 if (b > _session_range_location->end()) {
4392 _session_range_location->set_end (b);
4398 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4400 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4401 maybe_update_session_range (i->to, i->to + i->length);
4406 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4408 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4409 maybe_update_session_range (i->from, i->to);
4413 /* Region management */
4415 boost::shared_ptr<Region>
4416 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4418 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4419 RegionFactory::RegionMap::const_iterator i;
4420 boost::shared_ptr<Region> region;
4422 Glib::Threads::Mutex::Lock lm (region_lock);
4424 for (i = regions.begin(); i != regions.end(); ++i) {
4428 if (region->whole_file()) {
4430 if (child->source_equivalent (region)) {
4436 return boost::shared_ptr<Region> ();
4440 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4442 set<boost::shared_ptr<Region> > relevant_regions;
4444 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4445 RegionFactory::get_regions_using_source (*s, relevant_regions);
4448 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4449 set<boost::shared_ptr<Region> >::iterator tmp;
4454 playlists->destroy_region (*r);
4455 RegionFactory::map_remove (*r);
4457 (*r)->drop_sources ();
4458 (*r)->drop_references ();
4460 relevant_regions.erase (r);
4465 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4468 Glib::Threads::Mutex::Lock ls (source_lock);
4469 /* remove from the main source list */
4470 sources.erase ((*s)->id());
4473 (*s)->mark_for_remove ();
4474 (*s)->drop_references ();
4483 Session::remove_last_capture ()
4485 list<boost::shared_ptr<Source> > srcs;
4487 boost::shared_ptr<RouteList> rl = routes.reader ();
4488 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4489 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4494 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4497 srcs.insert (srcs.end(), l.begin(), l.end());
4502 destroy_sources (srcs);
4504 save_state (_current_snapshot_name);
4509 /* Source Management */
4512 Session::add_source (boost::shared_ptr<Source> source)
4514 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4515 pair<SourceMap::iterator,bool> result;
4517 entry.first = source->id();
4518 entry.second = source;
4521 Glib::Threads::Mutex::Lock lm (source_lock);
4522 result = sources.insert (entry);
4525 if (result.second) {
4527 /* yay, new source */
4529 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4532 if (!fs->within_session()) {
4533 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4539 boost::shared_ptr<AudioFileSource> afs;
4541 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4542 if (Config->get_auto_analyse_audio()) {
4543 Analyser::queue_source_for_analysis (source, false);
4547 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4552 Session::remove_source (boost::weak_ptr<Source> src)
4554 if (_state_of_the_state & Deletion) {
4558 SourceMap::iterator i;
4559 boost::shared_ptr<Source> source = src.lock();
4566 Glib::Threads::Mutex::Lock lm (source_lock);
4568 if ((i = sources.find (source->id())) != sources.end()) {
4573 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4575 /* save state so we don't end up with a session file
4576 referring to non-existent sources.
4579 save_state (_current_snapshot_name);
4583 boost::shared_ptr<Source>
4584 Session::source_by_id (const PBD::ID& id)
4586 Glib::Threads::Mutex::Lock lm (source_lock);
4587 SourceMap::iterator i;
4588 boost::shared_ptr<Source> source;
4590 if ((i = sources.find (id)) != sources.end()) {
4597 boost::shared_ptr<AudioFileSource>
4598 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4600 /* Restricted to audio files because only audio sources have channel
4604 Glib::Threads::Mutex::Lock lm (source_lock);
4606 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4607 boost::shared_ptr<AudioFileSource> afs
4608 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4610 if (afs && afs->path() == path && chn == afs->channel()) {
4615 return boost::shared_ptr<AudioFileSource>();
4618 boost::shared_ptr<MidiSource>
4619 Session::midi_source_by_path (const std::string& path) const
4621 /* Restricted to MIDI files because audio sources require a channel
4622 for unique identification, in addition to a path.
4625 Glib::Threads::Mutex::Lock lm (source_lock);
4627 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4628 boost::shared_ptr<MidiSource> ms
4629 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4630 boost::shared_ptr<FileSource> fs
4631 = boost::dynamic_pointer_cast<FileSource>(s->second);
4633 if (ms && fs && fs->path() == path) {
4638 return boost::shared_ptr<MidiSource>();
4642 Session::count_sources_by_origin (const string& path)
4645 Glib::Threads::Mutex::Lock lm (source_lock);
4647 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4648 boost::shared_ptr<FileSource> fs
4649 = boost::dynamic_pointer_cast<FileSource>(i->second);
4651 if (fs && fs->origin() == path) {
4660 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4662 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4663 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4665 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4670 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4672 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4674 if (Glib::path_is_absolute (filepath)) {
4676 /* rip the session dir from the audiofile source */
4678 string session_path;
4679 bool in_another_session = true;
4681 if (filepath.find (interchange_dir_string) != string::npos) {
4683 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4684 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4685 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4686 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4688 /* see if it is within our session */
4690 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4691 if (i->path == session_path) {
4692 in_another_session = false;
4697 in_another_session = false;
4701 if (in_another_session) {
4702 SessionDirectory sd (session_path);
4703 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4707 /* 1) if file belongs to this session
4708 * it may be a relative path (interchange/...)
4709 * or just basename (session_state, remove source)
4710 * -> just use the basename
4712 std::string filename = Glib::path_get_basename (filepath);
4715 /* 2) if the file is outside our session dir:
4716 * (imported but not copied) add the path for check-summming */
4718 path = Glib::path_get_dirname (filepath);
4721 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4725 Session::new_audio_source_path_for_embedded (const std::string& path)
4729 * we know that the filename is already unique because it exists
4730 * out in the filesystem.
4732 * However, when we bring it into the session, we could get a
4735 * Eg. two embedded files:
4740 * When merged into session, these collide.
4742 * There will not be a conflict with in-memory sources
4743 * because when the source was created we already picked
4744 * a unique name for it.
4746 * This collision is not likely to be common, but we have to guard
4747 * against it. So, if there is a collision, take the md5 hash of the
4748 * the path, and use that as the filename instead.
4751 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4752 string base = Glib::path_get_basename (path);
4753 string newpath = Glib::build_filename (sdir.sound_path(), base);
4755 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4759 md5.digestString (path.c_str());
4760 md5.writeToString ();
4761 base = md5.digestChars;
4763 string ext = get_suffix (path);
4770 newpath = Glib::build_filename (sdir.sound_path(), base);
4772 /* if this collides, we're screwed */
4774 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4775 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4784 /** Return true if there are no audio file sources that use @param name as
4785 * the filename component of their path.
4787 * Return false otherwise.
4789 * This method MUST ONLY be used to check in-session, mono files since it
4790 * hard-codes the channel of the audio file source we are looking for as zero.
4792 * If/when Ardour supports native files in non-mono formats, the logic here
4793 * will need to be revisited.
4796 Session::audio_source_name_is_unique (const string& name)
4798 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4799 vector<space_and_path>::iterator i;
4800 uint32_t existing = 0;
4802 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4804 /* note that we search *without* the extension so that
4805 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4806 in the event that this new name is required for
4807 a file format change.
4810 const string spath = *i;
4812 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4817 /* it is possible that we have the path already
4818 * assigned to a source that has not yet been written
4819 * (ie. the write source for a diskstream). we have to
4820 * check this in order to make sure that our candidate
4821 * path isn't used again, because that can lead to
4822 * two Sources point to the same file with different
4823 * notions of their removability.
4827 string possible_path = Glib::build_filename (spath, name);
4829 if (audio_source_by_path_and_channel (possible_path, 0)) {
4835 return (existing == 0);
4839 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)
4842 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4844 if (Profile->get_trx() && destructive) {
4846 sstr << setfill ('0') << setw (4) << cnt;
4847 sstr << legalized_base;
4849 sstr << legalized_base;
4851 if (take_required || related_exists) {
4863 } else if (nchan > 2) {
4868 /* XXX what? more than 26 channels! */
4879 /** Return a unique name based on \a base for a new internal audio source */
4881 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4884 string possible_name;
4885 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4887 bool some_related_source_name_exists = false;
4889 legalized = legalize_for_path (base);
4891 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4893 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4895 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4897 if (audio_source_name_is_unique (possible_name)) {
4901 some_related_source_name_exists = true;
4904 error << string_compose(
4905 _("There are already %1 recordings for %2, which I consider too many."),
4906 limit, base) << endmsg;
4908 throw failed_constructor();
4912 /* We've established that the new name does not exist in any session
4913 * directory, so now find out which one we should use for this new
4917 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4919 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4924 /** Return a unique name based on `base` for a new internal MIDI source */
4926 Session::new_midi_source_path (const string& base)
4929 char buf[PATH_MAX+1];
4930 const uint32_t limit = 10000;
4932 string possible_path;
4933 string possible_name;
4936 legalized = legalize_for_path (base);
4938 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4939 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4941 /* - the main session folder is the first in the vector.
4942 * - after checking all locations for file-name uniqueness,
4943 * we keep the one from the last iteration as new file name
4944 * - midi files are small and should just be kept in the main session-folder
4946 * -> reverse the array, check main session folder last and use that as location
4949 std::reverse(sdirs.begin(), sdirs.end());
4951 for (cnt = 1; cnt <= limit; ++cnt) {
4953 vector<space_and_path>::iterator i;
4954 uint32_t existing = 0;
4956 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4958 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4959 possible_name = buf;
4961 possible_path = Glib::build_filename (*i, possible_name);
4963 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4967 if (midi_source_by_path (possible_path)) {
4972 if (existing == 0) {
4977 error << string_compose(
4978 _("There are already %1 recordings for %2, which I consider too many."),
4979 limit, base) << endmsg;
4985 /* No need to "find best location" for software/app-based RAID, because
4986 MIDI is so small that we always put it in the same place.
4989 return possible_path;
4993 /** Create a new within-session audio source */
4994 boost::shared_ptr<AudioFileSource>
4995 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4997 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4999 if (!path.empty()) {
5000 return boost::dynamic_pointer_cast<AudioFileSource> (
5001 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
5003 throw failed_constructor ();
5007 /** Create a new within-session MIDI source */
5008 boost::shared_ptr<MidiSource>
5009 Session::create_midi_source_for_session (string const & basic_name)
5011 const string path = new_midi_source_path (basic_name);
5013 if (!path.empty()) {
5014 return boost::dynamic_pointer_cast<SMFSource> (
5015 SourceFactory::createWritable (
5016 DataType::MIDI, *this, path, false, frame_rate()));
5018 throw failed_constructor ();
5022 /** Create a new within-session MIDI source */
5023 boost::shared_ptr<MidiSource>
5024 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
5026 /* the caller passes in the track the source will be used in,
5027 so that we can keep the numbering sane.
5029 Rationale: a track with the name "Foo" that has had N
5030 captures carried out so far will ALREADY have a write source
5031 named "Foo-N+1.mid" waiting to be used for the next capture.
5033 If we call new_midi_source_name() we will get "Foo-N+2". But
5034 there is no region corresponding to "Foo-N+1", so when
5035 "Foo-N+2" appears in the track, the gap presents the user
5036 with odd behaviour - why did it skip past Foo-N+1?
5038 We could explain this to the user in some odd way, but
5039 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
5042 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
5045 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
5047 std::string name = track->steal_write_source_name ();
5050 return boost::shared_ptr<MidiSource>();
5053 /* MIDI files are small, just put them in the first location of the
5054 session source search path.
5057 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
5059 return boost::dynamic_pointer_cast<SMFSource> (
5060 SourceFactory::createWritable (
5061 DataType::MIDI, *this, path, false, frame_rate()));
5066 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
5068 if (playlist->hidden()) {
5072 playlists->add (playlist);
5075 playlist->release();
5082 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
5084 if (_state_of_the_state & Deletion) {
5088 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
5094 playlists->remove (playlist);
5100 Session::set_audition (boost::shared_ptr<Region> r)
5102 pending_audition_region = r;
5103 add_post_transport_work (PostTransportAudition);
5104 _butler->schedule_transport_work ();
5108 Session::audition_playlist ()
5110 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5111 ev->region.reset ();
5117 Session::register_lua_function (
5118 const std::string& name,
5119 const std::string& script,
5120 const LuaScriptParamList& args
5123 Glib::Threads::Mutex::Lock lm (lua_lock);
5125 lua_State* L = lua.getState();
5127 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
5128 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
5129 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
5130 if ((*i)->optional && !(*i)->is_set) { continue; }
5131 tbl_arg[(*i)->name] = (*i)->value;
5133 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
5138 Session::unregister_lua_function (const std::string& name)
5140 Glib::Threads::Mutex::Lock lm (lua_lock);
5141 (*_lua_del)(name); // throws luabridge::LuaException
5142 lua.collect_garbage ();
5146 std::vector<std::string>
5147 Session::registered_lua_functions ()
5149 Glib::Threads::Mutex::Lock lm (lua_lock);
5150 std::vector<std::string> rv;
5153 luabridge::LuaRef list ((*_lua_list)());
5154 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5155 if (!i.key ().isString ()) { assert(0); continue; }
5156 rv.push_back (i.key ().cast<std::string> ());
5158 } catch (luabridge::LuaException const& e) { }
5163 static void _lua_print (std::string s) {
5164 std::cout << "SessionLua: " << s << "\n";
5169 Session::try_run_lua (pframes_t nframes)
5171 if (_n_lua_scripts == 0) return;
5172 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5174 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5175 lua.collect_garbage_step ();
5180 Session::setup_lua ()
5183 lua.Print.connect (&_lua_print);
5187 "function ArdourSession ()"
5188 " local self = { scripts = {}, instances = {} }"
5190 " local remove = function (n)"
5191 " self.scripts[n] = nil"
5192 " self.instances[n] = nil"
5193 " Session:scripts_changed()" // call back
5196 " local addinternal = function (n, f, a)"
5197 " assert(type(n) == 'string', 'function-name must be string')"
5198 " assert(type(f) == 'function', 'Given script is a not a function')"
5199 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5200 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5201 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5202 " 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"
5203 " 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, Session = Session, PBD = PBD, Timecode = Timecode, Evoral = Evoral, C = C, ARDOUR = ARDOUR }"
5204 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5205 " Session:scripts_changed()" // call back
5208 " local add = function (n, b, a)"
5209 " assert(type(b) == 'string', 'ByteCode must be string')"
5210 " load (b)()" // assigns f
5211 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5212 " addinternal (n, load(f), a)"
5215 " local run = function (...)"
5216 " for n, s in pairs (self.instances) do"
5217 " local status, err = pcall (s, ...)"
5218 " if not status then"
5219 " print ('fn \"'.. n .. '\": ', err)"
5226 " local cleanup = function ()"
5227 " self.scripts = nil"
5228 " self.instances = nil"
5231 " local list = function ()"
5233 " for n, _ in pairs (self.scripts) do"
5239 " local function basic_serialize (o)"
5240 " if type(o) == \"number\" then"
5241 " return tostring(o)"
5243 " return string.format(\"%q\", o)"
5247 " local function serialize (name, value)"
5248 " local rv = name .. ' = '"
5250 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5251 " return rv .. basic_serialize(value) .. ' '"
5252 " elseif type(value) == \"table\" then"
5254 " for k,v in pairs(value) do"
5255 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5256 " rv = rv .. serialize(fieldname, v) .. ' '"
5257 " collectgarbage()" // string concatenation allocates a new string :(
5260 " elseif type(value) == \"function\" then"
5261 " return rv .. string.format(\"%q\", string.dump(value, true))"
5263 " error('cannot save a ' .. type(value))"
5268 " local save = function ()"
5269 " return (serialize('scripts', self.scripts))"
5272 " local restore = function (state)"
5273 " self.scripts = {}"
5275 " for n, s in pairs (scripts) do"
5276 " addinternal (n, load(s['f']), s['a'])"
5280 " return { run = run, add = add, remove = remove,"
5281 " list = list, restore = restore, save = save, cleanup = cleanup}"
5284 " sess = ArdourSession ()"
5285 " ArdourSession = nil"
5287 "function ardour () end"
5290 lua_State* L = lua.getState();
5293 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5294 lua.do_command ("sess = nil"); // hide it.
5295 lua.do_command ("collectgarbage()");
5297 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5298 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5299 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5300 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5301 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5302 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5303 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5304 } catch (luabridge::LuaException const& e) {
5305 fatal << string_compose (_("programming error: %1"),
5306 X_("Failed to setup Lua interpreter"))
5308 abort(); /*NOTREACHED*/
5311 LuaBindings::stddef (L);
5312 LuaBindings::common (L);
5313 LuaBindings::dsp (L);
5314 luabridge::push <Session *> (L, this);
5315 lua_setglobal (L, "Session");
5319 Session::scripts_changed ()
5321 assert (!lua_lock.trylock()); // must hold lua_lock
5324 luabridge::LuaRef list ((*_lua_list)());
5326 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5327 if (!i.key ().isString ()) { assert(0); continue; }
5330 _n_lua_scripts = cnt;
5331 } catch (luabridge::LuaException const& e) {
5332 fatal << string_compose (_("programming error: %1"),
5333 X_("Indexing Lua Session Scripts failed."))
5335 abort(); /*NOTREACHED*/
5340 Session::non_realtime_set_audition ()
5342 assert (pending_audition_region);
5343 auditioner->audition_region (pending_audition_region);
5344 pending_audition_region.reset ();
5345 AuditionActive (true); /* EMIT SIGNAL */
5349 Session::audition_region (boost::shared_ptr<Region> r)
5351 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5357 Session::cancel_audition ()
5362 if (auditioner->auditioning()) {
5363 auditioner->cancel_audition ();
5364 AuditionActive (false); /* EMIT SIGNAL */
5369 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5371 if (a->is_monitor()) {
5374 if (b->is_monitor()) {
5377 return a->presentation_info().order() < b->presentation_info().order();
5381 Session::is_auditioning () const
5383 /* can be called before we have an auditioner object */
5385 return auditioner->auditioning();
5392 Session::graph_reordered ()
5394 /* don't do this stuff if we are setting up connections
5395 from a set_state() call or creating new tracks. Ditto for deletion.
5398 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5402 /* every track/bus asked for this to be handled but it was deferred because
5403 we were connecting. do it now.
5406 request_input_change_handling ();
5410 /* force all diskstreams to update their capture offset values to
5411 reflect any changes in latencies within the graph.
5414 boost::shared_ptr<RouteList> rl = routes.reader ();
5415 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5416 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5418 tr->set_capture_offset ();
5423 /** @return Number of frames that there is disk space available to write,
5426 boost::optional<framecnt_t>
5427 Session::available_capture_duration ()
5429 Glib::Threads::Mutex::Lock lm (space_lock);
5431 if (_total_free_4k_blocks_uncertain) {
5432 return boost::optional<framecnt_t> ();
5435 float sample_bytes_on_disk = 4.0; // keep gcc happy
5437 switch (config.get_native_file_data_format()) {
5439 sample_bytes_on_disk = 4.0;
5443 sample_bytes_on_disk = 3.0;
5447 sample_bytes_on_disk = 2.0;
5451 /* impossible, but keep some gcc versions happy */
5452 fatal << string_compose (_("programming error: %1"),
5453 X_("illegal native file data format"))
5455 abort(); /*NOTREACHED*/
5458 double scale = 4096.0 / sample_bytes_on_disk;
5460 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5461 return max_framecnt;
5464 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5468 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5471 RCUWriter<BundleList> writer (_bundles);
5472 boost::shared_ptr<BundleList> b = writer.get_copy ();
5473 b->push_back (bundle);
5477 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5484 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5486 bool removed = false;
5489 RCUWriter<BundleList> writer (_bundles);
5490 boost::shared_ptr<BundleList> b = writer.get_copy ();
5491 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5493 if (i != b->end()) {
5500 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5506 boost::shared_ptr<Bundle>
5507 Session::bundle_by_name (string name) const
5509 boost::shared_ptr<BundleList> b = _bundles.reader ();
5511 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5512 if ((*i)->name() == name) {
5517 return boost::shared_ptr<Bundle> ();
5521 Session::tempo_map_changed (const PropertyChange&)
5525 playlists->update_after_tempo_map_change ();
5527 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5533 Session::gui_tempo_map_changed ()
5537 playlists->update_after_tempo_map_change ();
5539 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5543 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5545 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5546 (*i)->recompute_frames_from_bbt ();
5550 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5551 * the given count with the current block size.
5554 Session::ensure_buffers (ChanCount howmany)
5556 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5560 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5562 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5563 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5568 Session::next_insert_id ()
5570 /* this doesn't really loop forever. just think about it */
5573 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5574 if (!insert_bitset[n]) {
5575 insert_bitset[n] = true;
5581 /* none available, so resize and try again */
5583 insert_bitset.resize (insert_bitset.size() + 16, false);
5588 Session::next_send_id ()
5590 /* this doesn't really loop forever. just think about it */
5593 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5594 if (!send_bitset[n]) {
5595 send_bitset[n] = true;
5601 /* none available, so resize and try again */
5603 send_bitset.resize (send_bitset.size() + 16, false);
5608 Session::next_aux_send_id ()
5610 /* this doesn't really loop forever. just think about it */
5613 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5614 if (!aux_send_bitset[n]) {
5615 aux_send_bitset[n] = true;
5621 /* none available, so resize and try again */
5623 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5628 Session::next_return_id ()
5630 /* this doesn't really loop forever. just think about it */
5633 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5634 if (!return_bitset[n]) {
5635 return_bitset[n] = true;
5641 /* none available, so resize and try again */
5643 return_bitset.resize (return_bitset.size() + 16, false);
5648 Session::mark_send_id (uint32_t id)
5650 if (id >= send_bitset.size()) {
5651 send_bitset.resize (id+16, false);
5653 if (send_bitset[id]) {
5654 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5656 send_bitset[id] = true;
5660 Session::mark_aux_send_id (uint32_t id)
5662 if (id >= aux_send_bitset.size()) {
5663 aux_send_bitset.resize (id+16, false);
5665 if (aux_send_bitset[id]) {
5666 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5668 aux_send_bitset[id] = true;
5672 Session::mark_return_id (uint32_t id)
5674 if (id >= return_bitset.size()) {
5675 return_bitset.resize (id+16, false);
5677 if (return_bitset[id]) {
5678 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5680 return_bitset[id] = true;
5684 Session::mark_insert_id (uint32_t id)
5686 if (id >= insert_bitset.size()) {
5687 insert_bitset.resize (id+16, false);
5689 if (insert_bitset[id]) {
5690 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5692 insert_bitset[id] = true;
5696 Session::unmark_send_id (uint32_t id)
5698 if (id < send_bitset.size()) {
5699 send_bitset[id] = false;
5704 Session::unmark_aux_send_id (uint32_t id)
5706 if (id < aux_send_bitset.size()) {
5707 aux_send_bitset[id] = false;
5712 Session::unmark_return_id (uint32_t id)
5714 if (_state_of_the_state & Deletion) { return; }
5715 if (id < return_bitset.size()) {
5716 return_bitset[id] = false;
5721 Session::unmark_insert_id (uint32_t id)
5723 if (id < insert_bitset.size()) {
5724 insert_bitset[id] = false;
5729 Session::reset_native_file_format ()
5731 boost::shared_ptr<RouteList> rl = routes.reader ();
5733 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5734 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5736 /* don't save state as we do this, there's no point
5738 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5739 tr->reset_write_sources (false);
5740 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5746 Session::route_name_unique (string n) const
5748 boost::shared_ptr<RouteList> r = routes.reader ();
5750 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5751 if ((*i)->name() == n) {
5760 Session::route_name_internal (string n) const
5762 if (auditioner && auditioner->name() == n) {
5766 if (_click_io && _click_io->name() == n) {
5774 Session::freeze_all (InterThreadInfo& itt)
5776 boost::shared_ptr<RouteList> r = routes.reader ();
5778 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5780 boost::shared_ptr<Track> t;
5782 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5783 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5793 boost::shared_ptr<Region>
5794 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5795 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5796 InterThreadInfo& itt,
5797 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5798 bool for_export, bool for_freeze)
5800 boost::shared_ptr<Region> result;
5801 boost::shared_ptr<Playlist> playlist;
5802 boost::shared_ptr<Source> source;
5803 ChanCount diskstream_channels (track.n_channels());
5804 framepos_t position;
5805 framecnt_t this_chunk;
5807 framepos_t latency_skip;
5809 framepos_t len = end - start;
5810 bool need_block_size_reset = false;
5811 ChanCount const max_proc = track.max_processor_streams ();
5812 string legal_playlist_name;
5813 string possible_path;
5816 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5817 end, start) << endmsg;
5821 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5822 include_endpoint, for_export, for_freeze);
5824 if (diskstream_channels.n(track.data_type()) < 1) {
5825 error << _("Cannot write a range with no data.") << endmsg;
5829 // block all process callback handling
5831 block_processing ();
5834 // synchronize with AudioEngine::process_callback()
5835 // make sure processing is not currently running
5836 // and processing_blocked() is honored before
5837 // acquiring thread buffers
5838 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5841 _bounce_processing_active = true;
5843 /* call tree *MUST* hold route_lock */
5845 if ((playlist = track.playlist()) == 0) {
5849 legal_playlist_name = legalize_for_path (playlist->name());
5851 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5853 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5854 string path = ((track.data_type() == DataType::AUDIO)
5855 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5856 : new_midi_source_path (legal_playlist_name));
5863 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5866 catch (failed_constructor& err) {
5867 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5871 srcs.push_back (source);
5874 /* tell redirects that care that we are about to use a much larger
5875 * blocksize. this will flush all plugins too, so that they are ready
5876 * to be used for this process.
5879 need_block_size_reset = true;
5880 track.set_block_size (bounce_chunk_size);
5881 _engine.main_thread()->get_buffers ();
5885 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5887 /* create a set of reasonably-sized buffers */
5888 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5889 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5891 buffers.set_count (max_proc);
5893 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5894 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5895 boost::shared_ptr<MidiSource> ms;
5897 afs->prepare_for_peakfile_writes ();
5898 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5899 Source::Lock lock(ms->mutex());
5900 ms->mark_streaming_write_started(lock);
5904 while (to_do && !itt.cancel) {
5906 this_chunk = min (to_do, bounce_chunk_size);
5908 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5912 start += this_chunk;
5913 to_do -= this_chunk;
5914 itt.progress = (float) (1.0 - ((double) to_do / len));
5916 if (latency_skip >= bounce_chunk_size) {
5917 latency_skip -= bounce_chunk_size;
5921 const framecnt_t current_chunk = this_chunk - latency_skip;
5924 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5925 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5926 boost::shared_ptr<MidiSource> ms;
5929 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5932 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5933 Source::Lock lock(ms->mutex());
5935 const MidiBuffer& buf = buffers.get_midi(0);
5936 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5937 Evoral::Event<framepos_t> ev = *i;
5938 ev.set_time(ev.time() - position);
5939 ms->append_event_frames(lock, ev, ms->timeline_position());
5946 /* post-roll, pick up delayed processor output */
5947 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5949 while (latency_skip && !itt.cancel) {
5950 this_chunk = min (latency_skip, bounce_chunk_size);
5951 latency_skip -= this_chunk;
5953 buffers.silence (this_chunk, 0);
5954 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5957 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5958 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5961 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5973 xnow = localtime (&now);
5975 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5976 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5977 boost::shared_ptr<MidiSource> ms;
5980 afs->update_header (position, *xnow, now);
5981 afs->flush_header ();
5982 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5983 Source::Lock lock(ms->mutex());
5984 ms->mark_streaming_write_completed(lock);
5988 /* construct a region to represent the bounced material */
5992 plist.add (Properties::start, 0);
5993 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5994 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5996 result = RegionFactory::create (srcs, plist);
6002 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6003 (*src)->mark_for_remove ();
6004 (*src)->drop_references ();
6008 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
6009 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
6012 afs->done_with_peakfile_writes ();
6016 _bounce_processing_active = false;
6018 if (need_block_size_reset) {
6019 _engine.main_thread()->drop_buffers ();
6020 track.set_block_size (get_block_size());
6023 unblock_processing ();
6029 Session::gain_automation_buffer() const
6031 return ProcessThread::gain_automation_buffer ();
6035 Session::trim_automation_buffer() const
6037 return ProcessThread::trim_automation_buffer ();
6041 Session::send_gain_automation_buffer() const
6043 return ProcessThread::send_gain_automation_buffer ();
6047 Session::pan_automation_buffer() const
6049 return ProcessThread::pan_automation_buffer ();
6053 Session::get_silent_buffers (ChanCount count)
6055 return ProcessThread::get_silent_buffers (count);
6059 Session::get_scratch_buffers (ChanCount count, bool silence)
6061 return ProcessThread::get_scratch_buffers (count, silence);
6065 Session::get_noinplace_buffers (ChanCount count)
6067 return ProcessThread::get_noinplace_buffers (count);
6071 Session::get_route_buffers (ChanCount count, bool silence)
6073 return ProcessThread::get_route_buffers (count, silence);
6078 Session::get_mix_buffers (ChanCount count)
6080 return ProcessThread::get_mix_buffers (count);
6084 Session::ntracks () const
6087 boost::shared_ptr<RouteList> r = routes.reader ();
6089 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6090 if (boost::dynamic_pointer_cast<Track> (*i)) {
6099 Session::nbusses () const
6102 boost::shared_ptr<RouteList> r = routes.reader ();
6104 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
6105 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
6114 Session::add_automation_list(AutomationList *al)
6116 automation_lists[al->id()] = al;
6119 /** @return true if there is at least one record-enabled track, otherwise false */
6121 Session::have_rec_enabled_track () const
6123 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
6127 Session::have_rec_disabled_track () const
6129 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
6132 /** Update the state of our rec-enabled tracks flag */
6134 Session::update_route_record_state ()
6136 boost::shared_ptr<RouteList> rl = routes.reader ();
6137 RouteList::iterator i = rl->begin();
6138 while (i != rl->end ()) {
6140 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6141 if (tr && tr->rec_enable_control()->get_value()) {
6148 int const old = g_atomic_int_get (&_have_rec_enabled_track);
6150 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
6152 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
6153 RecordStateChanged (); /* EMIT SIGNAL */
6156 for (i = rl->begin(); i != rl->end (); ++i) {
6157 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6158 if (tr && !tr->rec_enable_control()->get_value()) {
6163 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
6165 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
6167 if (record_status() == Recording && record_arm_state_changed ) {
6168 RecordArmStateChanged ();
6174 Session::listen_position_changed ()
6176 boost::shared_ptr<RouteList> r = routes.reader ();
6178 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6179 (*i)->listen_position_changed ();
6184 Session::solo_control_mode_changed ()
6186 if (soloing() || listening()) {
6187 /* We can't use ::clear_all_solo_state() here because during
6188 session loading at program startup, that will queue a call
6189 to rt_clear_all_solo_state() that will not execute until
6190 AFTER solo states have been established (thus throwing away
6191 the session's saved solo state). So just explicitly turn
6194 set_controls (route_list_to_control_list (get_routes(), &Stripable::solo_control), 0.0, Controllable::NoGroup);
6198 /** Called when a property of one of our route groups changes */
6200 Session::route_group_property_changed (RouteGroup* rg)
6202 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6205 /** Called when a route is added to one of our route groups */
6207 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6209 RouteAddedToRouteGroup (rg, r);
6212 /** Called when a route is removed from one of our route groups */
6214 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6216 update_route_record_state ();
6217 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6220 boost::shared_ptr<RouteList>
6221 Session::get_tracks () const
6223 boost::shared_ptr<RouteList> rl = routes.reader ();
6224 boost::shared_ptr<RouteList> tl (new RouteList);
6226 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6227 if (boost::dynamic_pointer_cast<Track> (*r)) {
6228 if (!(*r)->is_auditioner()) {
6236 boost::shared_ptr<RouteList>
6237 Session::get_routes_with_regions_at (framepos_t const p) const
6239 boost::shared_ptr<RouteList> r = routes.reader ();
6240 boost::shared_ptr<RouteList> rl (new RouteList);
6242 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6243 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6248 boost::shared_ptr<Playlist> pl = tr->playlist ();
6253 if (pl->has_region_at (p)) {
6262 Session::goto_end ()
6264 if (_session_range_location) {
6265 request_locate (_session_range_location->end(), false);
6267 request_locate (0, false);
6272 Session::goto_start ()
6274 if (_session_range_location) {
6275 request_locate (_session_range_location->start(), false);
6277 request_locate (0, false);
6282 Session::current_start_frame () const
6284 return _session_range_location ? _session_range_location->start() : 0;
6288 Session::current_end_frame () const
6290 return _session_range_location ? _session_range_location->end() : 0;
6294 Session::set_session_range_location (framepos_t start, framepos_t end)
6296 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6297 _locations->add (_session_range_location);
6301 Session::step_edit_status_change (bool yn)
6307 send = (_step_editors == 0);
6312 send = (_step_editors == 1);
6315 if (_step_editors > 0) {
6321 StepEditStatusChange (val);
6327 Session::start_time_changed (framepos_t old)
6329 /* Update the auto loop range to match the session range
6330 (unless the auto loop range has been changed by the user)
6333 Location* s = _locations->session_range_location ();
6338 Location* l = _locations->auto_loop_location ();
6340 if (l && l->start() == old) {
6341 l->set_start (s->start(), true);
6346 Session::end_time_changed (framepos_t old)
6348 /* Update the auto loop range to match the session range
6349 (unless the auto loop range has been changed by the user)
6352 Location* s = _locations->session_range_location ();
6357 Location* l = _locations->auto_loop_location ();
6359 if (l && l->end() == old) {
6360 l->set_end (s->end(), true);
6364 std::vector<std::string>
6365 Session::source_search_path (DataType type) const
6369 if (session_dirs.size() == 1) {
6371 case DataType::AUDIO:
6372 sp.push_back (_session_dir->sound_path());
6374 case DataType::MIDI:
6375 sp.push_back (_session_dir->midi_path());
6379 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6380 SessionDirectory sdir (i->path);
6382 case DataType::AUDIO:
6383 sp.push_back (sdir.sound_path());
6385 case DataType::MIDI:
6386 sp.push_back (sdir.midi_path());
6392 if (type == DataType::AUDIO) {
6393 const string sound_path_2X = _session_dir->sound_path_2X();
6394 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6395 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6396 sp.push_back (sound_path_2X);
6401 // now check the explicit (possibly user-specified) search path
6404 case DataType::AUDIO:
6405 sp += Searchpath(config.get_audio_search_path ());
6407 case DataType::MIDI:
6408 sp += Searchpath(config.get_midi_search_path ());
6416 Session::ensure_search_path_includes (const string& path, DataType type)
6425 case DataType::AUDIO:
6426 sp += Searchpath(config.get_audio_search_path ());
6428 case DataType::MIDI:
6429 sp += Searchpath (config.get_midi_search_path ());
6433 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6434 /* No need to add this new directory if it has the same inode as
6435 an existing one; checking inode rather than name prevents duplicated
6436 directories when we are using symlinks.
6438 On Windows, I think we could just do if (*i == path) here.
6440 if (PBD::equivalent_paths (*i, path)) {
6448 case DataType::AUDIO:
6449 config.set_audio_search_path (sp.to_string());
6451 case DataType::MIDI:
6452 config.set_midi_search_path (sp.to_string());
6458 Session::remove_dir_from_search_path (const string& dir, DataType type)
6463 case DataType::AUDIO:
6464 sp = Searchpath(config.get_audio_search_path ());
6466 case DataType::MIDI:
6467 sp = Searchpath (config.get_midi_search_path ());
6474 case DataType::AUDIO:
6475 config.set_audio_search_path (sp.to_string());
6477 case DataType::MIDI:
6478 config.set_midi_search_path (sp.to_string());
6484 boost::shared_ptr<Speakers>
6485 Session::get_speakers()
6491 Session::unknown_processors () const
6495 boost::shared_ptr<RouteList> r = routes.reader ();
6496 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6497 list<string> t = (*i)->unknown_processors ();
6498 copy (t.begin(), t.end(), back_inserter (p));
6508 Session::update_latency (bool playback)
6511 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6513 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _route_deletion_in_progress) {
6517 boost::shared_ptr<RouteList> r = routes.reader ();
6518 framecnt_t max_latency = 0;
6521 /* reverse the list so that we work backwards from the last route to run to the first */
6522 RouteList* rl = routes.reader().get();
6523 r.reset (new RouteList (*rl));
6524 reverse (r->begin(), r->end());
6527 /* compute actual latency values for the given direction and store them all in per-port
6528 structures. this will also publish the same values (to JACK) so that computation of latency
6529 for routes can consistently use public latency values.
6532 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6533 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6536 /* because we latency compensate playback, our published playback latencies should
6537 be the same for all output ports - all material played back by ardour has
6538 the same latency, whether its caused by plugins or by latency compensation. since
6539 these may differ from the values computed above, reset all playback port latencies
6543 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6545 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6546 (*i)->set_public_port_latencies (max_latency, playback);
6551 post_playback_latency ();
6555 post_capture_latency ();
6558 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6562 Session::post_playback_latency ()
6564 set_worst_playback_latency ();
6566 boost::shared_ptr<RouteList> r = routes.reader ();
6568 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6569 if (!(*i)->is_auditioner() && ((*i)->active())) {
6570 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6574 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6575 (*i)->set_latency_compensation (_worst_track_latency);
6580 Session::post_capture_latency ()
6582 set_worst_capture_latency ();
6584 /* reflect any changes in capture latencies into capture offsets
6587 boost::shared_ptr<RouteList> rl = routes.reader();
6588 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6589 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6591 tr->set_capture_offset ();
6597 Session::initialize_latencies ()
6600 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6601 update_latency (false);
6602 update_latency (true);
6605 set_worst_io_latencies ();
6609 Session::set_worst_io_latencies ()
6611 set_worst_playback_latency ();
6612 set_worst_capture_latency ();
6616 Session::set_worst_playback_latency ()
6618 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6622 _worst_output_latency = 0;
6624 if (!_engine.connected()) {
6628 boost::shared_ptr<RouteList> r = routes.reader ();
6630 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6631 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6634 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6638 Session::set_worst_capture_latency ()
6640 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6644 _worst_input_latency = 0;
6646 if (!_engine.connected()) {
6650 boost::shared_ptr<RouteList> r = routes.reader ();
6652 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6653 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6656 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6660 Session::update_latency_compensation (bool force_whole_graph)
6662 bool some_track_latency_changed = false;
6664 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6668 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6670 _worst_track_latency = 0;
6672 boost::shared_ptr<RouteList> r = routes.reader ();
6674 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6675 if (!(*i)->is_auditioner() && ((*i)->active())) {
6677 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6678 some_track_latency_changed = true;
6680 _worst_track_latency = max (tl, _worst_track_latency);
6684 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6685 (some_track_latency_changed ? "yes" : "no")));
6687 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6689 if (some_track_latency_changed || force_whole_graph) {
6690 _engine.update_latencies ();
6694 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6695 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6699 tr->set_capture_offset ();
6704 Session::session_name_is_legal (const string& path)
6706 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6708 for (int i = 0; illegal_chars[i]; ++i) {
6709 if (path.find (illegal_chars[i]) != string::npos) {
6710 return illegal_chars[i];
6718 Session::notify_presentation_info_change ()
6720 if (deletion_in_progress()) {
6724 PresentationInfo::Change (); /* EMIT SIGNAL */
6725 reassign_track_numbers();
6727 #ifdef USE_TRACKS_CODE_FEATURES
6728 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6729 * if track order has been changed by user
6731 reconnect_existing_routes(true, true);
6737 Session::operation_in_progress (GQuark op) const
6739 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6742 boost::shared_ptr<Port>
6743 Session::ltc_input_port () const
6745 return _ltc_input->nth (0);
6748 boost::shared_ptr<Port>
6749 Session::ltc_output_port () const
6751 return _ltc_output->nth (0);
6755 Session::reconnect_ltc_input ()
6759 string src = Config->get_ltc_source_port();
6761 _ltc_input->disconnect (this);
6763 if (src != _("None") && !src.empty()) {
6764 _ltc_input->nth (0)->connect (src);
6767 if ( ARDOUR::Profile->get_trx () ) {
6768 // Tracks need this signal to update timecode_source_dropdown
6769 MtcOrLtcInputPortChanged (); //emit signal
6775 Session::reconnect_ltc_output ()
6779 string src = Config->get_ltc_output_port();
6781 _ltc_output->disconnect (this);
6783 if (src != _("None") && !src.empty()) {
6784 _ltc_output->nth (0)->connect (src);
6790 Session::set_range_selection (framepos_t start, framepos_t end)
6792 _range_selection = Evoral::Range<framepos_t> (start, end);
6793 #ifdef USE_TRACKS_CODE_FEATURES
6794 follow_playhead_priority ();
6799 Session::set_object_selection (framepos_t start, framepos_t end)
6801 _object_selection = Evoral::Range<framepos_t> (start, end);
6802 #ifdef USE_TRACKS_CODE_FEATURES
6803 follow_playhead_priority ();
6808 Session::clear_range_selection ()
6810 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6811 #ifdef USE_TRACKS_CODE_FEATURES
6812 follow_playhead_priority ();
6817 Session::clear_object_selection ()
6819 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6820 #ifdef USE_TRACKS_CODE_FEATURES
6821 follow_playhead_priority ();
6826 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6827 const ChanCount& input_start,
6828 const ChanCount& output_start,
6829 const ChanCount& input_offset,
6830 const ChanCount& output_offset)
6832 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6833 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6834 input_start, output_start,
6835 input_offset, output_offset));
6837 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6838 pthread_cond_signal (&_auto_connect_cond);
6839 pthread_mutex_unlock (&_auto_connect_mutex);
6844 Session::queue_latency_recompute ()
6846 g_atomic_int_inc (&_latency_recompute_pending);
6847 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6848 pthread_cond_signal (&_auto_connect_cond);
6849 pthread_mutex_unlock (&_auto_connect_mutex);
6854 Session::auto_connect (const AutoConnectRequest& ar)
6856 boost::shared_ptr<Route> route = ar.route.lock();
6858 if (!route) { return; }
6860 if (!IO::connecting_legal) {
6864 /* If both inputs and outputs are auto-connected to physical ports,
6865 * use the max of input and output offsets to ensure auto-connected
6866 * port numbers always match up (e.g. the first audio input and the
6867 * first audio output of the route will have the same physical
6868 * port number). Otherwise just use the lowest input or output
6872 const bool in_out_physical =
6873 (Config->get_input_auto_connect() & AutoConnectPhysical)
6874 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6875 && ar.connect_inputs;
6877 const ChanCount in_offset = in_out_physical
6878 ? ChanCount::max(ar.input_offset, ar.output_offset)
6881 const ChanCount out_offset = in_out_physical
6882 ? ChanCount::max(ar.input_offset, ar.output_offset)
6885 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6886 vector<string> physinputs;
6887 vector<string> physoutputs;
6889 _engine.get_physical_outputs (*t, physoutputs);
6890 _engine.get_physical_inputs (*t, physinputs);
6892 if (!physinputs.empty() && ar.connect_inputs) {
6893 uint32_t nphysical_in = physinputs.size();
6895 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6898 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6899 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6902 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6908 if (!physoutputs.empty()) {
6909 uint32_t nphysical_out = physoutputs.size();
6910 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6914 * do not create new connections if we reached the limit of physical outputs
6917 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6918 ARDOUR::Profile->get_trx () &&
6919 ar.output_offset.get(*t) == nphysical_out ) {
6923 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6924 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6925 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6926 /* master bus is audio only */
6927 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6928 port = _master_out->input()->ports().port(*t,
6929 i % _master_out->input()->n_ports().get(*t))->name();
6933 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6942 Session::auto_connect_thread_start ()
6944 if (_ac_thread_active) {
6948 while (!_auto_connect_queue.empty ()) {
6949 _auto_connect_queue.pop ();
6952 _ac_thread_active = true;
6953 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6954 _ac_thread_active = false;
6959 Session::auto_connect_thread_terminate ()
6961 if (!_ac_thread_active) {
6964 _ac_thread_active = false;
6967 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6968 while (!_auto_connect_queue.empty ()) {
6969 _auto_connect_queue.pop ();
6973 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6974 pthread_cond_signal (&_auto_connect_cond);
6975 pthread_mutex_unlock (&_auto_connect_mutex);
6979 pthread_join (_auto_connect_thread, &status);
6983 Session::auto_connect_thread (void *arg)
6985 Session *s = static_cast<Session *>(arg);
6986 s->auto_connect_thread_run ();
6992 Session::auto_connect_thread_run ()
6994 pthread_set_name (X_("autoconnect"));
6995 SessionEvent::create_per_thread_pool (X_("autoconnect"), 1024);
6996 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 1024);
6997 pthread_mutex_lock (&_auto_connect_mutex);
6998 while (_ac_thread_active) {
7000 if (!_auto_connect_queue.empty ()) {
7001 // Why would we need the process lock ??
7002 // A: if ports are added while we're connecting, the backend's iterator may be invalidated:
7003 // graph_order_callback() -> resort_routes() -> direct_feeds_according_to_reality () -> backend::connected_to()
7004 // All ardour-internal backends use a std::vector xxxAudioBackend::find_port()
7005 // We have control over those, but what does jack do?
7006 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
7008 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
7009 while (!_auto_connect_queue.empty ()) {
7010 const AutoConnectRequest ar (_auto_connect_queue.front());
7011 _auto_connect_queue.pop ();
7018 if (!actively_recording ()) { // might not be needed,
7019 /* this is only used for updating plugin latencies, the
7020 * graph does not change. so it's safe in general.
7022 * .. update_latency_compensation () entails set_capture_offset()
7023 * which calls Diskstream::set_capture_offset () which
7024 * modifies the capture offset... which can be a proplem
7025 * in "prepare_to_stop"
7027 while (g_atomic_int_and (&_latency_recompute_pending, 0)) {
7028 update_latency_compensation ();
7032 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
7034 pthread_mutex_unlock (&_auto_connect_mutex);