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/boost_debug.h"
40 #include "pbd/convert.h"
41 #include "pbd/convert.h"
42 #include "pbd/error.h"
43 #include "pbd/file_utils.h"
45 #include "pbd/pthread_utils.h"
46 #include "pbd/search_path.h"
47 #include "pbd/stacktrace.h"
48 #include "pbd/stl_delete.h"
49 #include "pbd/replace_all.h"
50 #include "pbd/unwind.h"
52 #include "ardour/amp.h"
53 #include "ardour/analyser.h"
54 #include "ardour/async_midi_port.h"
55 #include "ardour/audio_buffer.h"
56 #include "ardour/audio_diskstream.h"
57 #include "ardour/audio_port.h"
58 #include "ardour/audio_track.h"
59 #include "ardour/audioengine.h"
60 #include "ardour/audiofilesource.h"
61 #include "ardour/auditioner.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/route_graph.h"
94 #include "ardour/route_group.h"
95 #include "ardour/route_sorters.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/source_factory.h"
102 #include "ardour/speakers.h"
103 #include "ardour/tempo.h"
104 #include "ardour/track.h"
105 #include "ardour/user_bundle.h"
106 #include "ardour/utils.h"
108 #include "midi++/port.h"
109 #include "midi++/mmc.h"
111 #include "LuaBridge/LuaBridge.h"
115 #include <glibmm/checksum.h>
124 using namespace ARDOUR;
127 bool Session::_disable_all_loaded_plugins = false;
128 bool Session::_bypass_all_loaded_plugins = false;
129 guint Session::_name_id_counter = 0;
131 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
132 PBD::Signal1<void,std::string> Session::Dialog;
133 PBD::Signal0<int> Session::AskAboutPendingState;
134 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
135 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
136 PBD::Signal0<void> Session::SendFeedback;
137 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
139 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
140 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
141 PBD::Signal2<void,std::string, std::string> Session::Exported;
142 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
143 PBD::Signal0<void> Session::Quit;
144 PBD::Signal0<void> Session::FeedbackDetected;
145 PBD::Signal0<void> Session::SuccessfulGraphSort;
146 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
148 const framecnt_t Session::bounce_chunk_size = 8192;
149 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
150 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
152 // seconds should be added after the region exceeds end marker
153 #ifdef USE_TRACKS_CODE_FEATURES
154 const uint32_t Session::session_end_shift = 5;
156 const uint32_t Session::session_end_shift = 0;
159 /** @param snapshot_name Snapshot name, without .ardour suffix */
160 Session::Session (AudioEngine &eng,
161 const string& fullpath,
162 const string& snapshot_name,
163 BusProfile* bus_profile,
165 : playlists (new SessionPlaylists)
167 , process_function (&Session::process_with_events)
168 , _bounce_processing_active (false)
169 , waiting_for_sync_offset (false)
170 , _base_frame_rate (0)
171 , _nominal_frame_rate (0)
172 , _current_frame_rate (0)
173 , transport_sub_state (0)
174 , _record_status (Disabled)
175 , _transport_frame (0)
176 , _session_range_location (0)
179 , _transport_speed (0)
180 , _default_transport_speed (1.0)
181 , _last_transport_speed (0)
182 , _target_transport_speed (0.0)
183 , auto_play_legal (false)
184 , _last_slave_transport_frame (0)
185 , maximum_output_latency (0)
186 , _requested_return_frame (-1)
187 , current_block_size (0)
188 , _worst_output_latency (0)
189 , _worst_input_latency (0)
190 , _worst_track_latency (0)
191 , _have_captured (false)
192 , _non_soloed_outs_muted (false)
195 , _solo_isolated_cnt (0)
197 , _was_seamless (Config->get_seamless_loop ())
198 , _under_nsm_control (false)
200 , delta_accumulator_cnt (0)
201 , average_slave_delta (1800) // !!! why 1800 ???
203 , have_first_delta_accumulator (false)
204 , _slave_state (Stopped)
205 , _mtc_active (false)
206 , _ltc_active (false)
207 , post_export_sync (false)
208 , post_export_position (0)
210 , _export_rolling (false)
211 , _export_preroll (0)
212 , _pre_export_mmc_enabled (false)
213 , _name (snapshot_name)
215 , _send_qf_mtc (false)
216 , _pframes_since_last_mtc (0)
217 , session_midi_feedback (0)
219 , loop_changing (false)
221 , _session_dir (new SessionDirectory (fullpath))
222 , _current_snapshot_name (snapshot_name)
224 , state_was_pending (false)
225 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
227 , _save_queued (false)
228 , _last_roll_location (0)
229 , _last_roll_or_reversal_location (0)
230 , _last_record_location (0)
231 , pending_locate_roll (false)
232 , pending_locate_frame (0)
233 , pending_locate_flush (false)
234 , pending_abort (false)
235 , pending_auto_loop (false)
236 , _mempool ("Session", 1048576)
237 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
239 , _butler (new Butler (*this))
240 , _post_transport_work (0)
241 , cumulative_rf_motion (0)
243 , _locations (new Locations (*this))
244 , _ignore_skips_updates (false)
245 , _rt_thread_active (false)
246 , _rt_emit_pending (false)
247 , _ac_thread_active (false)
249 , outbound_mtc_timecode_frame (0)
250 , next_quarter_frame_to_send (-1)
251 , _frames_per_timecode_frame (0)
252 , _frames_per_hour (0)
253 , _timecode_frames_per_hour (0)
254 , last_timecode_valid (false)
255 , last_timecode_when (0)
256 , _send_timecode_update (false)
268 , ltc_timecode_offset (0)
269 , ltc_timecode_negative_offset (false)
270 , midi_control_ui (0)
272 , _all_route_group (new RouteGroup (*this, "all"))
273 , routes (new RouteList)
274 , _adding_routes_in_progress (false)
275 , _reconnecting_routes_in_progress (false)
276 , _route_deletion_in_progress (false)
277 , destructive_index (0)
278 , _track_number_decimals(1)
279 , default_fade_steepness (0)
280 , default_fade_msecs (0)
281 , _total_free_4k_blocks (0)
282 , _total_free_4k_blocks_uncertain (false)
283 , no_questions_about_missing_files (false)
286 , _bundles (new BundleList)
287 , _bundle_xml_node (0)
291 , click_emphasis_data (0)
293 , click_emphasis_length (0)
294 , _clicks_cleared (0)
295 , _play_range (false)
296 , _range_selection (-1,-1)
297 , _object_selection (-1,-1)
299 , first_file_data_format_reset (true)
300 , first_file_header_format_reset (true)
301 , have_looped (false)
302 , _have_rec_enabled_track (false)
303 , _have_rec_disabled_track (true)
305 , _suspend_timecode_transmission (0)
306 , _speakers (new Speakers)
308 , ignore_route_processor_changes (false)
315 pthread_mutex_init (&_rt_emit_mutex, 0);
316 pthread_cond_init (&_rt_emit_cond, 0);
318 pthread_mutex_init (&_auto_connect_mutex, 0);
319 pthread_cond_init (&_auto_connect_cond, 0);
321 init_name_id_counter (1); // reset for new sessions, start at 1
323 pre_engine_init (fullpath);
329 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
331 #ifdef USE_TRACKS_CODE_FEATURES
332 sr = EngineStateController::instance()->get_current_sample_rate();
334 if (ensure_engine (sr)) {
336 throw SessionException (_("Cannot connect to audio/midi engine"));
339 // set samplerate for plugins added early
340 // e.g from templates or MB channelstrip
341 set_block_size (_engine.samples_per_cycle());
342 set_frame_rate (_engine.sample_rate());
344 if (create (mix_template, bus_profile)) {
346 throw SessionException (_("Session initialization failed"));
349 /* if a mix template was provided, then ::create() will
350 * have copied it into the session and we need to load it
351 * so that we have the state ready for ::set_state()
352 * after the engine is started.
354 * Note that we do NOT try to get the sample rate from
355 * the template at this time, though doing so would
356 * be easy if we decided this was an appropriate part
360 if (!mix_template.empty()) {
361 if (load_state (_current_snapshot_name)) {
362 throw SessionException (_("Failed to load template/snapshot state"));
364 store_recent_templates (mix_template);
367 /* load default session properties - if any */
372 if (load_state (_current_snapshot_name)) {
373 throw SessionException (_("Failed to load state"));
376 /* try to get sample rate from XML state so that we
377 * can influence the SR if we set up the audio
382 const XMLProperty* prop;
383 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
384 sr = atoi (prop->value());
388 if (ensure_engine (sr)) {
390 throw SessionException (_("Cannot connect to audio/midi engine"));
394 if (post_engine_init ()) {
396 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
399 store_recent_sessions (_name, _path);
401 bool was_dirty = dirty();
403 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
405 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
406 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
409 DirtyChanged (); /* EMIT SIGNAL */
412 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
413 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
415 emit_thread_start ();
416 auto_connect_thread_start ();
418 /* hook us up to the engine since we are now completely constructed */
420 BootMessage (_("Connect to engine"));
422 _engine.set_session (this);
423 _engine.reset_timebase ();
425 #ifdef USE_TRACKS_CODE_FEATURES
427 EngineStateController::instance()->set_session(this);
430 if ( ARDOUR::Profile->get_trx () ) {
432 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
433 * each available input must have corresponding track when session starts.
436 uint32_t how_many (0);
438 std::vector<std::string> inputs;
439 EngineStateController::instance()->get_physical_audio_inputs(inputs);
441 how_many = inputs.size();
443 list<boost::shared_ptr<AudioTrack> > tracks;
445 // Track names after driver
446 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
447 string track_name = "";
448 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
450 track_name = inputs[i];
451 replace_all (track_name, "system:capture", "");
453 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
454 tracks.insert(tracks.begin(), single_track.front());
456 } else { // Default track names
457 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
460 if (tracks.size() != how_many) {
462 throw failed_constructor ();
471 BootMessage (_("Session loading complete"));
483 Session::next_name_id ()
485 return g_atomic_int_add (&_name_id_counter, 1);
489 Session::name_id_counter ()
491 return g_atomic_int_get (&_name_id_counter);
495 Session::init_name_id_counter (guint n)
497 g_atomic_int_set (&_name_id_counter, n);
501 Session::ensure_engine (uint32_t desired_sample_rate)
503 if (_engine.current_backend() == 0) {
504 /* backend is unknown ... */
505 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
506 if (r.get_value_or (-1) != 0) {
509 } else if (_engine.setup_required()) {
510 /* backend is known, but setup is needed */
511 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
512 if (r.get_value_or (-1) != 0) {
515 } else if (!_engine.running()) {
516 if (_engine.start()) {
521 /* at this point the engine should be running
524 if (!_engine.running()) {
528 return immediately_post_engine ();
533 Session::immediately_post_engine ()
535 /* Do various initializations that should take place directly after we
536 * know that the engine is running, but before we either create a
537 * session or set state for an existing one.
540 if (how_many_dsp_threads () > 1) {
541 /* For now, only create the graph if we are using >1 DSP threads, as
542 it is a bit slower than the old code with 1 thread.
544 _process_graph.reset (new Graph (*this));
547 /* every time we reconnect, recompute worst case output latencies */
549 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
551 if (synced_to_engine()) {
552 _engine.transport_stop ();
555 if (config.get_jack_time_master()) {
556 _engine.transport_locate (_transport_frame);
560 BootMessage (_("Set up LTC"));
562 BootMessage (_("Set up Click"));
564 BootMessage (_("Set up standard connections"));
568 catch (failed_constructor& err) {
572 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
574 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
582 vector<void*> debug_pointers;
584 /* if we got to here, leaving pending capture state around
588 remove_pending_capture_state ();
592 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
594 /* stop autoconnecting */
595 auto_connect_thread_terminate ();
597 /* disconnect from any and all signals that we are connected to */
599 Port::PortSignalDrop (); /* EMIT SIGNAL */
602 /* shutdown control surface protocols while we still have ports
603 and the engine to move data to any devices.
606 ControlProtocolManager::instance().drop_protocols ();
608 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
610 _engine.remove_session ();
612 #ifdef USE_TRACKS_CODE_FEATURES
613 EngineStateController::instance()->remove_session();
616 /* deregister all ports - there will be no process or any other
617 * callbacks from the engine any more.
620 Port::PortDrop (); /* EMIT SIGNAL */
624 /* clear history so that no references to objects are held any more */
628 /* clear state tree so that no references to objects are held any more */
633 // unregister all lua functions, drop held references (if any)
635 lua.do_command ("Session = nil");
643 lua.collect_garbage ();
645 /* reset dynamic state version back to default */
646 Stateful::loading_state_version = 0;
648 _butler->drop_references ();
652 delete _all_route_group;
654 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
655 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
659 if (click_data != default_click) {
660 delete [] click_data;
663 if (click_emphasis_data != default_click_emphasis) {
664 delete [] click_emphasis_data;
669 /* need to remove auditioner before monitoring section
670 * otherwise it is re-connected */
673 /* drop references to routes held by the monitoring section
674 * specifically _monitor_out aux/listen references */
675 remove_monitor_section();
677 /* clear out any pending dead wood from RCU managed objects */
682 AudioDiskstream::free_working_buffers();
684 /* tell everyone who is still standing that we're about to die */
687 /* tell everyone to drop references and delete objects as we go */
689 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
690 RegionFactory::delete_all_regions ();
692 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
694 /* reset these three references to special routes before we do the usual route delete thing */
696 _master_out.reset ();
697 _monitor_out.reset ();
700 RCUWriter<RouteList> writer (routes);
701 boost::shared_ptr<RouteList> r = writer.get_copy ();
703 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
704 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
705 (*i)->drop_references ();
709 /* writer goes out of scope and updates master */
714 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
715 Glib::Threads::Mutex::Lock lm (source_lock);
716 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
717 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
718 i->second->drop_references ();
724 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
727 emit_thread_terminate ();
729 pthread_cond_destroy (&_rt_emit_cond);
730 pthread_mutex_destroy (&_rt_emit_mutex);
732 pthread_cond_destroy (&_auto_connect_cond);
733 pthread_mutex_destroy (&_auto_connect_mutex);
735 delete _scene_changer; _scene_changer = 0;
736 delete midi_control_ui; midi_control_ui = 0;
738 delete _mmc; _mmc = 0;
739 delete _midi_ports; _midi_ports = 0;
740 delete _locations; _locations = 0;
744 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
746 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
747 boost_debug_list_ptrs ();
752 Session::setup_ltc ()
756 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
757 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
759 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
760 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
763 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
764 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
766 reconnect_ltc_input ();
769 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
770 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
773 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
774 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
776 reconnect_ltc_output ();
779 /* fix up names of LTC ports because we don't want the normal
780 * IO style of NAME/TYPE-{in,out}N
783 _ltc_input->nth (0)->set_name (X_("LTC-in"));
784 _ltc_output->nth (0)->set_name (X_("LTC-out"));
788 Session::setup_click ()
792 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
793 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
795 _click_io.reset (new ClickIO (*this, X_("Click")));
796 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
797 _click_gain->activate ();
799 setup_click_state (state_tree->root());
801 setup_click_state (0);
806 Session::setup_click_state (const XMLNode* node)
808 const XMLNode* child = 0;
810 if (node && (child = find_named_node (*node, "Click")) != 0) {
812 /* existing state for Click */
815 if (Stateful::loading_state_version < 3000) {
816 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
818 const XMLNodeList& children (child->children());
819 XMLNodeList::const_iterator i = children.begin();
820 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
822 if (i != children.end()) {
823 c = _click_gain->set_state (**i, Stateful::loading_state_version);
829 _clicking = Config->get_clicking ();
833 error << _("could not setup Click I/O") << endmsg;
840 /* default state for Click: dual-mono to first 2 physical outputs */
843 _engine.get_physical_outputs (DataType::AUDIO, outs);
845 for (uint32_t physport = 0; physport < 2; ++physport) {
846 if (outs.size() > physport) {
847 if (_click_io->add_port (outs[physport], this)) {
848 // relax, even though its an error
853 if (_click_io->n_ports () > ChanCount::ZERO) {
854 _clicking = Config->get_clicking ();
860 Session::setup_bundles ()
864 RCUWriter<BundleList> writer (_bundles);
865 boost::shared_ptr<BundleList> b = writer.get_copy ();
866 for (BundleList::iterator i = b->begin(); i != b->end();) {
867 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
875 vector<string> inputs[DataType::num_types];
876 vector<string> outputs[DataType::num_types];
877 for (uint32_t i = 0; i < DataType::num_types; ++i) {
878 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
879 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
882 /* Create a set of Bundle objects that map
883 to the physical I/O currently available. We create both
884 mono and stereo bundles, so that the common cases of mono
885 and stereo tracks get bundles to put in their mixer strip
886 in / out menus. There may be a nicer way of achieving that;
887 it doesn't really scale that well to higher channel counts
890 /* mono output bundles */
892 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
894 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
896 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
898 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
901 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
902 c->add_channel (_("mono"), DataType::AUDIO);
903 c->set_port (0, outputs[DataType::AUDIO][np]);
905 add_bundle (c, false);
908 /* stereo output bundles */
910 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
911 if (np + 1 < outputs[DataType::AUDIO].size()) {
913 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
914 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
915 c->add_channel (_("L"), DataType::AUDIO);
916 c->set_port (0, outputs[DataType::AUDIO][np]);
917 c->add_channel (_("R"), DataType::AUDIO);
918 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
920 add_bundle (c, false);
924 /* mono input bundles */
926 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
928 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
930 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
932 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
935 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
936 c->add_channel (_("mono"), DataType::AUDIO);
937 c->set_port (0, inputs[DataType::AUDIO][np]);
939 add_bundle (c, false);
942 /* stereo input bundles */
944 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
945 if (np + 1 < inputs[DataType::AUDIO].size()) {
947 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
949 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
950 c->add_channel (_("L"), DataType::AUDIO);
951 c->set_port (0, inputs[DataType::AUDIO][np]);
952 c->add_channel (_("R"), DataType::AUDIO);
953 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
955 add_bundle (c, false);
959 /* MIDI input bundles */
961 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
962 string n = inputs[DataType::MIDI][np];
963 std::string pn = _engine.get_pretty_name_by_name (n);
967 boost::erase_first (n, X_("alsa_pcm:"));
969 boost::shared_ptr<Bundle> c (new Bundle (n, false));
970 c->add_channel ("", DataType::MIDI);
971 c->set_port (0, inputs[DataType::MIDI][np]);
972 add_bundle (c, false);
975 /* MIDI output bundles */
977 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
978 string n = outputs[DataType::MIDI][np];
979 std::string pn = _engine.get_pretty_name_by_name (n);
983 boost::erase_first (n, X_("alsa_pcm:"));
985 boost::shared_ptr<Bundle> c (new Bundle (n, true));
986 c->add_channel ("", DataType::MIDI);
987 c->set_port (0, outputs[DataType::MIDI][np]);
988 add_bundle (c, false);
991 // we trust the backend to only calls us if there's a change
992 BundleAddedOrRemoved (); /* EMIT SIGNAL */
996 Session::auto_connect_master_bus ()
998 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1002 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1003 // In this case it means "Multi Out" output mode
1004 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1008 /* if requested auto-connect the outputs to the first N physical ports.
1011 uint32_t limit = _master_out->n_outputs().n_total();
1012 vector<string> outputs[DataType::num_types];
1014 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1015 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1018 for (uint32_t n = 0; n < limit; ++n) {
1019 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1021 if (outputs[p->type()].size() > n) {
1022 connect_to = outputs[p->type()][n];
1025 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1026 if (_master_out->output()->connect (p, connect_to, this)) {
1027 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1036 Session::remove_monitor_section ()
1038 if (!_monitor_out || Profile->get_trx()) {
1042 /* force reversion to Solo-In-Place */
1043 Config->set_solo_control_is_listen_control (false);
1045 /* if we are auditioning, cancel it ... this is a workaround
1046 to a problem (auditioning does not execute the process graph,
1047 which is needed to remove routes when using >1 core for processing)
1052 /* Hold process lock while doing this so that we don't hear bits and
1053 * pieces of audio as we work on each route.
1056 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1058 /* Connect tracks to monitor section. Note that in an
1059 existing session, the internal sends will already exist, but we want the
1060 routes to notice that they connect to the control out specifically.
1064 boost::shared_ptr<RouteList> r = routes.reader ();
1065 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1067 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1069 if ((*x)->is_monitor()) {
1071 } else if ((*x)->is_master()) {
1074 (*x)->remove_aux_or_listen (_monitor_out);
1079 remove_route (_monitor_out);
1080 if (_state_of_the_state & Deletion) {
1084 auto_connect_master_bus ();
1087 auditioner->connect ();
1090 Config->ParameterChanged ("use-monitor-bus");
1094 Session::add_monitor_section ()
1098 if (_monitor_out || !_master_out || Profile->get_trx()) {
1102 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1108 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1109 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
1112 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1113 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1114 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1116 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1121 add_routes (rl, false, false, false);
1123 assert (_monitor_out);
1125 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1126 are undefined, at best.
1129 uint32_t limit = _monitor_out->n_inputs().n_audio();
1133 /* connect the inputs to the master bus outputs. this
1134 * represents a separate data feed from the internal sends from
1135 * each route. as of jan 2011, it allows the monitor section to
1136 * conditionally ignore either the internal sends or the normal
1137 * input feed, but we should really find a better way to do
1141 _master_out->output()->disconnect (this);
1143 for (uint32_t n = 0; n < limit; ++n) {
1144 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1145 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1148 string connect_to = o->name();
1149 if (_monitor_out->input()->connect (p, connect_to, this)) {
1150 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1158 /* if monitor section is not connected, connect it to physical outs
1161 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1163 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1165 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1168 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1170 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1171 Config->get_monitor_bus_preferred_bundle())
1177 /* Monitor bus is audio only */
1179 vector<string> outputs[DataType::num_types];
1181 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1182 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1185 uint32_t mod = outputs[DataType::AUDIO].size();
1186 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1190 for (uint32_t n = 0; n < limit; ++n) {
1192 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1194 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1195 connect_to = outputs[DataType::AUDIO][n % mod];
1198 if (!connect_to.empty()) {
1199 if (_monitor_out->output()->connect (p, connect_to, this)) {
1200 error << string_compose (
1201 _("cannot connect control output %1 to %2"),
1212 /* Hold process lock while doing this so that we don't hear bits and
1213 * pieces of audio as we work on each route.
1216 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1218 /* Connect tracks to monitor section. Note that in an
1219 existing session, the internal sends will already exist, but we want the
1220 routes to notice that they connect to the control out specifically.
1224 boost::shared_ptr<RouteList> rls = routes.reader ();
1226 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1228 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1230 if ((*x)->is_monitor()) {
1232 } else if ((*x)->is_master()) {
1235 (*x)->enable_monitor_send ();
1240 auditioner->connect ();
1242 Config->ParameterChanged ("use-monitor-bus");
1246 Session::reset_monitor_section ()
1248 /* Process lock should be held by the caller.*/
1250 if (!_monitor_out || Profile->get_trx()) {
1254 uint32_t limit = _master_out->n_outputs().n_audio();
1256 /* connect the inputs to the master bus outputs. this
1257 * represents a separate data feed from the internal sends from
1258 * each route. as of jan 2011, it allows the monitor section to
1259 * conditionally ignore either the internal sends or the normal
1260 * input feed, but we should really find a better way to do
1264 _master_out->output()->disconnect (this);
1265 _monitor_out->output()->disconnect (this);
1267 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1268 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1270 for (uint32_t n = 0; n < limit; ++n) {
1271 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1272 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1275 string connect_to = o->name();
1276 if (_monitor_out->input()->connect (p, connect_to, this)) {
1277 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1284 /* connect monitor section to physical outs
1287 if (Config->get_auto_connect_standard_busses()) {
1289 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1291 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1294 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1296 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1297 Config->get_monitor_bus_preferred_bundle())
1303 /* Monitor bus is audio only */
1305 vector<string> outputs[DataType::num_types];
1307 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1308 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1311 uint32_t mod = outputs[DataType::AUDIO].size();
1312 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1316 for (uint32_t n = 0; n < limit; ++n) {
1318 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1320 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1321 connect_to = outputs[DataType::AUDIO][n % mod];
1324 if (!connect_to.empty()) {
1325 if (_monitor_out->output()->connect (p, connect_to, this)) {
1326 error << string_compose (
1327 _("cannot connect control output %1 to %2"),
1338 /* Connect tracks to monitor section. Note that in an
1339 existing session, the internal sends will already exist, but we want the
1340 routes to notice that they connect to the control out specifically.
1344 boost::shared_ptr<RouteList> rls = routes.reader ();
1346 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1348 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1350 if ((*x)->is_monitor()) {
1352 } else if ((*x)->is_master()) {
1355 (*x)->enable_monitor_send ();
1361 Session::hookup_io ()
1363 /* stop graph reordering notifications from
1364 causing resorts, etc.
1367 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1371 /* we delay creating the auditioner till now because
1372 it makes its own connections to ports.
1376 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1378 throw failed_constructor ();
1380 a->use_new_diskstream ();
1384 catch (failed_constructor& err) {
1385 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1389 /* load bundles, which we may have postponed earlier on */
1390 if (_bundle_xml_node) {
1391 load_bundles (*_bundle_xml_node);
1392 delete _bundle_xml_node;
1395 /* Tell all IO objects to connect themselves together */
1397 IO::enable_connecting ();
1399 /* Now tell all "floating" ports to connect to whatever
1400 they should be connected to.
1403 AudioEngine::instance()->reconnect_ports ();
1405 /* Anyone who cares about input state, wake up and do something */
1407 IOConnectionsComplete (); /* EMIT SIGNAL */
1409 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1411 /* now handle the whole enchilada as if it was one
1412 graph reorder event.
1417 /* update the full solo state, which can't be
1418 correctly determined on a per-route basis, but
1419 needs the global overview that only the session
1423 update_route_solo_state ();
1427 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1429 boost::shared_ptr<Track> track = wp.lock ();
1434 boost::shared_ptr<Playlist> playlist;
1436 if ((playlist = track->playlist()) != 0) {
1437 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1438 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1439 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1444 Session::record_enabling_legal () const
1446 /* this used to be in here, but survey says.... we don't need to restrict it */
1447 // if (record_status() == Recording) {
1451 if (Config->get_all_safe()) {
1458 Session::set_track_monitor_input_status (bool yn)
1460 boost::shared_ptr<RouteList> rl = routes.reader ();
1461 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1462 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1463 if (tr && tr->record_enabled ()) {
1464 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1465 tr->request_input_monitoring (yn);
1471 Session::auto_punch_start_changed (Location* location)
1473 replace_event (SessionEvent::PunchIn, location->start());
1475 if (get_record_enabled() && config.get_punch_in()) {
1476 /* capture start has been changed, so save new pending state */
1477 save_state ("", true);
1482 Session::auto_punch_end_changed (Location* location)
1484 framepos_t when_to_stop = location->end();
1485 // when_to_stop += _worst_output_latency + _worst_input_latency;
1486 replace_event (SessionEvent::PunchOut, when_to_stop);
1490 Session::auto_punch_changed (Location* location)
1492 framepos_t when_to_stop = location->end();
1494 replace_event (SessionEvent::PunchIn, location->start());
1495 //when_to_stop += _worst_output_latency + _worst_input_latency;
1496 replace_event (SessionEvent::PunchOut, when_to_stop);
1499 /** @param loc A loop location.
1500 * @param pos Filled in with the start time of the required fade-out (in session frames).
1501 * @param length Filled in with the length of the required fade-out.
1504 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1506 pos = max (loc->start(), loc->end() - 64);
1507 length = loc->end() - pos;
1511 Session::auto_loop_changed (Location* location)
1513 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1516 auto_loop_declick_range (location, dcp, dcl);
1518 if (transport_rolling() && play_loop) {
1520 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1522 // if (_transport_frame > location->end()) {
1524 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1525 // relocate to beginning of loop
1526 clear_events (SessionEvent::LocateRoll);
1528 request_locate (location->start(), true);
1531 else if (Config->get_seamless_loop() && !loop_changing) {
1533 // schedule a locate-roll to refill the diskstreams at the
1534 // previous loop end
1535 loop_changing = true;
1537 if (location->end() > last_loopend) {
1538 clear_events (SessionEvent::LocateRoll);
1539 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1545 clear_events (SessionEvent::AutoLoopDeclick);
1546 clear_events (SessionEvent::AutoLoop);
1549 /* possibly move playhead if not rolling; if we are rolling we'll move
1550 to the loop start on stop if that is appropriate.
1555 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1556 if (pos == location->start()) {
1557 request_locate (pos);
1562 last_loopend = location->end();
1567 Session::set_auto_punch_location (Location* location)
1571 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1572 punch_connections.drop_connections();
1573 existing->set_auto_punch (false, this);
1574 remove_event (existing->start(), SessionEvent::PunchIn);
1575 clear_events (SessionEvent::PunchOut);
1576 auto_punch_location_changed (0);
1581 if (location == 0) {
1585 if (location->end() <= location->start()) {
1586 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1590 punch_connections.drop_connections ();
1592 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1593 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1594 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1596 location->set_auto_punch (true, this);
1598 auto_punch_changed (location);
1600 auto_punch_location_changed (location);
1604 Session::set_session_extents (framepos_t start, framepos_t end)
1607 if ((existing = _locations->session_range_location()) == 0) {
1608 //if there is no existing session, we need to make a new session location (should never happen)
1609 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1613 error << _("Session: you can't use that location for session start/end)") << endmsg;
1617 existing->set( start, end );
1623 Session::set_auto_loop_location (Location* location)
1627 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1628 loop_connections.drop_connections ();
1629 existing->set_auto_loop (false, this);
1630 remove_event (existing->end(), SessionEvent::AutoLoop);
1633 auto_loop_declick_range (existing, dcp, dcl);
1634 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1635 auto_loop_location_changed (0);
1640 if (location == 0) {
1644 if (location->end() <= location->start()) {
1645 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1649 last_loopend = location->end();
1651 loop_connections.drop_connections ();
1653 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1654 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1655 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1656 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1658 location->set_auto_loop (true, this);
1660 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1661 // set all tracks to use internal looping
1662 boost::shared_ptr<RouteList> rl = routes.reader ();
1663 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1664 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1665 if (tr && !tr->hidden()) {
1666 tr->set_loop (location);
1671 /* take care of our stuff first */
1673 auto_loop_changed (location);
1675 /* now tell everyone else */
1677 auto_loop_location_changed (location);
1681 Session::update_marks (Location*)
1687 Session::update_skips (Location* loc, bool consolidate)
1689 if (_ignore_skips_updates) {
1693 Locations::LocationList skips;
1696 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1697 consolidate_skips (loc);
1700 sync_locations_to_skips ();
1706 Session::consolidate_skips (Location* loc)
1708 Locations::LocationList all_locations = _locations->list ();
1710 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1712 if (!(*l)->is_skip ()) {
1717 /* don't test against self */
1724 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1725 case Evoral::OverlapInternal:
1726 case Evoral::OverlapExternal:
1727 case Evoral::OverlapStart:
1728 case Evoral::OverlapEnd:
1729 /* adjust new location to cover existing one */
1730 loc->set_start (min (loc->start(), (*l)->start()));
1731 loc->set_end (max (loc->end(), (*l)->end()));
1732 /* we don't need this one any more */
1733 _locations->remove (*l);
1734 /* the location has been deleted, so remove reference to it in our local list */
1735 l = all_locations.erase (l);
1738 case Evoral::OverlapNone:
1746 Session::sync_locations_to_skips ()
1748 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1749 * Session::_sync_locations_to_skips() from the audioengine thread.
1751 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1755 Session::_sync_locations_to_skips ()
1757 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1759 Locations::LocationList const & locs (_locations->list());
1761 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1763 Location* location = *i;
1765 if (location->is_skip() && location->is_skipping()) {
1766 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1774 Session::location_added (Location *location)
1776 if (location->is_auto_punch()) {
1777 set_auto_punch_location (location);
1780 if (location->is_auto_loop()) {
1781 set_auto_loop_location (location);
1784 if (location->is_session_range()) {
1785 /* no need for any signal handling or event setting with the session range,
1786 because we keep a direct reference to it and use its start/end directly.
1788 _session_range_location = location;
1791 if (location->is_mark()) {
1792 /* listen for per-location signals that require us to do any * global updates for marks */
1794 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1795 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1796 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1797 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1800 if (location->is_skip()) {
1801 /* listen for per-location signals that require us to update skip-locate events */
1803 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1804 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1805 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1806 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1808 update_skips (location, true);
1815 Session::location_removed (Location *location)
1817 if (location->is_auto_loop()) {
1818 set_auto_loop_location (0);
1819 set_track_loop (false);
1822 if (location->is_auto_punch()) {
1823 set_auto_punch_location (0);
1826 if (location->is_session_range()) {
1827 /* this is never supposed to happen */
1828 error << _("programming error: session range removed!") << endl;
1831 if (location->is_skip()) {
1833 update_skips (location, false);
1840 Session::locations_changed ()
1842 _locations->apply (*this, &Session::_locations_changed);
1846 Session::_locations_changed (const Locations::LocationList& locations)
1848 /* There was some mass-change in the Locations object.
1850 We might be re-adding a location here but it doesn't actually matter
1851 for all the locations that the Session takes an interest in.
1855 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1856 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1857 location_added (*i);
1861 update_skips (NULL, false);
1865 Session::enable_record ()
1867 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1868 /* no recording at anything except normal speed */
1873 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1875 if (rs == Recording) {
1879 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1881 _last_record_location = _transport_frame;
1882 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1884 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1885 set_track_monitor_input_status (true);
1888 RecordStateChanged ();
1895 Session::set_all_tracks_record_enabled (bool enable )
1897 boost::shared_ptr<RouteList> rl = routes.reader();
1898 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1899 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1901 tr->set_record_enabled (enable, Controllable::NoGroup);
1908 Session::disable_record (bool rt_context, bool force)
1912 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1914 if (!Config->get_latched_record_enable () || force) {
1915 g_atomic_int_set (&_record_status, Disabled);
1916 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1918 if (rs == Recording) {
1919 g_atomic_int_set (&_record_status, Enabled);
1923 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1924 set_track_monitor_input_status (false);
1927 RecordStateChanged (); /* emit signal */
1930 remove_pending_capture_state ();
1936 Session::step_back_from_record ()
1938 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1940 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1941 set_track_monitor_input_status (false);
1944 RecordStateChanged (); /* emit signal */
1949 Session::maybe_enable_record ()
1951 if (_step_editors > 0) {
1955 g_atomic_int_set (&_record_status, Enabled);
1957 /* This function is currently called from somewhere other than an RT thread.
1958 This save_state() call therefore doesn't impact anything. Doing it here
1959 means that we save pending state of which sources the next record will use,
1960 which gives us some chance of recovering from a crash during the record.
1963 save_state ("", true);
1965 if (_transport_speed) {
1966 if (!config.get_punch_in()) {
1970 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1971 RecordStateChanged (); /* EMIT SIGNAL */
1978 Session::audible_frame () const
1984 offset = worst_playback_latency ();
1986 if (synced_to_engine()) {
1987 /* Note: this is basically just sync-to-JACK */
1988 tf = _engine.transport_frame();
1990 tf = _transport_frame;
1995 if (!non_realtime_work_pending()) {
1999 /* Check to see if we have passed the first guaranteed
2000 audible frame past our last start position. if not,
2001 return that last start point because in terms
2002 of audible frames, we have not moved yet.
2004 `Start position' in this context means the time we last
2005 either started, located, or changed transport direction.
2008 if (_transport_speed > 0.0f) {
2010 if (!play_loop || !have_looped) {
2011 if (tf < _last_roll_or_reversal_location + offset) {
2012 return _last_roll_or_reversal_location;
2020 } else if (_transport_speed < 0.0f) {
2022 /* XXX wot? no backward looping? */
2024 if (tf > _last_roll_or_reversal_location - offset) {
2025 return _last_roll_or_reversal_location;
2037 Session::set_frame_rate (framecnt_t frames_per_second)
2039 /** \fn void Session::set_frame_size(framecnt_t)
2040 the AudioEngine object that calls this guarantees
2041 that it will not be called while we are also in
2042 ::process(). Its fine to do things that block
2046 if (_base_frame_rate == 0) {
2047 _base_frame_rate = frames_per_second;
2049 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2050 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2052 _nominal_frame_rate = frames_per_second;
2057 reset_write_sources (false);
2059 // XXX we need some equivalent to this, somehow
2060 // SndFileSource::setup_standard_crossfades (frames_per_second);
2064 /* XXX need to reset/reinstantiate all LADSPA plugins */
2068 Session::set_block_size (pframes_t nframes)
2070 /* the AudioEngine guarantees
2071 that it will not be called while we are also in
2072 ::process(). It is therefore fine to do things that block
2077 current_block_size = nframes;
2081 boost::shared_ptr<RouteList> r = routes.reader ();
2083 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2084 (*i)->set_block_size (nframes);
2087 boost::shared_ptr<RouteList> rl = routes.reader ();
2088 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2089 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2091 tr->set_block_size (nframes);
2095 set_worst_io_latencies ();
2101 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2103 boost::shared_ptr<Route> r2;
2105 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2106 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2110 /* make a copy of the existing list of routes that feed r1 */
2112 Route::FedBy existing (r1->fed_by());
2114 /* for each route that feeds r1, recurse, marking it as feeding
2118 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2119 if (!(r2 = i->r.lock ())) {
2120 /* (*i) went away, ignore it */
2124 /* r2 is a route that feeds r1 which somehow feeds base. mark
2125 base as being fed by r2
2128 rbase->add_fed_by (r2, i->sends_only);
2132 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2136 if (r1->feeds (r2) && r2->feeds (r1)) {
2140 /* now recurse, so that we can mark base as being fed by
2141 all routes that feed r2
2144 trace_terminal (r2, rbase);
2151 Session::resort_routes ()
2153 /* don't do anything here with signals emitted
2154 by Routes during initial setup or while we
2155 are being destroyed.
2158 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2162 if (_route_deletion_in_progress) {
2167 RCUWriter<RouteList> writer (routes);
2168 boost::shared_ptr<RouteList> r = writer.get_copy ();
2169 resort_routes_using (r);
2170 /* writer goes out of scope and forces update */
2174 boost::shared_ptr<RouteList> rl = routes.reader ();
2175 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2176 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2178 const Route::FedBy& fb ((*i)->fed_by());
2180 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2181 boost::shared_ptr<Route> sf = f->r.lock();
2183 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2191 /** This is called whenever we need to rebuild the graph of how we will process
2193 * @param r List of routes, in any order.
2197 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2199 /* We are going to build a directed graph of our routes;
2200 this is where the edges of that graph are put.
2205 /* Go through all routes doing two things:
2207 * 1. Collect the edges of the route graph. Each of these edges
2208 * is a pair of routes, one of which directly feeds the other
2209 * either by a JACK connection or by an internal send.
2211 * 2. Begin the process of making routes aware of which other
2212 * routes directly or indirectly feed them. This information
2213 * is used by the solo code.
2216 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2218 /* Clear out the route's list of direct or indirect feeds */
2219 (*i)->clear_fed_by ();
2221 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2223 bool via_sends_only;
2225 /* See if this *j feeds *i according to the current state of the JACK
2226 connections and internal sends.
2228 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2229 /* add the edge to the graph (part #1) */
2230 edges.add (*j, *i, via_sends_only);
2231 /* tell the route (for part #2) */
2232 (*i)->add_fed_by (*j, via_sends_only);
2237 /* Attempt a topological sort of the route graph */
2238 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2240 if (sorted_routes) {
2241 /* We got a satisfactory topological sort, so there is no feedback;
2244 Note: the process graph rechain does not require a
2245 topologically-sorted list, but hey ho.
2247 if (_process_graph) {
2248 _process_graph->rechain (sorted_routes, edges);
2251 _current_route_graph = edges;
2253 /* Complete the building of the routes' lists of what directly
2254 or indirectly feeds them.
2256 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2257 trace_terminal (*i, *i);
2260 *r = *sorted_routes;
2263 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2264 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2265 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2266 (*i)->name(), (*i)->order_key ()));
2270 SuccessfulGraphSort (); /* EMIT SIGNAL */
2273 /* The topological sort failed, so we have a problem. Tell everyone
2274 and stick to the old graph; this will continue to be processed, so
2275 until the feedback is fixed, what is played back will not quite
2276 reflect what is actually connected. Note also that we do not
2277 do trace_terminal here, as it would fail due to an endless recursion,
2278 so the solo code will think that everything is still connected
2282 FeedbackDetected (); /* EMIT SIGNAL */
2287 /** Find a route name starting with \a base, maybe followed by the
2288 * lowest \a id. \a id will always be added if \a definitely_add_number
2289 * is true on entry; otherwise it will only be added if required
2290 * to make the name unique.
2292 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2293 * The available route name with the lowest ID will be used, and \a id
2294 * will be set to the ID.
2296 * \return false if a route name could not be found, and \a track_name
2297 * and \a id do not reflect a free route name.
2300 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2302 /* the base may conflict with ports that do not belong to existing
2303 routes, but hidden objects like the click track. So check port names
2304 before anything else.
2307 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2308 if (base == *reserved) {
2309 /* Check if this reserved name already exists, and if
2310 so, disallow it without a numeric suffix.
2312 if (route_by_name (*reserved)) {
2313 definitely_add_number = true;
2322 if (!definitely_add_number && route_by_name (base) == 0) {
2323 /* juse use the base */
2329 name = string_compose ("%1 %2", base, id);
2331 if (route_by_name (name) == 0) {
2337 } while (id < (UINT_MAX-1));
2342 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2344 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2346 in = ChanCount::ZERO;
2347 out = ChanCount::ZERO;
2349 boost::shared_ptr<RouteList> r = routes.reader ();
2351 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2352 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2353 if (tr && !tr->is_auditioner()) {
2354 in += tr->n_inputs();
2355 out += tr->n_outputs();
2361 Session::default_track_name_pattern (DataType t)
2364 case DataType::AUDIO:
2365 if (Profile->get_trx()) {
2372 case DataType::MIDI:
2379 /** Caller must not hold process lock
2380 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2381 * @param instrument plugin info for the instrument to insert pre-fader, if any
2383 list<boost::shared_ptr<MidiTrack> >
2384 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2385 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2388 uint32_t track_id = 0;
2390 RouteList new_routes;
2391 list<boost::shared_ptr<MidiTrack> > ret;
2393 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2394 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2397 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2398 error << "cannot find name for new midi track" << endmsg;
2402 boost::shared_ptr<MidiTrack> track;
2405 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2407 if (track->init ()) {
2411 if (Profile->get_mixbus ()) {
2412 track->set_strict_io (true);
2415 track->use_new_diskstream();
2417 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2418 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2421 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2422 if (track->input()->ensure_io (input, false, this)) {
2423 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2427 if (track->output()->ensure_io (output, false, this)) {
2428 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2433 track->non_realtime_input_change();
2436 route_group->add (track);
2439 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2441 if (Config->get_remote_model() == UserOrdered) {
2442 track->set_remote_control_id (next_control_id());
2445 new_routes.push_back (track);
2446 ret.push_back (track);
2448 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2451 catch (failed_constructor &err) {
2452 error << _("Session: could not create new midi track.") << endmsg;
2456 catch (AudioEngine::PortRegistrationFailure& pfe) {
2458 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;
2466 if (!new_routes.empty()) {
2467 StateProtector sp (this);
2468 if (Profile->get_trx()) {
2469 add_routes (new_routes, false, false, false);
2471 add_routes (new_routes, true, true, false);
2475 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2476 PluginPtr plugin = instrument->load (*this);
2477 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2478 (*r)->add_processor (p, PreFader);
2488 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument)
2491 uint32_t bus_id = 0;
2495 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2498 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2499 error << "cannot find name for new midi bus" << endmsg;
2504 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2510 if (Profile->get_mixbus ()) {
2511 bus->set_strict_io (true);
2514 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2515 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2518 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2520 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2521 error << _("cannot configure new midi bus input") << endmsg;
2526 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2527 error << _("cannot configure new midi bus output") << endmsg;
2533 route_group->add (bus);
2535 if (Config->get_remote_model() == UserOrdered) {
2536 bus->set_remote_control_id (next_control_id());
2539 ret.push_back (bus);
2540 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2544 catch (failed_constructor &err) {
2545 error << _("Session: could not create new audio route.") << endmsg;
2549 catch (AudioEngine::PortRegistrationFailure& pfe) {
2550 error << pfe.what() << endmsg;
2560 StateProtector sp (this);
2561 add_routes (ret, false, false, false);
2564 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2565 PluginPtr plugin = instrument->load (*this);
2566 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2567 (*r)->add_processor (p, PreFader);
2578 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2580 boost::shared_ptr<Route> midi_track (wmt.lock());
2586 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2588 if (change.after.n_audio() <= change.before.n_audio()) {
2592 /* new audio ports: make sure the audio goes somewhere useful,
2593 * unless the user has no-auto-connect selected.
2595 * The existing ChanCounts don't matter for this call as they are only
2596 * to do with matching input and output indices, and we are only changing
2599 auto_connect_route (midi_track, false, ChanCount(), change.before);
2603 #ifdef USE_TRACKS_CODE_FEATURES
2606 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2608 return route1->remote_control_id() < route2->remote_control_id();
2612 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2614 // it is not allowed to perform connection
2615 if (!IO::connecting_legal) {
2619 // if we are deleting routes we will call this once at the end
2620 if (_route_deletion_in_progress) {
2624 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2630 // We need to disconnect the route's inputs and outputs first
2631 // basing on autoconnect configuration
2632 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2633 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2635 ChanCount existing_inputs;
2636 ChanCount existing_outputs;
2637 count_existing_track_channels (existing_inputs, existing_outputs);
2639 //ChanCount inputs = ChanCount::ZERO;
2640 //ChanCount outputs = ChanCount::ZERO;
2642 RouteList existing_routes = *routes.reader ();
2643 existing_routes.sort (compare_routes_by_remote_id);
2646 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2648 vector<string> physinputs;
2649 vector<string> physoutputs;
2651 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2652 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2654 uint32_t input_n = 0;
2655 uint32_t output_n = 0;
2656 RouteList::iterator rIter = existing_routes.begin();
2657 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2658 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2659 for (; rIter != existing_routes.end(); ++rIter) {
2660 if (*rIter == _master_out || *rIter == _monitor_out ) {
2664 if (current_output_auto_connection == AutoConnectPhysical) {
2665 (*rIter)->amp()->deactivate();
2666 } else if (current_output_auto_connection == AutoConnectMaster) {
2667 (*rIter)->amp()->activate();
2670 if (reconnectIputs) {
2671 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2673 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2675 if (current_input_auto_connection & AutoConnectPhysical) {
2677 if ( input_n == physinputs.size() ) {
2681 string port = physinputs[input_n];
2683 if (port.empty() ) {
2684 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2687 //GZ: check this; could be heavy
2688 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2694 if (reconnectOutputs) {
2696 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2697 if (current_output_auto_connection & AutoConnectPhysical) {
2699 //GZ: check this; could be heavy
2700 (*rIter)->output()->disconnect (this);
2701 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2703 //GZ: check this; could be heavy
2704 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2706 } else if (current_output_auto_connection & AutoConnectMaster){
2708 if (!reconnect_master) {
2712 //GZ: check this; could be heavy
2713 (*rIter)->output()->disconnect (this);
2716 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2717 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2719 error << error << "Master bus is not available" << endmsg;
2724 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2725 if (current_output_auto_connection & AutoConnectPhysical) {
2727 if ( output_n == physoutputs.size() ) {
2731 string port = physoutputs[output_n];
2733 if (port.empty() ) {
2734 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2737 //GZ: check this; could be heavy
2738 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2741 } else if (current_output_auto_connection & AutoConnectMaster) {
2743 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2747 // connect to master bus
2748 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2750 if (port.empty() ) {
2751 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2755 //GZ: check this; could be heavy
2756 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2763 _master_out->output()->disconnect (this);
2764 auto_connect_master_bus ();
2769 session_routes_reconnected (); /* EMIT SIGNAL */
2773 Session::reconnect_midi_scene_ports(bool inputs)
2777 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2779 scene_in_ptr->disconnect_all ();
2781 std::vector<EngineStateController::MidiPortState> midi_port_states;
2782 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2784 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2786 for (; state_iter != midi_port_states.end(); ++state_iter) {
2787 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2788 scene_in_ptr->connect (state_iter->name);
2795 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2797 if (scene_out_ptr ) {
2798 scene_out_ptr->disconnect_all ();
2800 std::vector<EngineStateController::MidiPortState> midi_port_states;
2801 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2803 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2805 for (; state_iter != midi_port_states.end(); ++state_iter) {
2806 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2807 scene_out_ptr->connect (state_iter->name);
2815 Session::reconnect_mtc_ports ()
2817 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2823 mtc_in_ptr->disconnect_all ();
2825 std::vector<EngineStateController::MidiPortState> midi_port_states;
2826 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2828 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2830 for (; state_iter != midi_port_states.end(); ++state_iter) {
2831 if (state_iter->available && state_iter->mtc_in) {
2832 mtc_in_ptr->connect (state_iter->name);
2836 if (!_midi_ports->mtc_input_port ()->connected () &&
2837 config.get_external_sync () &&
2838 (Config->get_sync_source () == MTC) ) {
2839 config.set_external_sync (false);
2842 if ( ARDOUR::Profile->get_trx () ) {
2843 // Tracks need this signal to update timecode_source_dropdown
2844 MtcOrLtcInputPortChanged (); //emit signal
2849 Session::reconnect_mmc_ports(bool inputs)
2851 if (inputs ) { // get all enabled midi input ports
2853 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2855 mmc_in_ptr->disconnect_all ();
2856 std::vector<std::string> enabled_midi_inputs;
2857 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2859 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2861 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2862 mmc_in_ptr->connect (*port_iter);
2866 } else { // get all enabled midi output ports
2868 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2870 mmc_out_ptr->disconnect_all ();
2871 std::vector<std::string> enabled_midi_outputs;
2872 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2874 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2876 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2877 mmc_out_ptr->connect (*port_iter);
2885 /** Caller must not hold process lock
2886 * @param name_template string to use for the start of the name, or "" to use "Audio".
2888 list< boost::shared_ptr<AudioTrack> >
2889 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2890 uint32_t how_many, string name_template)
2893 uint32_t track_id = 0;
2895 RouteList new_routes;
2896 list<boost::shared_ptr<AudioTrack> > ret;
2898 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2899 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2903 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2904 error << "cannot find name for new audio track" << endmsg;
2908 boost::shared_ptr<AudioTrack> track;
2911 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2913 if (track->init ()) {
2917 if (Profile->get_mixbus ()) {
2918 track->set_strict_io (true);
2922 if (ARDOUR::Profile->get_trx ()) {
2923 // TRACKS considers it's not a USE CASE, it's
2924 // a piece of behavior of the session model:
2926 // Gain for a newly created route depends on
2927 // the current output_auto_connect mode:
2929 // 0 for Stereo Out mode
2931 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2932 track->set_gain (dB_to_coefficient (0), Controllable::NoGroup);
2936 track->use_new_diskstream();
2938 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2939 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2942 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2944 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2945 error << string_compose (
2946 _("cannot configure %1 in/%2 out configuration for new audio track"),
2947 input_channels, output_channels)
2952 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2953 error << string_compose (
2954 _("cannot configure %1 in/%2 out configuration for new audio track"),
2955 input_channels, output_channels)
2962 route_group->add (track);
2965 track->non_realtime_input_change();
2967 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2968 if (Config->get_remote_model() == UserOrdered) {
2969 track->set_remote_control_id (next_control_id());
2972 new_routes.push_back (track);
2973 ret.push_back (track);
2975 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2978 catch (failed_constructor &err) {
2979 error << _("Session: could not create new audio track.") << endmsg;
2983 catch (AudioEngine::PortRegistrationFailure& pfe) {
2985 error << pfe.what() << endmsg;
2993 if (!new_routes.empty()) {
2994 StateProtector sp (this);
2995 if (Profile->get_trx()) {
2996 add_routes (new_routes, false, false, false);
2998 add_routes (new_routes, true, true, false);
3005 /** Caller must not hold process lock.
3006 * @param name_template string to use for the start of the name, or "" to use "Bus".
3009 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
3012 uint32_t bus_id = 0;
3016 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3019 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3020 error << "cannot find name for new audio bus" << endmsg;
3025 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3031 if (Profile->get_mixbus ()) {
3032 bus->set_strict_io (true);
3035 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
3036 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
3039 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3041 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3042 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3043 input_channels, output_channels)
3049 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3050 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3051 input_channels, output_channels)
3058 route_group->add (bus);
3060 if (Config->get_remote_model() == UserOrdered) {
3061 bus->set_remote_control_id (next_control_id());
3064 bus->add_internal_return ();
3066 ret.push_back (bus);
3068 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3074 catch (failed_constructor &err) {
3075 error << _("Session: could not create new audio route.") << endmsg;
3079 catch (AudioEngine::PortRegistrationFailure& pfe) {
3080 error << pfe.what() << endmsg;
3090 StateProtector sp (this);
3091 if (Profile->get_trx()) {
3092 add_routes (ret, false, false, false);
3094 add_routes (ret, false, true, true); // autoconnect // outputs only
3103 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3107 if (!tree.read (template_path.c_str())) {
3111 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3115 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3118 uint32_t control_id;
3119 uint32_t number = 0;
3120 const uint32_t being_added = how_many;
3121 /* This will prevent the use of any existing XML-provided PBD::ID
3124 Stateful::ForceIDRegeneration force_ids;
3125 IO::disable_connecting ();
3127 control_id = next_control_id ();
3131 /* We're going to modify the node contents a bit so take a
3132 * copy. The node may be re-used when duplicating more than once.
3135 XMLNode node_copy (node);
3140 if (!name_base.empty()) {
3142 /* if we're adding more than one routes, force
3143 * all the names of the new routes to be
3144 * numbered, via the final parameter.
3147 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3148 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3154 string const route_name = node_copy.property(X_("name"))->value ();
3156 /* generate a new name by adding a number to the end of the template name */
3157 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3158 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3159 abort(); /*NOTREACHED*/
3163 /* set this name in the XML description that we are about to use */
3165 bool rename_playlist;
3168 rename_playlist = true;
3172 rename_playlist = false;
3175 Route::set_name_in_state (node_copy, name, rename_playlist);
3177 /* trim bitslots from listen sends so that new ones are used */
3178 XMLNodeList children = node_copy.children ();
3179 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3180 if ((*i)->name() == X_("Processor")) {
3181 XMLProperty* role = (*i)->property (X_("role"));
3182 if (role && role->value() == X_("Listen")) {
3183 (*i)->remove_property (X_("bitslot"));
3188 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3191 error << _("Session: cannot create track/bus from template description") << endmsg;
3195 if (boost::dynamic_pointer_cast<Track>(route)) {
3196 /* force input/output change signals so that the new diskstream
3197 picks up the configuration of the route. During session
3198 loading this normally happens in a different way.
3201 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3203 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3204 change.after = route->input()->n_ports();
3205 route->input()->changed (change, this);
3206 change.after = route->output()->n_ports();
3207 route->output()->changed (change, this);
3210 route->set_remote_control_id (control_id);
3213 boost::shared_ptr<Track> track;
3215 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3218 track->use_new_playlist ();
3221 track->use_copy_playlist ();
3228 ret.push_back (route);
3230 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3233 catch (failed_constructor &err) {
3234 error << _("Session: could not create new route from template") << endmsg;
3238 catch (AudioEngine::PortRegistrationFailure& pfe) {
3239 error << pfe.what() << endmsg;
3248 StateProtector sp (this);
3249 if (Profile->get_trx()) {
3250 add_routes (ret, false, false, false);
3252 add_routes (ret, true, true, false);
3254 IO::enable_connecting ();
3261 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3264 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3265 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3268 error << _("Adding new tracks/busses failed") << endmsg;
3273 update_latency (true);
3274 update_latency (false);
3279 save_state (_current_snapshot_name);
3282 reassign_track_numbers();
3284 update_route_record_state ();
3286 RouteAdded (new_routes); /* EMIT SIGNAL */
3290 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3292 ChanCount existing_inputs;
3293 ChanCount existing_outputs;
3294 uint32_t order = next_control_id();
3297 if (_order_hint > -1) {
3298 order = _order_hint;
3302 count_existing_track_channels (existing_inputs, existing_outputs);
3305 RCUWriter<RouteList> writer (routes);
3306 boost::shared_ptr<RouteList> r = writer.get_copy ();
3307 r->insert (r->end(), new_routes.begin(), new_routes.end());
3309 /* if there is no control out and we're not in the middle of loading,
3310 * resort the graph here. if there is a control out, we will resort
3311 * toward the end of this method. if we are in the middle of loading,
3312 * we will resort when done.
3315 if (!_monitor_out && IO::connecting_legal) {
3316 resort_routes_using (r);
3320 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3322 boost::weak_ptr<Route> wpr (*x);
3323 boost::shared_ptr<Route> r (*x);
3325 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
3326 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3327 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3328 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3329 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3330 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3332 if (r->is_master()) {
3336 if (r->is_monitor()) {
3340 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3342 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3343 track_playlist_changed (boost::weak_ptr<Track> (tr));
3344 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3346 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3348 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3349 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3353 if (input_auto_connect || output_auto_connect) {
3354 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3355 existing_inputs += r->n_inputs();
3356 existing_outputs += r->n_outputs();
3359 /* order keys are a GUI responsibility but we need to set up
3360 reasonable defaults because they also affect the remote control
3361 ID in most situations.
3364 if (!r->has_order_key ()) {
3365 if (r->is_auditioner()) {
3366 /* use an arbitrarily high value */
3367 r->set_order_key (UINT_MAX);
3369 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3370 r->set_order_key (order);
3378 if (_monitor_out && IO::connecting_legal) {
3379 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3381 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3382 if ((*x)->is_monitor()) {
3384 } else if ((*x)->is_master()) {
3387 (*x)->enable_monitor_send ();
3394 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3396 boost::shared_ptr<RouteList> r = routes.reader ();
3397 boost::shared_ptr<Send> s;
3399 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3400 if ((s = (*i)->internal_send_for (dest)) != 0) {
3401 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3407 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3409 boost::shared_ptr<RouteList> r = routes.reader ();
3410 boost::shared_ptr<Send> s;
3412 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3413 if ((s = (*i)->internal_send_for (dest)) != 0) {
3414 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3420 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3422 boost::shared_ptr<RouteList> r = routes.reader ();
3423 boost::shared_ptr<Send> s;
3425 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3426 if ((s = (*i)->internal_send_for (dest)) != 0) {
3427 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3432 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3434 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3436 boost::shared_ptr<RouteList> r = routes.reader ();
3437 boost::shared_ptr<RouteList> t (new RouteList);
3439 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3440 /* no MIDI sends because there are no MIDI busses yet */
3441 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3446 add_internal_sends (dest, p, t);
3450 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3452 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3453 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3458 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3460 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3464 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3466 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3470 if (!dest->internal_return()) {
3471 dest->add_internal_return ();
3474 sender->add_aux_send (dest, before);
3481 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3483 { // RCU Writer scope
3484 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3485 RCUWriter<RouteList> writer (routes);
3486 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3489 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3491 if (*iter == _master_out) {
3495 (*iter)->set_solo (false, Controllable::NoGroup);
3499 /* deleting the master out seems like a dumb
3500 idea, but its more of a UI policy issue
3504 if (*iter == _master_out) {
3505 _master_out = boost::shared_ptr<Route> ();
3508 if (*iter == _monitor_out) {
3509 _monitor_out.reset ();
3512 // We need to disconnect the route's inputs and outputs
3514 (*iter)->input()->disconnect (0);
3515 (*iter)->output()->disconnect (0);
3517 /* if the route had internal sends sending to it, remove them */
3518 if ((*iter)->internal_return()) {
3520 boost::shared_ptr<RouteList> r = routes.reader ();
3521 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3522 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3524 (*i)->remove_processor (s);
3529 /* if the monitoring section had a pointer to this route, remove it */
3530 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3531 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3532 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3533 (*iter)->remove_aux_or_listen (_monitor_out);
3536 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3537 if (mt && mt->step_editing()) {
3538 if (_step_editors > 0) {
3544 /* writer goes out of scope, forces route list update */
3546 } // end of RCU Writer scope
3548 update_route_solo_state ();
3549 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3550 update_latency_compensation ();
3553 /* Re-sort routes to remove the graph's current references to the one that is
3554 * going away, then flush old references out of the graph.
3555 * Wave Tracks: reconnect routes
3558 #ifdef USE_TRACKS_CODE_FEATURES
3559 reconnect_existing_routes(true, false);
3561 routes.flush (); // maybe unsafe, see below.
3565 if (_process_graph && !(_state_of_the_state & Deletion)) {
3566 _process_graph->clear_other_chain ();
3569 /* get rid of it from the dead wood collection in the route list manager */
3570 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3574 /* try to cause everyone to drop their references
3575 * and unregister ports from the backend
3578 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3579 (*iter)->drop_references ();
3582 if (_state_of_the_state & Deletion) {
3586 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3588 /* save the new state of the world */
3590 if (save_state (_current_snapshot_name)) {
3591 save_history (_current_snapshot_name);
3594 reassign_track_numbers();
3595 update_route_record_state ();
3599 Session::remove_route (boost::shared_ptr<Route> route)
3601 boost::shared_ptr<RouteList> rl (new RouteList);
3602 rl->push_back (route);
3607 Session::route_mute_changed ()
3613 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3615 boost::shared_ptr<Route> route = wpr.lock();
3617 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_listen_changed")) << endmsg;
3621 if (route->listening_via_monitor ()) {
3623 if (Config->get_exclusive_solo()) {
3625 RouteGroup* rg = route->route_group ();
3626 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3628 boost::shared_ptr<RouteList> r = routes.reader ();
3630 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3631 if ((*i) == route) {
3632 /* already changed */
3636 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3637 /* route does not get solo propagated to it */
3641 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3642 /* this route is a part of the same solo group as the route
3643 * that was changed. Changing that route did change or will
3644 * change all group members appropriately, so we can ignore it
3649 (*i)->set_listen (false, Controllable::NoGroup);
3655 } else if (_listen_cnt > 0) {
3660 update_route_solo_state ();
3663 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3665 boost::shared_ptr<Route> route = wpr.lock ();
3668 /* should not happen */
3669 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_isolated_changed")) << endmsg;
3673 bool send_changed = false;
3675 if (route->solo_isolated()) {
3676 if (_solo_isolated_cnt == 0) {
3677 send_changed = true;
3679 _solo_isolated_cnt++;
3680 } else if (_solo_isolated_cnt > 0) {
3681 _solo_isolated_cnt--;
3682 if (_solo_isolated_cnt == 0) {
3683 send_changed = true;
3688 IsolatedChanged (); /* EMIT SIGNAL */
3693 Session::route_solo_changed (bool self_solo_change, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3695 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3697 if (!self_solo_change) {
3698 // session doesn't care about changes to soloed-by-others
3702 boost::shared_ptr<Route> route = wpr.lock ();
3705 boost::shared_ptr<RouteList> r = routes.reader ();
3708 if (route->self_soloed()) {
3714 /* the route may be a member of a group that has shared-solo
3715 * semantics. If so, then all members of that group should follow the
3716 * solo of the changed route. But ... this is optional, controlled by a
3717 * Controllable::GroupControlDisposition.
3719 * The first argument to the signal that this method is connected to is the
3720 * GroupControlDisposition value that was used to change solo.
3722 * If the solo change was done with group semantics (either InverseGroup
3723 * (force the entire group to change even if the group shared solo is
3724 * disabled) or UseGroup (use the group, which may or may not have the
3725 * shared solo property enabled)) then as we propagate the change to
3726 * the entire session we should IGNORE THE GROUP that the changed route
3730 RouteGroup* rg = route->route_group ();
3731 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3733 if (delta == 1 && Config->get_exclusive_solo()) {
3735 /* new solo: disable all other solos, but not the group if its solo-enabled */
3737 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3739 if ((*i) == route) {
3740 /* already changed */
3744 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3745 /* route does not get solo propagated to it */
3749 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3750 /* this route is a part of the same solo group as the route
3751 * that was changed. Changing that route did change or will
3752 * change all group members appropriately, so we can ignore it
3758 (*i)->set_solo (false, group_override);
3762 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3764 RouteList uninvolved;
3766 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3768 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3769 bool via_sends_only;
3770 bool in_signal_flow;
3772 if ((*i) == route) {
3773 /* already changed */
3777 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3778 /* route does not get solo propagated to it */
3782 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3783 /* this route is a part of the same solo group as the route
3784 * that was changed. Changing that route did change or will
3785 * change all group members appropriately, so we can ignore it
3791 in_signal_flow = false;
3793 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3795 if ((*i)->feeds (route, &via_sends_only)) {
3796 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3797 if (!via_sends_only) {
3798 if (!route->soloed_by_others_upstream()) {
3799 (*i)->mod_solo_by_others_downstream (delta);
3801 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3804 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3806 in_signal_flow = true;
3808 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3811 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3813 if (route->feeds (*i, &via_sends_only)) {
3814 /* propagate solo upstream only if routing other than
3815 sends is involved, but do consider the other route
3816 (*i) to be part of the signal flow even if only
3819 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3823 route->soloed_by_others_downstream(),
3824 route->soloed_by_others_upstream()));
3825 if (!via_sends_only) {
3826 //NB. Triggers Invert Push, which handles soloed by downstream
3827 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3828 (*i)->mod_solo_by_others_upstream (delta);
3830 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3832 in_signal_flow = true;
3834 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3837 if (!in_signal_flow) {
3838 uninvolved.push_back (*i);
3842 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3844 update_route_solo_state (r);
3846 /* now notify that the mute state of the routes not involved in the signal
3847 pathway of the just-solo-changed route may have altered.
3850 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3851 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3852 (*i)->act_on_mute ();
3853 (*i)->mute_changed ();
3856 SoloChanged (); /* EMIT SIGNAL */
3861 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3863 /* now figure out if anything that matters is soloed (or is "listening")*/
3865 bool something_soloed = false;
3866 bool something_listening = false;
3867 uint32_t listeners = 0;
3868 uint32_t isolated = 0;
3871 r = routes.reader();
3874 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3875 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3876 something_soloed = true;
3879 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3880 if (Config->get_solo_control_is_listen_control()) {
3882 something_listening = true;
3884 (*i)->set_listen (false, Controllable::NoGroup);
3888 if ((*i)->solo_isolated()) {
3893 if (something_soloed != _non_soloed_outs_muted) {
3894 _non_soloed_outs_muted = something_soloed;
3895 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3898 if (something_listening != _listening) {
3899 _listening = something_listening;
3900 SoloActive (_listening);
3903 _listen_cnt = listeners;
3905 if (isolated != _solo_isolated_cnt) {
3906 _solo_isolated_cnt = isolated;
3907 IsolatedChanged (); /* EMIT SIGNAL */
3910 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3911 something_soloed, listeners, isolated));
3914 boost::shared_ptr<RouteList>
3915 Session::get_routes_with_internal_returns() const
3917 boost::shared_ptr<RouteList> r = routes.reader ();
3918 boost::shared_ptr<RouteList> rl (new RouteList);
3920 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3921 if ((*i)->internal_return ()) {
3929 Session::io_name_is_legal (const std::string& name)
3931 boost::shared_ptr<RouteList> r = routes.reader ();
3933 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
3934 if (name == *reserved) {
3935 if (!route_by_name (*reserved)) {
3936 /* first instance of a reserved name is allowed */
3939 /* all other instances of a reserved name are not allowed */
3944 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3945 if ((*i)->name() == name) {
3949 if ((*i)->has_io_processor_named (name)) {
3958 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3961 vector<string> connections;
3963 /* if we are passed only a single route and we're not told to turn
3964 * others off, then just do the simple thing.
3967 if (flip_others == false && rl->size() == 1) {
3968 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3970 mt->set_input_active (onoff);
3975 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3977 PortSet& ps ((*rt)->input()->ports());
3979 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3980 p->get_connections (connections);
3983 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3984 routes_using_input_from (*s, rl2);
3987 /* scan all relevant routes to see if others are on or off */
3989 bool others_are_already_on = false;
3991 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3993 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3999 if ((*r) != (*rt)) {
4000 if (mt->input_active()) {
4001 others_are_already_on = true;
4004 /* this one needs changing */
4005 mt->set_input_active (onoff);
4011 /* globally reverse other routes */
4013 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4014 if ((*r) != (*rt)) {
4015 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4017 mt->set_input_active (!others_are_already_on);
4026 Session::routes_using_input_from (const string& str, RouteList& rl)
4028 boost::shared_ptr<RouteList> r = routes.reader();
4030 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4031 if ((*i)->input()->connected_to (str)) {
4037 boost::shared_ptr<Route>
4038 Session::route_by_name (string name)
4040 boost::shared_ptr<RouteList> r = routes.reader ();
4042 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4043 if ((*i)->name() == name) {
4048 return boost::shared_ptr<Route> ((Route*) 0);
4051 boost::shared_ptr<Route>
4052 Session::route_by_id (PBD::ID id)
4054 boost::shared_ptr<RouteList> r = routes.reader ();
4056 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4057 if ((*i)->id() == id) {
4062 return boost::shared_ptr<Route> ((Route*) 0);
4065 boost::shared_ptr<Processor>
4066 Session::processor_by_id (PBD::ID id) const
4068 boost::shared_ptr<RouteList> r = routes.reader ();
4070 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4071 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4077 return boost::shared_ptr<Processor> ();
4080 boost::shared_ptr<Track>
4081 Session::track_by_diskstream_id (PBD::ID id)
4083 boost::shared_ptr<RouteList> r = routes.reader ();
4085 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4086 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4087 if (t && t->using_diskstream_id (id)) {
4092 return boost::shared_ptr<Track> ();
4095 boost::shared_ptr<Route>
4096 Session::route_by_remote_id (uint32_t id)
4098 boost::shared_ptr<RouteList> r = routes.reader ();
4100 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4101 if ((*i)->remote_control_id() == id) {
4106 return boost::shared_ptr<Route> ((Route*) 0);
4110 boost::shared_ptr<Route>
4111 Session::route_by_selected_count (uint32_t id)
4113 boost::shared_ptr<RouteList> r = routes.reader ();
4115 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4116 /* NOT IMPLEMENTED */
4119 return boost::shared_ptr<Route> ((Route*) 0);
4124 Session::reassign_track_numbers ()
4128 RouteList r (*(routes.reader ()));
4129 SignalOrderRouteSorter sorter;
4132 StateProtector sp (this);
4134 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4135 if (boost::dynamic_pointer_cast<Track> (*i)) {
4136 (*i)->set_track_number(++tn);
4138 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4139 (*i)->set_track_number(--bn);
4142 const uint32_t decimals = ceilf (log10f (tn + 1));
4143 const bool decimals_changed = _track_number_decimals != decimals;
4144 _track_number_decimals = decimals;
4146 if (decimals_changed && config.get_track_name_number ()) {
4147 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4148 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4150 t->resync_track_name();
4153 // trigger GUI re-layout
4154 config.ParameterChanged("track-name-number");
4159 Session::playlist_region_added (boost::weak_ptr<Region> w)
4161 boost::shared_ptr<Region> r = w.lock ();
4166 /* These are the operations that are currently in progress... */
4167 list<GQuark> curr = _current_trans_quarks;
4170 /* ...and these are the operations during which we want to update
4171 the session range location markers.
4174 ops.push_back (Operations::capture);
4175 ops.push_back (Operations::paste);
4176 ops.push_back (Operations::duplicate_region);
4177 ops.push_back (Operations::insert_file);
4178 ops.push_back (Operations::insert_region);
4179 ops.push_back (Operations::drag_region_brush);
4180 ops.push_back (Operations::region_drag);
4181 ops.push_back (Operations::selection_grab);
4182 ops.push_back (Operations::region_fill);
4183 ops.push_back (Operations::fill_selection);
4184 ops.push_back (Operations::create_region);
4185 ops.push_back (Operations::region_copy);
4186 ops.push_back (Operations::fixed_time_region_copy);
4189 /* See if any of the current operations match the ones that we want */
4191 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4193 /* If so, update the session range markers */
4195 maybe_update_session_range (r->position (), r->last_frame ());
4199 /** Update the session range markers if a is before the current start or
4200 * b is after the current end.
4203 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4205 if (_state_of_the_state & Loading) {
4209 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4211 if (_session_range_location == 0) {
4213 set_session_range_location (a, b + session_end_marker_shift_samples);
4217 if (a < _session_range_location->start()) {
4218 _session_range_location->set_start (a);
4221 if (b > _session_range_location->end()) {
4222 _session_range_location->set_end (b);
4228 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4230 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4231 maybe_update_session_range (i->to, i->to + i->length);
4236 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4238 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4239 maybe_update_session_range (i->from, i->to);
4243 /* Region management */
4245 boost::shared_ptr<Region>
4246 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4248 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4249 RegionFactory::RegionMap::const_iterator i;
4250 boost::shared_ptr<Region> region;
4252 Glib::Threads::Mutex::Lock lm (region_lock);
4254 for (i = regions.begin(); i != regions.end(); ++i) {
4258 if (region->whole_file()) {
4260 if (child->source_equivalent (region)) {
4266 return boost::shared_ptr<Region> ();
4270 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4272 set<boost::shared_ptr<Region> > relevant_regions;
4274 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4275 RegionFactory::get_regions_using_source (*s, relevant_regions);
4278 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4279 set<boost::shared_ptr<Region> >::iterator tmp;
4284 playlists->destroy_region (*r);
4285 RegionFactory::map_remove (*r);
4287 (*r)->drop_sources ();
4288 (*r)->drop_references ();
4290 relevant_regions.erase (r);
4295 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4298 Glib::Threads::Mutex::Lock ls (source_lock);
4299 /* remove from the main source list */
4300 sources.erase ((*s)->id());
4303 (*s)->mark_for_remove ();
4304 (*s)->drop_references ();
4313 Session::remove_last_capture ()
4315 list<boost::shared_ptr<Source> > srcs;
4317 boost::shared_ptr<RouteList> rl = routes.reader ();
4318 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4319 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4324 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4327 srcs.insert (srcs.end(), l.begin(), l.end());
4332 destroy_sources (srcs);
4334 save_state (_current_snapshot_name);
4339 /* Source Management */
4342 Session::add_source (boost::shared_ptr<Source> source)
4344 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4345 pair<SourceMap::iterator,bool> result;
4347 entry.first = source->id();
4348 entry.second = source;
4351 Glib::Threads::Mutex::Lock lm (source_lock);
4352 result = sources.insert (entry);
4355 if (result.second) {
4357 /* yay, new source */
4359 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4362 if (!fs->within_session()) {
4363 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4369 boost::shared_ptr<AudioFileSource> afs;
4371 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4372 if (Config->get_auto_analyse_audio()) {
4373 Analyser::queue_source_for_analysis (source, false);
4377 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4382 Session::remove_source (boost::weak_ptr<Source> src)
4384 if (_state_of_the_state & Deletion) {
4388 SourceMap::iterator i;
4389 boost::shared_ptr<Source> source = src.lock();
4396 Glib::Threads::Mutex::Lock lm (source_lock);
4398 if ((i = sources.find (source->id())) != sources.end()) {
4403 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4405 /* save state so we don't end up with a session file
4406 referring to non-existent sources.
4409 save_state (_current_snapshot_name);
4413 boost::shared_ptr<Source>
4414 Session::source_by_id (const PBD::ID& id)
4416 Glib::Threads::Mutex::Lock lm (source_lock);
4417 SourceMap::iterator i;
4418 boost::shared_ptr<Source> source;
4420 if ((i = sources.find (id)) != sources.end()) {
4427 boost::shared_ptr<AudioFileSource>
4428 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4430 /* Restricted to audio files because only audio sources have channel
4434 Glib::Threads::Mutex::Lock lm (source_lock);
4436 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4437 boost::shared_ptr<AudioFileSource> afs
4438 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4440 if (afs && afs->path() == path && chn == afs->channel()) {
4445 return boost::shared_ptr<AudioFileSource>();
4448 boost::shared_ptr<MidiSource>
4449 Session::midi_source_by_path (const std::string& path) const
4451 /* Restricted to MIDI files because audio sources require a channel
4452 for unique identification, in addition to a path.
4455 Glib::Threads::Mutex::Lock lm (source_lock);
4457 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4458 boost::shared_ptr<MidiSource> ms
4459 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4460 boost::shared_ptr<FileSource> fs
4461 = boost::dynamic_pointer_cast<FileSource>(s->second);
4463 if (ms && fs && fs->path() == path) {
4468 return boost::shared_ptr<MidiSource>();
4472 Session::count_sources_by_origin (const string& path)
4475 Glib::Threads::Mutex::Lock lm (source_lock);
4477 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4478 boost::shared_ptr<FileSource> fs
4479 = boost::dynamic_pointer_cast<FileSource>(i->second);
4481 if (fs && fs->origin() == path) {
4490 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4492 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4493 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4495 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4500 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4502 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4504 if (Glib::path_is_absolute (filepath)) {
4506 /* rip the session dir from the audiofile source */
4508 string session_path;
4509 bool in_another_session = true;
4511 if (filepath.find (interchange_dir_string) != string::npos) {
4513 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4514 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4515 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4516 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4518 /* see if it is within our session */
4520 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4521 if (i->path == session_path) {
4522 in_another_session = false;
4527 in_another_session = false;
4531 if (in_another_session) {
4532 SessionDirectory sd (session_path);
4533 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4537 /* 1) if file belongs to this session
4538 * it may be a relative path (interchange/...)
4539 * or just basename (session_state, remove source)
4540 * -> just use the basename
4542 std::string filename = Glib::path_get_basename (filepath);
4545 /* 2) if the file is outside our session dir:
4546 * (imported but not copied) add the path for check-summming */
4548 path = Glib::path_get_dirname (filepath);
4551 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4555 Session::new_audio_source_path_for_embedded (const std::string& path)
4559 * we know that the filename is already unique because it exists
4560 * out in the filesystem.
4562 * However, when we bring it into the session, we could get a
4565 * Eg. two embedded files:
4570 * When merged into session, these collide.
4572 * There will not be a conflict with in-memory sources
4573 * because when the source was created we already picked
4574 * a unique name for it.
4576 * This collision is not likely to be common, but we have to guard
4577 * against it. So, if there is a collision, take the md5 hash of the
4578 * the path, and use that as the filename instead.
4581 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4582 string base = Glib::path_get_basename (path);
4583 string newpath = Glib::build_filename (sdir.sound_path(), base);
4585 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4589 md5.digestString (path.c_str());
4590 md5.writeToString ();
4591 base = md5.digestChars;
4593 string ext = get_suffix (path);
4600 newpath = Glib::build_filename (sdir.sound_path(), base);
4602 /* if this collides, we're screwed */
4604 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4605 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4614 /** Return true if there are no audio file sources that use @param name as
4615 * the filename component of their path.
4617 * Return false otherwise.
4619 * This method MUST ONLY be used to check in-session, mono files since it
4620 * hard-codes the channel of the audio file source we are looking for as zero.
4622 * If/when Ardour supports native files in non-mono formats, the logic here
4623 * will need to be revisited.
4626 Session::audio_source_name_is_unique (const string& name)
4628 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4629 vector<space_and_path>::iterator i;
4630 uint32_t existing = 0;
4632 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4634 /* note that we search *without* the extension so that
4635 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4636 in the event that this new name is required for
4637 a file format change.
4640 const string spath = *i;
4642 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4647 /* it is possible that we have the path already
4648 * assigned to a source that has not yet been written
4649 * (ie. the write source for a diskstream). we have to
4650 * check this in order to make sure that our candidate
4651 * path isn't used again, because that can lead to
4652 * two Sources point to the same file with different
4653 * notions of their removability.
4657 string possible_path = Glib::build_filename (spath, name);
4659 if (audio_source_by_path_and_channel (possible_path, 0)) {
4665 return (existing == 0);
4669 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)
4672 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4674 if (Profile->get_trx() && destructive) {
4676 sstr << setfill ('0') << setw (4) << cnt;
4677 sstr << legalized_base;
4679 sstr << legalized_base;
4681 if (take_required || related_exists) {
4693 } else if (nchan > 2) {
4698 /* XXX what? more than 26 channels! */
4709 /** Return a unique name based on \a base for a new internal audio source */
4711 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4714 string possible_name;
4715 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4717 bool some_related_source_name_exists = false;
4719 legalized = legalize_for_path (base);
4721 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4723 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4725 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4727 if (audio_source_name_is_unique (possible_name)) {
4731 some_related_source_name_exists = true;
4734 error << string_compose(
4735 _("There are already %1 recordings for %2, which I consider too many."),
4736 limit, base) << endmsg;
4738 throw failed_constructor();
4742 /* We've established that the new name does not exist in any session
4743 * directory, so now find out which one we should use for this new
4747 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4749 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4754 /** Return a unique name based on `base` for a new internal MIDI source */
4756 Session::new_midi_source_path (const string& base)
4759 char buf[PATH_MAX+1];
4760 const uint32_t limit = 10000;
4762 string possible_path;
4763 string possible_name;
4766 legalized = legalize_for_path (base);
4768 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4769 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4771 /* - the main session folder is the first in the vector.
4772 * - after checking all locations for file-name uniqueness,
4773 * we keep the one from the last iteration as new file name
4774 * - midi files are small and should just be kept in the main session-folder
4776 * -> reverse the array, check main session folder last and use that as location
4779 std::reverse(sdirs.begin(), sdirs.end());
4781 for (cnt = 1; cnt <= limit; ++cnt) {
4783 vector<space_and_path>::iterator i;
4784 uint32_t existing = 0;
4786 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4788 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4789 possible_name = buf;
4791 possible_path = Glib::build_filename (*i, possible_name);
4793 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4797 if (midi_source_by_path (possible_path)) {
4802 if (existing == 0) {
4807 error << string_compose(
4808 _("There are already %1 recordings for %2, which I consider too many."),
4809 limit, base) << endmsg;
4815 /* No need to "find best location" for software/app-based RAID, because
4816 MIDI is so small that we always put it in the same place.
4819 return possible_path;
4823 /** Create a new within-session audio source */
4824 boost::shared_ptr<AudioFileSource>
4825 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4827 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4829 if (!path.empty()) {
4830 return boost::dynamic_pointer_cast<AudioFileSource> (
4831 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4833 throw failed_constructor ();
4837 /** Create a new within-session MIDI source */
4838 boost::shared_ptr<MidiSource>
4839 Session::create_midi_source_for_session (string const & basic_name)
4841 const string path = new_midi_source_path (basic_name);
4843 if (!path.empty()) {
4844 return boost::dynamic_pointer_cast<SMFSource> (
4845 SourceFactory::createWritable (
4846 DataType::MIDI, *this, path, false, frame_rate()));
4848 throw failed_constructor ();
4852 /** Create a new within-session MIDI source */
4853 boost::shared_ptr<MidiSource>
4854 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4856 /* the caller passes in the track the source will be used in,
4857 so that we can keep the numbering sane.
4859 Rationale: a track with the name "Foo" that has had N
4860 captures carried out so far will ALREADY have a write source
4861 named "Foo-N+1.mid" waiting to be used for the next capture.
4863 If we call new_midi_source_name() we will get "Foo-N+2". But
4864 there is no region corresponding to "Foo-N+1", so when
4865 "Foo-N+2" appears in the track, the gap presents the user
4866 with odd behaviour - why did it skip past Foo-N+1?
4868 We could explain this to the user in some odd way, but
4869 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4872 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4875 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4877 std::string name = track->steal_write_source_name ();
4880 return boost::shared_ptr<MidiSource>();
4883 /* MIDI files are small, just put them in the first location of the
4884 session source search path.
4887 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4889 return boost::dynamic_pointer_cast<SMFSource> (
4890 SourceFactory::createWritable (
4891 DataType::MIDI, *this, path, false, frame_rate()));
4896 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4898 if (playlist->hidden()) {
4902 playlists->add (playlist);
4905 playlist->release();
4912 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4914 if (_state_of_the_state & Deletion) {
4918 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4924 playlists->remove (playlist);
4930 Session::set_audition (boost::shared_ptr<Region> r)
4932 pending_audition_region = r;
4933 add_post_transport_work (PostTransportAudition);
4934 _butler->schedule_transport_work ();
4938 Session::audition_playlist ()
4940 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4941 ev->region.reset ();
4947 Session::register_lua_function (
4948 const std::string& name,
4949 const std::string& script,
4950 const LuaScriptParamList& args
4953 Glib::Threads::Mutex::Lock lm (lua_lock);
4955 lua_State* L = lua.getState();
4957 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
4958 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
4959 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
4960 if ((*i)->optional && !(*i)->is_set) { continue; }
4961 tbl_arg[(*i)->name] = (*i)->value;
4963 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
4968 Session::unregister_lua_function (const std::string& name)
4970 Glib::Threads::Mutex::Lock lm (lua_lock);
4971 (*_lua_del)(name); // throws luabridge::LuaException
4972 lua.collect_garbage ();
4976 std::vector<std::string>
4977 Session::registered_lua_functions ()
4979 Glib::Threads::Mutex::Lock lm (lua_lock);
4980 std::vector<std::string> rv;
4983 luabridge::LuaRef list ((*_lua_list)());
4984 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
4985 if (!i.key ().isString ()) { assert(0); continue; }
4986 rv.push_back (i.key ().cast<std::string> ());
4988 } catch (luabridge::LuaException const& e) { }
4993 static void _lua_print (std::string s) {
4994 std::cout << "SessionLua: " << s << "\n";
4999 Session::try_run_lua (pframes_t nframes)
5001 if (_n_lua_scripts == 0) return;
5002 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
5004 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
5009 Session::setup_lua ()
5012 lua.Print.connect (&_lua_print);
5015 "function ArdourSession ()"
5016 " local self = { scripts = {}, instances = {} }"
5018 " local remove = function (n)"
5019 " self.scripts[n] = nil"
5020 " self.instances[n] = nil"
5021 " Session:scripts_changed()" // call back
5024 " local addinternal = function (n, f, a)"
5025 " assert(type(n) == 'string', 'function-name must be string')"
5026 " assert(type(f) == 'function', 'Given script is a not a function')"
5027 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5028 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5029 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5030 " 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"
5031 " local env = { print = print, Session = Session, 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 }"
5032 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5033 " Session:scripts_changed()" // call back
5036 " local add = function (n, b, a)"
5037 " assert(type(b) == 'string', 'ByteCode must be string')"
5038 " load (b)()" // assigns f
5039 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5040 " addinternal (n, load(f), a)"
5043 " local run = function (...)"
5044 " for n, s in pairs (self.instances) do"
5045 " local status, err = pcall (s, ...)"
5046 " if not status then"
5047 " print ('fn \"'.. n .. '\": ', err)"
5054 " local cleanup = function ()"
5055 " self.scripts = nil"
5056 " self.instances = nil"
5059 " local list = function ()"
5061 " for n, _ in pairs (self.scripts) do"
5067 " local function basic_serialize (o)"
5068 " if type(o) == \"number\" then"
5069 " return tostring(o)"
5071 " return string.format(\"%q\", o)"
5075 " local function serialize (name, value)"
5076 " local rv = name .. ' = '"
5078 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5079 " return rv .. basic_serialize(value) .. ' '"
5080 " elseif type(value) == \"table\" then"
5082 " for k,v in pairs(value) do"
5083 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5084 " rv = rv .. serialize(fieldname, v) .. ' '"
5085 " collectgarbage()" // string concatenation allocates a new string :(
5088 " elseif type(value) == \"function\" then"
5089 " return rv .. string.format(\"%q\", string.dump(value, true))"
5091 " error('cannot save a ' .. type(value))"
5096 " local save = function ()"
5097 " return (serialize('scripts', self.scripts))"
5100 " local restore = function (state)"
5101 " self.scripts = {}"
5103 " for n, s in pairs (scripts) do"
5104 " addinternal (n, load(s['f']), s['a'])"
5108 " return { run = run, add = add, remove = remove,"
5109 " list = list, restore = restore, save = save, cleanup = cleanup}"
5112 " sess = ArdourSession ()"
5113 " ArdourSession = nil"
5115 "function ardour () end"
5118 lua_State* L = lua.getState();
5121 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5122 lua.do_command ("sess = nil"); // hide it.
5123 lua.do_command ("collectgarbage()");
5125 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5126 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5127 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5128 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5129 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5130 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5131 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5132 } catch (luabridge::LuaException const& e) {
5133 fatal << string_compose (_("programming error: %1"),
5134 X_("Failed to setup Lua interpreter"))
5136 abort(); /*NOTREACHED*/
5139 LuaBindings::stddef (L);
5140 LuaBindings::common (L);
5141 LuaBindings::dsp (L);
5142 luabridge::push <Session *> (L, this);
5143 lua_setglobal (L, "Session");
5147 Session::scripts_changed ()
5149 assert (!lua_lock.trylock()); // must hold lua_lock
5152 luabridge::LuaRef list ((*_lua_list)());
5154 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5155 if (!i.key ().isString ()) { assert(0); continue; }
5158 _n_lua_scripts = cnt;
5159 } catch (luabridge::LuaException const& e) {
5160 fatal << string_compose (_("programming error: %1"),
5161 X_("Indexing Lua Session Scripts failed."))
5163 abort(); /*NOTREACHED*/
5168 Session::non_realtime_set_audition ()
5170 assert (pending_audition_region);
5171 auditioner->audition_region (pending_audition_region);
5172 pending_audition_region.reset ();
5173 AuditionActive (true); /* EMIT SIGNAL */
5177 Session::audition_region (boost::shared_ptr<Region> r)
5179 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5185 Session::cancel_audition ()
5190 if (auditioner->auditioning()) {
5191 auditioner->cancel_audition ();
5192 AuditionActive (false); /* EMIT SIGNAL */
5197 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5199 if (a->is_monitor()) {
5202 if (b->is_monitor()) {
5205 return a->order_key () < b->order_key ();
5209 Session::is_auditioning () const
5211 /* can be called before we have an auditioner object */
5213 return auditioner->auditioning();
5220 Session::graph_reordered ()
5222 /* don't do this stuff if we are setting up connections
5223 from a set_state() call or creating new tracks. Ditto for deletion.
5226 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5230 /* every track/bus asked for this to be handled but it was deferred because
5231 we were connecting. do it now.
5234 request_input_change_handling ();
5238 /* force all diskstreams to update their capture offset values to
5239 reflect any changes in latencies within the graph.
5242 boost::shared_ptr<RouteList> rl = routes.reader ();
5243 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5244 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5246 tr->set_capture_offset ();
5251 /** @return Number of frames that there is disk space available to write,
5254 boost::optional<framecnt_t>
5255 Session::available_capture_duration ()
5257 Glib::Threads::Mutex::Lock lm (space_lock);
5259 if (_total_free_4k_blocks_uncertain) {
5260 return boost::optional<framecnt_t> ();
5263 float sample_bytes_on_disk = 4.0; // keep gcc happy
5265 switch (config.get_native_file_data_format()) {
5267 sample_bytes_on_disk = 4.0;
5271 sample_bytes_on_disk = 3.0;
5275 sample_bytes_on_disk = 2.0;
5279 /* impossible, but keep some gcc versions happy */
5280 fatal << string_compose (_("programming error: %1"),
5281 X_("illegal native file data format"))
5283 abort(); /*NOTREACHED*/
5286 double scale = 4096.0 / sample_bytes_on_disk;
5288 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5289 return max_framecnt;
5292 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5296 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5299 RCUWriter<BundleList> writer (_bundles);
5300 boost::shared_ptr<BundleList> b = writer.get_copy ();
5301 b->push_back (bundle);
5305 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5312 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5314 bool removed = false;
5317 RCUWriter<BundleList> writer (_bundles);
5318 boost::shared_ptr<BundleList> b = writer.get_copy ();
5319 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5321 if (i != b->end()) {
5328 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5334 boost::shared_ptr<Bundle>
5335 Session::bundle_by_name (string name) const
5337 boost::shared_ptr<BundleList> b = _bundles.reader ();
5339 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5340 if ((*i)->name() == name) {
5345 return boost::shared_ptr<Bundle> ();
5349 Session::tempo_map_changed (const PropertyChange&)
5353 playlists->update_after_tempo_map_change ();
5355 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5361 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5363 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5364 (*i)->recompute_frames_from_bbt ();
5368 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5369 * the given count with the current block size.
5372 Session::ensure_buffers (ChanCount howmany)
5374 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5378 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5380 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5381 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5386 Session::next_insert_id ()
5388 /* this doesn't really loop forever. just think about it */
5391 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5392 if (!insert_bitset[n]) {
5393 insert_bitset[n] = true;
5399 /* none available, so resize and try again */
5401 insert_bitset.resize (insert_bitset.size() + 16, false);
5406 Session::next_send_id ()
5408 /* this doesn't really loop forever. just think about it */
5411 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5412 if (!send_bitset[n]) {
5413 send_bitset[n] = true;
5419 /* none available, so resize and try again */
5421 send_bitset.resize (send_bitset.size() + 16, false);
5426 Session::next_aux_send_id ()
5428 /* this doesn't really loop forever. just think about it */
5431 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5432 if (!aux_send_bitset[n]) {
5433 aux_send_bitset[n] = true;
5439 /* none available, so resize and try again */
5441 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5446 Session::next_return_id ()
5448 /* this doesn't really loop forever. just think about it */
5451 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5452 if (!return_bitset[n]) {
5453 return_bitset[n] = true;
5459 /* none available, so resize and try again */
5461 return_bitset.resize (return_bitset.size() + 16, false);
5466 Session::mark_send_id (uint32_t id)
5468 if (id >= send_bitset.size()) {
5469 send_bitset.resize (id+16, false);
5471 if (send_bitset[id]) {
5472 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5474 send_bitset[id] = true;
5478 Session::mark_aux_send_id (uint32_t id)
5480 if (id >= aux_send_bitset.size()) {
5481 aux_send_bitset.resize (id+16, false);
5483 if (aux_send_bitset[id]) {
5484 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5486 aux_send_bitset[id] = true;
5490 Session::mark_return_id (uint32_t id)
5492 if (id >= return_bitset.size()) {
5493 return_bitset.resize (id+16, false);
5495 if (return_bitset[id]) {
5496 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5498 return_bitset[id] = true;
5502 Session::mark_insert_id (uint32_t id)
5504 if (id >= insert_bitset.size()) {
5505 insert_bitset.resize (id+16, false);
5507 if (insert_bitset[id]) {
5508 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5510 insert_bitset[id] = true;
5514 Session::unmark_send_id (uint32_t id)
5516 if (id < send_bitset.size()) {
5517 send_bitset[id] = false;
5522 Session::unmark_aux_send_id (uint32_t id)
5524 if (id < aux_send_bitset.size()) {
5525 aux_send_bitset[id] = false;
5530 Session::unmark_return_id (uint32_t id)
5532 if (_state_of_the_state & Deletion) { return; }
5533 if (id < return_bitset.size()) {
5534 return_bitset[id] = false;
5539 Session::unmark_insert_id (uint32_t id)
5541 if (id < insert_bitset.size()) {
5542 insert_bitset[id] = false;
5547 Session::reset_native_file_format ()
5549 boost::shared_ptr<RouteList> rl = routes.reader ();
5551 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5552 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5554 /* don't save state as we do this, there's no point
5556 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5557 tr->reset_write_sources (false);
5558 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5564 Session::route_name_unique (string n) const
5566 boost::shared_ptr<RouteList> r = routes.reader ();
5568 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5569 if ((*i)->name() == n) {
5578 Session::route_name_internal (string n) const
5580 if (auditioner && auditioner->name() == n) {
5584 if (_click_io && _click_io->name() == n) {
5592 Session::freeze_all (InterThreadInfo& itt)
5594 boost::shared_ptr<RouteList> r = routes.reader ();
5596 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5598 boost::shared_ptr<Track> t;
5600 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5601 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5611 boost::shared_ptr<Region>
5612 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5613 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5614 InterThreadInfo& itt,
5615 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5616 bool for_export, bool for_freeze)
5618 boost::shared_ptr<Region> result;
5619 boost::shared_ptr<Playlist> playlist;
5620 boost::shared_ptr<Source> source;
5621 ChanCount diskstream_channels (track.n_channels());
5622 framepos_t position;
5623 framecnt_t this_chunk;
5625 framepos_t latency_skip;
5627 framepos_t len = end - start;
5628 bool need_block_size_reset = false;
5629 ChanCount const max_proc = track.max_processor_streams ();
5630 string legal_playlist_name;
5631 string possible_path;
5634 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5635 end, start) << endmsg;
5639 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5640 include_endpoint, for_export, for_freeze);
5642 if (diskstream_channels.n(track.data_type()) < 1) {
5643 error << _("Cannot write a range with no data.") << endmsg;
5647 // block all process callback handling
5649 block_processing ();
5652 // synchronize with AudioEngine::process_callback()
5653 // make sure processing is not currently running
5654 // and processing_blocked() is honored before
5655 // acquiring thread buffers
5656 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5659 _bounce_processing_active = true;
5661 /* call tree *MUST* hold route_lock */
5663 if ((playlist = track.playlist()) == 0) {
5667 legal_playlist_name = legalize_for_path (playlist->name());
5669 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5671 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5672 string path = ((track.data_type() == DataType::AUDIO)
5673 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5674 : new_midi_source_path (legal_playlist_name));
5681 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5684 catch (failed_constructor& err) {
5685 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5689 srcs.push_back (source);
5692 /* tell redirects that care that we are about to use a much larger
5693 * blocksize. this will flush all plugins too, so that they are ready
5694 * to be used for this process.
5697 need_block_size_reset = true;
5698 track.set_block_size (bounce_chunk_size);
5699 _engine.main_thread()->get_buffers ();
5703 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5705 /* create a set of reasonably-sized buffers */
5706 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5707 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5709 buffers.set_count (max_proc);
5711 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5712 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5713 boost::shared_ptr<MidiSource> ms;
5715 afs->prepare_for_peakfile_writes ();
5716 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5717 Source::Lock lock(ms->mutex());
5718 ms->mark_streaming_write_started(lock);
5722 while (to_do && !itt.cancel) {
5724 this_chunk = min (to_do, bounce_chunk_size);
5726 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5730 start += this_chunk;
5731 to_do -= this_chunk;
5732 itt.progress = (float) (1.0 - ((double) to_do / len));
5734 if (latency_skip >= bounce_chunk_size) {
5735 latency_skip -= bounce_chunk_size;
5739 const framecnt_t current_chunk = this_chunk - latency_skip;
5742 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5743 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5744 boost::shared_ptr<MidiSource> ms;
5747 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5750 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5751 Source::Lock lock(ms->mutex());
5753 const MidiBuffer& buf = buffers.get_midi(0);
5754 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5755 Evoral::Event<framepos_t> ev = *i;
5756 ev.set_time(ev.time() - position);
5757 ms->append_event_frames(lock, ev, ms->timeline_position());
5764 /* post-roll, pick up delayed processor output */
5765 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5767 while (latency_skip && !itt.cancel) {
5768 this_chunk = min (latency_skip, bounce_chunk_size);
5769 latency_skip -= this_chunk;
5771 buffers.silence (this_chunk, 0);
5772 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5775 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5776 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5779 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5791 xnow = localtime (&now);
5793 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5794 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5795 boost::shared_ptr<MidiSource> ms;
5798 afs->update_header (position, *xnow, now);
5799 afs->flush_header ();
5800 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5801 Source::Lock lock(ms->mutex());
5802 ms->mark_streaming_write_completed(lock);
5806 /* construct a region to represent the bounced material */
5810 plist.add (Properties::start, 0);
5811 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5812 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5814 result = RegionFactory::create (srcs, plist);
5820 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5821 (*src)->mark_for_remove ();
5822 (*src)->drop_references ();
5826 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5827 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5830 afs->done_with_peakfile_writes ();
5834 _bounce_processing_active = false;
5836 if (need_block_size_reset) {
5837 _engine.main_thread()->drop_buffers ();
5838 track.set_block_size (get_block_size());
5841 unblock_processing ();
5848 Session::gain_automation_buffer() const
5850 return ProcessThread::gain_automation_buffer ();
5854 Session::trim_automation_buffer() const
5856 return ProcessThread::trim_automation_buffer ();
5860 Session::send_gain_automation_buffer() const
5862 return ProcessThread::send_gain_automation_buffer ();
5866 Session::pan_automation_buffer() const
5868 return ProcessThread::pan_automation_buffer ();
5872 Session::get_silent_buffers (ChanCount count)
5874 return ProcessThread::get_silent_buffers (count);
5878 Session::get_scratch_buffers (ChanCount count, bool silence)
5880 return ProcessThread::get_scratch_buffers (count, silence);
5884 Session::get_noinplace_buffers (ChanCount count)
5886 return ProcessThread::get_noinplace_buffers (count);
5890 Session::get_route_buffers (ChanCount count, bool silence)
5892 return ProcessThread::get_route_buffers (count, silence);
5897 Session::get_mix_buffers (ChanCount count)
5899 return ProcessThread::get_mix_buffers (count);
5903 Session::ntracks () const
5906 boost::shared_ptr<RouteList> r = routes.reader ();
5908 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5909 if (boost::dynamic_pointer_cast<Track> (*i)) {
5918 Session::nbusses () const
5921 boost::shared_ptr<RouteList> r = routes.reader ();
5923 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5924 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5933 Session::add_automation_list(AutomationList *al)
5935 automation_lists[al->id()] = al;
5938 /** @return true if there is at least one record-enabled track, otherwise false */
5940 Session::have_rec_enabled_track () const
5942 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
5946 Session::have_rec_disabled_track () const
5948 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
5951 /** Update the state of our rec-enabled tracks flag */
5953 Session::update_route_record_state ()
5955 boost::shared_ptr<RouteList> rl = routes.reader ();
5956 RouteList::iterator i = rl->begin();
5957 while (i != rl->end ()) {
5959 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5960 if (tr && tr->record_enabled ()) {
5967 int const old = g_atomic_int_get (&_have_rec_enabled_track);
5969 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5971 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5972 RecordStateChanged (); /* EMIT SIGNAL */
5975 for (i = rl->begin(); i != rl->end (); ++i) {
5976 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5977 if (tr && !tr->record_enabled ()) {
5982 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
5984 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
5986 if (record_status() == Recording && record_arm_state_changed ) {
5987 RecordArmStateChanged ();
5993 Session::listen_position_changed ()
5995 boost::shared_ptr<RouteList> r = routes.reader ();
5997 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5998 (*i)->listen_position_changed ();
6003 Session::solo_control_mode_changed ()
6005 /* cancel all solo or all listen when solo control mode changes */
6008 set_solo (get_routes(), false);
6009 } else if (listening()) {
6010 set_listen (get_routes(), false);
6014 /** Called when a property of one of our route groups changes */
6016 Session::route_group_property_changed (RouteGroup* rg)
6018 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6021 /** Called when a route is added to one of our route groups */
6023 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6025 RouteAddedToRouteGroup (rg, r);
6028 /** Called when a route is removed from one of our route groups */
6030 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6032 update_route_record_state ();
6033 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6036 boost::shared_ptr<RouteList>
6037 Session::get_tracks () const
6039 boost::shared_ptr<RouteList> rl = routes.reader ();
6040 boost::shared_ptr<RouteList> tl (new RouteList);
6042 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6043 if (boost::dynamic_pointer_cast<Track> (*r)) {
6044 if (!(*r)->is_auditioner()) {
6052 boost::shared_ptr<RouteList>
6053 Session::get_routes_with_regions_at (framepos_t const p) const
6055 boost::shared_ptr<RouteList> r = routes.reader ();
6056 boost::shared_ptr<RouteList> rl (new RouteList);
6058 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6059 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6064 boost::shared_ptr<Playlist> pl = tr->playlist ();
6069 if (pl->has_region_at (p)) {
6078 Session::goto_end ()
6080 if (_session_range_location) {
6081 request_locate (_session_range_location->end(), false);
6083 request_locate (0, false);
6088 Session::goto_start ()
6090 if (_session_range_location) {
6091 request_locate (_session_range_location->start(), false);
6093 request_locate (0, false);
6098 Session::current_start_frame () const
6100 return _session_range_location ? _session_range_location->start() : 0;
6104 Session::current_end_frame () const
6106 return _session_range_location ? _session_range_location->end() : 0;
6110 Session::set_session_range_location (framepos_t start, framepos_t end)
6112 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6113 _locations->add (_session_range_location);
6117 Session::step_edit_status_change (bool yn)
6123 send = (_step_editors == 0);
6128 send = (_step_editors == 1);
6131 if (_step_editors > 0) {
6137 StepEditStatusChange (val);
6143 Session::start_time_changed (framepos_t old)
6145 /* Update the auto loop range to match the session range
6146 (unless the auto loop range has been changed by the user)
6149 Location* s = _locations->session_range_location ();
6154 Location* l = _locations->auto_loop_location ();
6156 if (l && l->start() == old) {
6157 l->set_start (s->start(), true);
6162 Session::end_time_changed (framepos_t old)
6164 /* Update the auto loop range to match the session range
6165 (unless the auto loop range has been changed by the user)
6168 Location* s = _locations->session_range_location ();
6173 Location* l = _locations->auto_loop_location ();
6175 if (l && l->end() == old) {
6176 l->set_end (s->end(), true);
6180 std::vector<std::string>
6181 Session::source_search_path (DataType type) const
6185 if (session_dirs.size() == 1) {
6187 case DataType::AUDIO:
6188 sp.push_back (_session_dir->sound_path());
6190 case DataType::MIDI:
6191 sp.push_back (_session_dir->midi_path());
6195 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6196 SessionDirectory sdir (i->path);
6198 case DataType::AUDIO:
6199 sp.push_back (sdir.sound_path());
6201 case DataType::MIDI:
6202 sp.push_back (sdir.midi_path());
6208 if (type == DataType::AUDIO) {
6209 const string sound_path_2X = _session_dir->sound_path_2X();
6210 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6211 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6212 sp.push_back (sound_path_2X);
6217 // now check the explicit (possibly user-specified) search path
6220 case DataType::AUDIO:
6221 sp += Searchpath(config.get_audio_search_path ());
6223 case DataType::MIDI:
6224 sp += Searchpath(config.get_midi_search_path ());
6232 Session::ensure_search_path_includes (const string& path, DataType type)
6241 case DataType::AUDIO:
6242 sp += Searchpath(config.get_audio_search_path ());
6244 case DataType::MIDI:
6245 sp += Searchpath (config.get_midi_search_path ());
6249 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6250 /* No need to add this new directory if it has the same inode as
6251 an existing one; checking inode rather than name prevents duplicated
6252 directories when we are using symlinks.
6254 On Windows, I think we could just do if (*i == path) here.
6256 if (PBD::equivalent_paths (*i, path)) {
6264 case DataType::AUDIO:
6265 config.set_audio_search_path (sp.to_string());
6267 case DataType::MIDI:
6268 config.set_midi_search_path (sp.to_string());
6274 Session::remove_dir_from_search_path (const string& dir, DataType type)
6279 case DataType::AUDIO:
6280 sp = Searchpath(config.get_audio_search_path ());
6282 case DataType::MIDI:
6283 sp = Searchpath (config.get_midi_search_path ());
6290 case DataType::AUDIO:
6291 config.set_audio_search_path (sp.to_string());
6293 case DataType::MIDI:
6294 config.set_midi_search_path (sp.to_string());
6300 boost::shared_ptr<Speakers>
6301 Session::get_speakers()
6307 Session::unknown_processors () const
6311 boost::shared_ptr<RouteList> r = routes.reader ();
6312 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6313 list<string> t = (*i)->unknown_processors ();
6314 copy (t.begin(), t.end(), back_inserter (p));
6324 Session::update_latency (bool playback)
6326 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6328 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
6332 boost::shared_ptr<RouteList> r = routes.reader ();
6333 framecnt_t max_latency = 0;
6336 /* reverse the list so that we work backwards from the last route to run to the first */
6337 RouteList* rl = routes.reader().get();
6338 r.reset (new RouteList (*rl));
6339 reverse (r->begin(), r->end());
6342 /* compute actual latency values for the given direction and store them all in per-port
6343 structures. this will also publish the same values (to JACK) so that computation of latency
6344 for routes can consistently use public latency values.
6347 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6348 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6351 /* because we latency compensate playback, our published playback latencies should
6352 be the same for all output ports - all material played back by ardour has
6353 the same latency, whether its caused by plugins or by latency compensation. since
6354 these may differ from the values computed above, reset all playback port latencies
6358 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6360 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6361 (*i)->set_public_port_latencies (max_latency, playback);
6366 post_playback_latency ();
6370 post_capture_latency ();
6373 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6377 Session::post_playback_latency ()
6379 set_worst_playback_latency ();
6381 boost::shared_ptr<RouteList> r = routes.reader ();
6383 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6384 if (!(*i)->is_auditioner() && ((*i)->active())) {
6385 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6389 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6390 (*i)->set_latency_compensation (_worst_track_latency);
6395 Session::post_capture_latency ()
6397 set_worst_capture_latency ();
6399 /* reflect any changes in capture latencies into capture offsets
6402 boost::shared_ptr<RouteList> rl = routes.reader();
6403 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6404 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6406 tr->set_capture_offset ();
6412 Session::initialize_latencies ()
6415 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6416 update_latency (false);
6417 update_latency (true);
6420 set_worst_io_latencies ();
6424 Session::set_worst_io_latencies ()
6426 set_worst_playback_latency ();
6427 set_worst_capture_latency ();
6431 Session::set_worst_playback_latency ()
6433 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6437 _worst_output_latency = 0;
6439 if (!_engine.connected()) {
6443 boost::shared_ptr<RouteList> r = routes.reader ();
6445 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6446 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6449 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6453 Session::set_worst_capture_latency ()
6455 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6459 _worst_input_latency = 0;
6461 if (!_engine.connected()) {
6465 boost::shared_ptr<RouteList> r = routes.reader ();
6467 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6468 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6471 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6475 Session::update_latency_compensation (bool force_whole_graph)
6477 bool some_track_latency_changed = false;
6479 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6483 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6485 _worst_track_latency = 0;
6487 boost::shared_ptr<RouteList> r = routes.reader ();
6489 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6490 if (!(*i)->is_auditioner() && ((*i)->active())) {
6492 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6493 some_track_latency_changed = true;
6495 _worst_track_latency = max (tl, _worst_track_latency);
6499 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6500 (some_track_latency_changed ? "yes" : "no")));
6502 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6504 if (some_track_latency_changed || force_whole_graph) {
6505 _engine.update_latencies ();
6509 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6510 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6514 tr->set_capture_offset ();
6519 Session::session_name_is_legal (const string& path)
6521 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6523 for (int i = 0; illegal_chars[i]; ++i) {
6524 if (path.find (illegal_chars[i]) != string::npos) {
6525 return illegal_chars[i];
6533 Session::next_control_id () const
6537 /* the monitor bus remote ID is in a different
6538 * "namespace" than regular routes. its existence doesn't
6539 * affect normal (low) numbered routes.
6546 /* the same about masterbus in Waves Tracks */
6548 if (Profile->get_trx() && _master_out) {
6552 return nroutes() - subtract;
6556 Session::notify_remote_id_change ()
6558 if (deletion_in_progress()) {
6562 switch (Config->get_remote_model()) {
6564 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6570 #ifdef USE_TRACKS_CODE_FEATURES
6571 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6572 * if track order has been changed by user
6574 reconnect_existing_routes(true, true);
6580 Session::sync_order_keys ()
6582 if (deletion_in_progress()) {
6586 /* tell everyone that something has happened to the sort keys
6587 and let them sync up with the change(s)
6588 this will give objects that manage the sort order keys the
6589 opportunity to keep them in sync if they wish to.
6592 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6594 reassign_track_numbers();
6596 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6598 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6602 Session::operation_in_progress (GQuark op) const
6604 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6607 boost::shared_ptr<Port>
6608 Session::ltc_input_port () const
6610 return _ltc_input->nth (0);
6613 boost::shared_ptr<Port>
6614 Session::ltc_output_port () const
6616 return _ltc_output->nth (0);
6620 Session::reconnect_ltc_input ()
6624 string src = Config->get_ltc_source_port();
6626 _ltc_input->disconnect (this);
6628 if (src != _("None") && !src.empty()) {
6629 _ltc_input->nth (0)->connect (src);
6632 if ( ARDOUR::Profile->get_trx () ) {
6633 // Tracks need this signal to update timecode_source_dropdown
6634 MtcOrLtcInputPortChanged (); //emit signal
6640 Session::reconnect_ltc_output ()
6644 string src = Config->get_ltc_output_port();
6646 _ltc_output->disconnect (this);
6648 if (src != _("None") && !src.empty()) {
6649 _ltc_output->nth (0)->connect (src);
6655 Session::set_range_selection (framepos_t start, framepos_t end)
6657 _range_selection = Evoral::Range<framepos_t> (start, end);
6658 #ifdef USE_TRACKS_CODE_FEATURES
6659 follow_playhead_priority ();
6664 Session::set_object_selection (framepos_t start, framepos_t end)
6666 _object_selection = Evoral::Range<framepos_t> (start, end);
6667 #ifdef USE_TRACKS_CODE_FEATURES
6668 follow_playhead_priority ();
6673 Session::clear_range_selection ()
6675 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6676 #ifdef USE_TRACKS_CODE_FEATURES
6677 follow_playhead_priority ();
6682 Session::clear_object_selection ()
6684 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6685 #ifdef USE_TRACKS_CODE_FEATURES
6686 follow_playhead_priority ();
6691 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6692 const ChanCount& input_start,
6693 const ChanCount& output_start,
6694 const ChanCount& input_offset,
6695 const ChanCount& output_offset)
6697 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6698 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6699 input_start, output_start,
6700 input_offset, output_offset));
6702 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6703 pthread_cond_signal (&_auto_connect_cond);
6704 pthread_mutex_unlock (&_auto_connect_mutex);
6709 Session::auto_connect (const AutoConnectRequest& ar)
6711 boost::shared_ptr<Route> route = ar.route.lock();
6713 if (!route) { return; }
6715 if (!IO::connecting_legal) {
6719 //why would we need the process lock ??
6720 //Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6722 /* If both inputs and outputs are auto-connected to physical ports,
6723 * use the max of input and output offsets to ensure auto-connected
6724 * port numbers always match up (e.g. the first audio input and the
6725 * first audio output of the route will have the same physical
6726 * port number). Otherwise just use the lowest input or output
6730 const bool in_out_physical =
6731 (Config->get_input_auto_connect() & AutoConnectPhysical)
6732 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6733 && ar.connect_inputs;
6735 const ChanCount in_offset = in_out_physical
6736 ? ChanCount::max(ar.input_offset, ar.output_offset)
6739 const ChanCount out_offset = in_out_physical
6740 ? ChanCount::max(ar.input_offset, ar.output_offset)
6743 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6744 vector<string> physinputs;
6745 vector<string> physoutputs;
6747 _engine.get_physical_outputs (*t, physoutputs);
6748 _engine.get_physical_inputs (*t, physinputs);
6750 if (!physinputs.empty() && ar.connect_inputs) {
6751 uint32_t nphysical_in = physinputs.size();
6753 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6756 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6757 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6760 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6766 if (!physoutputs.empty()) {
6767 uint32_t nphysical_out = physoutputs.size();
6768 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6772 * do not create new connections if we reached the limit of physical outputs
6775 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6776 ARDOUR::Profile->get_trx () &&
6777 ar.output_offset.get(*t) == nphysical_out ) {
6781 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6782 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6783 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6784 /* master bus is audio only */
6785 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6786 port = _master_out->input()->ports().port(*t,
6787 i % _master_out->input()->n_ports().get(*t))->name();
6791 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6800 Session::auto_connect_thread_start ()
6802 if (_ac_thread_active) {
6806 while (!_auto_connect_queue.empty ()) {
6807 _auto_connect_queue.pop ();
6810 _ac_thread_active = true;
6811 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6812 _ac_thread_active = false;
6817 Session::auto_connect_thread_terminate ()
6819 if (!_ac_thread_active) {
6822 _ac_thread_active = false;
6825 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6826 while (!_auto_connect_queue.empty ()) {
6827 _auto_connect_queue.pop ();
6831 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6832 pthread_cond_signal (&_auto_connect_cond);
6833 pthread_mutex_unlock (&_auto_connect_mutex);
6837 pthread_join (_auto_connect_thread, &status);
6841 Session::auto_connect_thread (void *arg)
6843 Session *s = static_cast<Session *>(arg);
6844 s->auto_connect_thread_run ();
6850 Session::auto_connect_thread_run ()
6852 pthread_set_name (X_("autoconnect"));
6853 SessionEvent::create_per_thread_pool (X_("autoconnect"), 256);
6854 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 256);
6855 pthread_mutex_lock (&_auto_connect_mutex);
6856 while (_ac_thread_active) {
6858 while (!_auto_connect_queue.empty ()) {
6859 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6860 if (_auto_connect_queue.empty ()) { break; } // re-check with lock
6861 const AutoConnectRequest ar (_auto_connect_queue.front());
6862 _auto_connect_queue.pop ();
6867 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
6869 pthread_mutex_unlock (&_auto_connect_mutex);