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/search_path.h"
46 #include "pbd/stacktrace.h"
47 #include "pbd/stl_delete.h"
48 #include "pbd/replace_all.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/directory_names.h"
70 #ifdef USE_TRACKS_CODE_FEATURES
71 #include "ardour/engine_state_controller.h"
73 #include "ardour/filename_extensions.h"
74 #include "ardour/gain_control.h"
75 #include "ardour/graph.h"
76 #include "ardour/luabindings.h"
77 #include "ardour/midiport_manager.h"
78 #include "ardour/scene_changer.h"
79 #include "ardour/midi_patch_manager.h"
80 #include "ardour/midi_track.h"
81 #include "ardour/midi_ui.h"
82 #include "ardour/operations.h"
83 #include "ardour/playlist.h"
84 #include "ardour/plugin.h"
85 #include "ardour/plugin_insert.h"
86 #include "ardour/process_thread.h"
87 #include "ardour/profile.h"
88 #include "ardour/rc_configuration.h"
89 #include "ardour/recent_sessions.h"
90 #include "ardour/region.h"
91 #include "ardour/region_factory.h"
92 #include "ardour/route_graph.h"
93 #include "ardour/route_group.h"
94 #include "ardour/route_sorters.h"
95 #include "ardour/send.h"
96 #include "ardour/session.h"
97 #include "ardour/session_directory.h"
98 #include "ardour/session_playlists.h"
99 #include "ardour/smf_source.h"
100 #include "ardour/source_factory.h"
101 #include "ardour/speakers.h"
102 #include "ardour/tempo.h"
103 #include "ardour/track.h"
104 #include "ardour/user_bundle.h"
105 #include "ardour/utils.h"
107 #include "midi++/port.h"
108 #include "midi++/mmc.h"
110 #include "LuaBridge/LuaBridge.h"
114 #include <glibmm/checksum.h>
123 using namespace ARDOUR;
126 bool Session::_disable_all_loaded_plugins = false;
127 bool Session::_bypass_all_loaded_plugins = false;
129 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
130 PBD::Signal1<void,std::string> Session::Dialog;
131 PBD::Signal0<int> Session::AskAboutPendingState;
132 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
133 PBD::Signal0<void> Session::SendFeedback;
134 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
136 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
137 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
138 PBD::Signal2<void,std::string, std::string> Session::Exported;
139 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
140 PBD::Signal0<void> Session::Quit;
141 PBD::Signal0<void> Session::FeedbackDetected;
142 PBD::Signal0<void> Session::SuccessfulGraphSort;
143 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
145 const framecnt_t Session::bounce_chunk_size = 8192;
146 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
147 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
149 // seconds should be added after the region exceeds end marker
150 #ifdef USE_TRACKS_CODE_FEATURES
151 const uint32_t Session::session_end_shift = 5;
153 const uint32_t Session::session_end_shift = 0;
156 /** @param snapshot_name Snapshot name, without .ardour suffix */
157 Session::Session (AudioEngine &eng,
158 const string& fullpath,
159 const string& snapshot_name,
160 BusProfile* bus_profile,
162 : playlists (new SessionPlaylists)
164 , process_function (&Session::process_with_events)
165 , _bounce_processing_active (false)
166 , waiting_for_sync_offset (false)
167 , _base_frame_rate (0)
168 , _current_frame_rate (0)
169 , _nominal_frame_rate (0)
170 , transport_sub_state (0)
171 , _record_status (Disabled)
172 , _transport_frame (0)
173 , _session_range_location (0)
176 , _transport_speed (0)
177 , _default_transport_speed (1.0)
178 , _last_transport_speed (0)
179 , _target_transport_speed (0.0)
180 , auto_play_legal (false)
181 , _last_slave_transport_frame (0)
182 , maximum_output_latency (0)
183 , _requested_return_frame (-1)
184 , current_block_size (0)
185 , _worst_output_latency (0)
186 , _worst_input_latency (0)
187 , _worst_track_latency (0)
188 , _have_captured (false)
189 , _non_soloed_outs_muted (false)
192 , _solo_isolated_cnt (0)
194 , _was_seamless (Config->get_seamless_loop ())
195 , _under_nsm_control (false)
197 , delta_accumulator_cnt (0)
198 , average_slave_delta (1800) // !!! why 1800 ???
200 , have_first_delta_accumulator (false)
201 , _slave_state (Stopped)
202 , _mtc_active (false)
203 , _ltc_active (false)
204 , post_export_sync (false)
205 , post_export_position (0)
207 , _export_started (false)
208 , _export_rolling (false)
209 , _pre_export_mmc_enabled (false)
210 , _name (snapshot_name)
212 , _send_qf_mtc (false)
213 , _pframes_since_last_mtc (0)
214 , session_midi_feedback (0)
216 , loop_changing (false)
218 , _session_dir (new SessionDirectory (fullpath))
219 , _current_snapshot_name (snapshot_name)
221 , state_was_pending (false)
222 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
224 , _save_queued (false)
225 , _last_roll_location (0)
226 , _last_roll_or_reversal_location (0)
227 , _last_record_location (0)
228 , pending_locate_roll (false)
229 , pending_locate_frame (0)
230 , pending_locate_flush (false)
231 , pending_abort (false)
232 , pending_auto_loop (false)
233 , _mempool ("Session", 1048576)
234 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
235 , _butler (new Butler (*this))
236 , _post_transport_work (0)
237 , cumulative_rf_motion (0)
239 , _locations (new Locations (*this))
240 , _ignore_skips_updates (false)
241 , _rt_thread_active (false)
242 , _rt_emit_pending (false)
244 , outbound_mtc_timecode_frame (0)
245 , next_quarter_frame_to_send (-1)
246 , _frames_per_timecode_frame (0)
247 , _frames_per_hour (0)
248 , _timecode_frames_per_hour (0)
249 , last_timecode_valid (false)
250 , last_timecode_when (0)
251 , _send_timecode_update (false)
263 , ltc_timecode_offset (0)
264 , ltc_timecode_negative_offset (false)
265 , midi_control_ui (0)
267 , _all_route_group (new RouteGroup (*this, "all"))
268 , routes (new RouteList)
269 , _adding_routes_in_progress (false)
270 , _reconnecting_routes_in_progress (false)
271 , _route_deletion_in_progress (false)
272 , destructive_index (0)
273 , _track_number_decimals(1)
274 , default_fade_steepness (0)
275 , default_fade_msecs (0)
276 , _total_free_4k_blocks (0)
277 , _total_free_4k_blocks_uncertain (false)
278 , no_questions_about_missing_files (false)
281 , _bundles (new BundleList)
282 , _bundle_xml_node (0)
286 , click_emphasis_data (0)
288 , click_emphasis_length (0)
289 , _clicks_cleared (0)
290 , _play_range (false)
291 , _range_selection (-1,-1)
292 , _object_selection (-1,-1)
294 , first_file_data_format_reset (true)
295 , first_file_header_format_reset (true)
296 , have_looped (false)
297 , _have_rec_enabled_track (false)
298 , _have_rec_disabled_track (true)
300 , _suspend_timecode_transmission (0)
301 , _speakers (new Speakers)
303 , ignore_route_processor_changes (false)
310 pthread_mutex_init (&_rt_emit_mutex, 0);
311 pthread_cond_init (&_rt_emit_cond, 0);
313 pre_engine_init (fullpath);
319 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
321 #ifdef USE_TRACKS_CODE_FEATURES
322 sr = EngineStateController::instance()->get_current_sample_rate();
324 if (ensure_engine (sr)) {
326 throw SessionException (_("Cannot connect to audio/midi engine"));
329 // set samplerate for plugins added early
330 // e.g from templates or MB channelstrip
331 set_block_size (_engine.samples_per_cycle());
332 set_frame_rate (_engine.sample_rate());
334 if (create (mix_template, bus_profile)) {
336 throw SessionException (_("Session initialization failed"));
339 /* if a mix template was provided, then ::create() will
340 * have copied it into the session and we need to load it
341 * so that we have the state ready for ::set_state()
342 * after the engine is started.
344 * Note that we do NOT try to get the sample rate from
345 * the template at this time, though doing so would
346 * be easy if we decided this was an appropriate part
350 if (!mix_template.empty()) {
351 if (load_state (_current_snapshot_name)) {
352 throw SessionException (_("Failed to load template/snapshot state"));
354 store_recent_templates (mix_template);
357 /* load default session properties - if any */
362 if (load_state (_current_snapshot_name)) {
363 throw SessionException (_("Failed to load state"));
366 /* try to get sample rate from XML state so that we
367 * can influence the SR if we set up the audio
372 const XMLProperty* prop;
373 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
374 sr = atoi (prop->value());
378 if (ensure_engine (sr)) {
380 throw SessionException (_("Cannot connect to audio/midi engine"));
384 if (post_engine_init ()) {
386 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
389 store_recent_sessions (_name, _path);
391 bool was_dirty = dirty();
393 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
395 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
396 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
399 DirtyChanged (); /* EMIT SIGNAL */
402 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
403 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
405 emit_thread_start ();
407 /* hook us up to the engine since we are now completely constructed */
409 BootMessage (_("Connect to engine"));
411 _engine.set_session (this);
412 _engine.reset_timebase ();
414 #ifdef USE_TRACKS_CODE_FEATURES
416 EngineStateController::instance()->set_session(this);
419 if ( ARDOUR::Profile->get_trx () ) {
421 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
422 * each available input must have corresponding track when session starts.
425 uint32_t how_many (0);
427 std::vector<std::string> inputs;
428 EngineStateController::instance()->get_physical_audio_inputs(inputs);
430 how_many = inputs.size();
432 list<boost::shared_ptr<AudioTrack> > tracks;
434 // Track names after driver
435 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
436 string track_name = "";
437 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
439 track_name = inputs[i];
440 replace_all (track_name, "system:capture", "");
442 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
443 tracks.insert(tracks.begin(), single_track.front());
445 } else { // Default track names
446 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
449 if (tracks.size() != how_many) {
451 throw failed_constructor ();
460 BootMessage (_("Session loading complete"));
472 Session::ensure_engine (uint32_t desired_sample_rate)
474 if (_engine.current_backend() == 0) {
475 /* backend is unknown ... */
476 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
477 if (r.get_value_or (-1) != 0) {
480 } else if (_engine.setup_required()) {
481 /* backend is known, but setup is needed */
482 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
483 if (r.get_value_or (-1) != 0) {
486 } else if (!_engine.running()) {
487 if (_engine.start()) {
492 /* at this point the engine should be running
495 if (!_engine.running()) {
499 return immediately_post_engine ();
504 Session::immediately_post_engine ()
506 /* Do various initializations that should take place directly after we
507 * know that the engine is running, but before we either create a
508 * session or set state for an existing one.
511 if (how_many_dsp_threads () > 1) {
512 /* For now, only create the graph if we are using >1 DSP threads, as
513 it is a bit slower than the old code with 1 thread.
515 _process_graph.reset (new Graph (*this));
518 /* every time we reconnect, recompute worst case output latencies */
520 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
522 if (synced_to_engine()) {
523 _engine.transport_stop ();
526 if (config.get_jack_time_master()) {
527 _engine.transport_locate (_transport_frame);
531 BootMessage (_("Set up LTC"));
533 BootMessage (_("Set up Click"));
535 BootMessage (_("Set up standard connections"));
539 catch (failed_constructor& err) {
543 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
545 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
553 vector<void*> debug_pointers;
555 /* if we got to here, leaving pending capture state around
559 remove_pending_capture_state ();
563 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
565 /* disconnect from any and all signals that we are connected to */
569 /* shutdown control surface protocols while we still have ports
570 and the engine to move data to any devices.
573 ControlProtocolManager::instance().drop_protocols ();
575 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
577 _engine.remove_session ();
579 #ifdef USE_TRACKS_CODE_FEATURES
580 EngineStateController::instance()->remove_session();
583 /* deregister all ports - there will be no process or any other
584 * callbacks from the engine any more.
587 Port::PortDrop (); /* EMIT SIGNAL */
591 /* clear history so that no references to objects are held any more */
595 /* clear state tree so that no references to objects are held any more */
600 // unregister all lua functions, drop held references (if any)
602 lua.do_command ("Session = nil");
610 lua.collect_garbage ();
612 /* reset dynamic state version back to default */
613 Stateful::loading_state_version = 0;
615 _butler->drop_references ();
619 delete _all_route_group;
621 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
622 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
626 if (click_data != default_click) {
627 delete [] click_data;
630 if (click_emphasis_data != default_click_emphasis) {
631 delete [] click_emphasis_data;
636 /* need to remove auditioner before monitoring section
637 * otherwise it is re-connected */
640 /* drop references to routes held by the monitoring section
641 * specifically _monitor_out aux/listen references */
642 remove_monitor_section();
644 /* clear out any pending dead wood from RCU managed objects */
649 AudioDiskstream::free_working_buffers();
651 /* tell everyone who is still standing that we're about to die */
654 /* tell everyone to drop references and delete objects as we go */
656 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
657 RegionFactory::delete_all_regions ();
659 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
661 /* reset these three references to special routes before we do the usual route delete thing */
663 _master_out.reset ();
664 _monitor_out.reset ();
667 RCUWriter<RouteList> writer (routes);
668 boost::shared_ptr<RouteList> r = writer.get_copy ();
670 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
671 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
672 (*i)->drop_references ();
676 /* writer goes out of scope and updates master */
681 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
682 Glib::Threads::Mutex::Lock lm (source_lock);
683 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
684 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
685 i->second->drop_references ();
691 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
694 emit_thread_terminate ();
696 pthread_cond_destroy (&_rt_emit_cond);
697 pthread_mutex_destroy (&_rt_emit_mutex);
699 delete _scene_changer; _scene_changer = 0;
700 delete midi_control_ui; midi_control_ui = 0;
702 delete _mmc; _mmc = 0;
703 delete _midi_ports; _midi_ports = 0;
704 delete _locations; _locations = 0;
708 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
710 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
711 boost_debug_list_ptrs ();
716 Session::setup_ltc ()
720 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
721 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
723 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
724 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
727 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
728 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
730 reconnect_ltc_input ();
733 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
734 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
737 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
738 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
740 reconnect_ltc_output ();
743 /* fix up names of LTC ports because we don't want the normal
744 * IO style of NAME/TYPE-{in,out}N
747 _ltc_input->nth (0)->set_name (X_("LTC-in"));
748 _ltc_output->nth (0)->set_name (X_("LTC-out"));
752 Session::setup_click ()
756 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
757 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
759 _click_io.reset (new ClickIO (*this, X_("Click")));
760 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
761 _click_gain->activate ();
763 setup_click_state (state_tree->root());
765 setup_click_state (0);
770 Session::setup_click_state (const XMLNode* node)
772 const XMLNode* child = 0;
774 if (node && (child = find_named_node (*node, "Click")) != 0) {
776 /* existing state for Click */
779 if (Stateful::loading_state_version < 3000) {
780 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
782 const XMLNodeList& children (child->children());
783 XMLNodeList::const_iterator i = children.begin();
784 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
786 if (i != children.end()) {
787 c = _click_gain->set_state (**i, Stateful::loading_state_version);
793 _clicking = Config->get_clicking ();
797 error << _("could not setup Click I/O") << endmsg;
804 /* default state for Click: dual-mono to first 2 physical outputs */
807 _engine.get_physical_outputs (DataType::AUDIO, outs);
809 for (uint32_t physport = 0; physport < 2; ++physport) {
810 if (outs.size() > physport) {
811 if (_click_io->add_port (outs[physport], this)) {
812 // relax, even though its an error
817 if (_click_io->n_ports () > ChanCount::ZERO) {
818 _clicking = Config->get_clicking ();
824 Session::setup_bundles ()
828 RCUWriter<BundleList> writer (_bundles);
829 boost::shared_ptr<BundleList> b = writer.get_copy ();
830 for (BundleList::iterator i = b->begin(); i != b->end();) {
831 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
839 vector<string> inputs[DataType::num_types];
840 vector<string> outputs[DataType::num_types];
841 for (uint32_t i = 0; i < DataType::num_types; ++i) {
842 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
843 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
846 /* Create a set of Bundle objects that map
847 to the physical I/O currently available. We create both
848 mono and stereo bundles, so that the common cases of mono
849 and stereo tracks get bundles to put in their mixer strip
850 in / out menus. There may be a nicer way of achieving that;
851 it doesn't really scale that well to higher channel counts
854 /* mono output bundles */
856 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
858 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
860 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
862 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
865 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
866 c->add_channel (_("mono"), DataType::AUDIO);
867 c->set_port (0, outputs[DataType::AUDIO][np]);
869 add_bundle (c, false);
872 /* stereo output bundles */
874 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
875 if (np + 1 < outputs[DataType::AUDIO].size()) {
877 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
878 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
879 c->add_channel (_("L"), DataType::AUDIO);
880 c->set_port (0, outputs[DataType::AUDIO][np]);
881 c->add_channel (_("R"), DataType::AUDIO);
882 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
884 add_bundle (c, false);
888 /* mono input bundles */
890 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
892 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
894 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
896 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
899 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
900 c->add_channel (_("mono"), DataType::AUDIO);
901 c->set_port (0, inputs[DataType::AUDIO][np]);
903 add_bundle (c, false);
906 /* stereo input bundles */
908 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
909 if (np + 1 < inputs[DataType::AUDIO].size()) {
911 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
913 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
914 c->add_channel (_("L"), DataType::AUDIO);
915 c->set_port (0, inputs[DataType::AUDIO][np]);
916 c->add_channel (_("R"), DataType::AUDIO);
917 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
919 add_bundle (c, false);
923 /* MIDI input bundles */
925 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
926 string n = inputs[DataType::MIDI][np];
927 std::string pn = _engine.get_pretty_name_by_name (n);
931 boost::erase_first (n, X_("alsa_pcm:"));
933 boost::shared_ptr<Bundle> c (new Bundle (n, false));
934 c->add_channel ("", DataType::MIDI);
935 c->set_port (0, inputs[DataType::MIDI][np]);
936 add_bundle (c, false);
939 /* MIDI output bundles */
941 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
942 string n = outputs[DataType::MIDI][np];
943 std::string pn = _engine.get_pretty_name_by_name (n);
947 boost::erase_first (n, X_("alsa_pcm:"));
949 boost::shared_ptr<Bundle> c (new Bundle (n, true));
950 c->add_channel ("", DataType::MIDI);
951 c->set_port (0, outputs[DataType::MIDI][np]);
952 add_bundle (c, false);
955 // we trust the backend to only calls us if there's a change
956 BundleAddedOrRemoved (); /* EMIT SIGNAL */
960 Session::auto_connect_master_bus ()
962 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
966 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
967 // In this case it means "Multi Out" output mode
968 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
972 /* if requested auto-connect the outputs to the first N physical ports.
975 uint32_t limit = _master_out->n_outputs().n_total();
976 vector<string> outputs[DataType::num_types];
978 for (uint32_t i = 0; i < DataType::num_types; ++i) {
979 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
982 for (uint32_t n = 0; n < limit; ++n) {
983 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
985 if (outputs[p->type()].size() > n) {
986 connect_to = outputs[p->type()][n];
989 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
990 if (_master_out->output()->connect (p, connect_to, this)) {
991 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1000 Session::remove_monitor_section ()
1002 if (!_monitor_out || Profile->get_trx()) {
1006 /* force reversion to Solo-In-Place */
1007 Config->set_solo_control_is_listen_control (false);
1009 /* if we are auditioning, cancel it ... this is a workaround
1010 to a problem (auditioning does not execute the process graph,
1011 which is needed to remove routes when using >1 core for processing)
1016 /* Hold process lock while doing this so that we don't hear bits and
1017 * pieces of audio as we work on each route.
1020 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1022 /* Connect tracks to monitor section. Note that in an
1023 existing session, the internal sends will already exist, but we want the
1024 routes to notice that they connect to the control out specifically.
1028 boost::shared_ptr<RouteList> r = routes.reader ();
1029 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1031 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1033 if ((*x)->is_monitor()) {
1035 } else if ((*x)->is_master()) {
1038 (*x)->remove_aux_or_listen (_monitor_out);
1043 remove_route (_monitor_out);
1044 auto_connect_master_bus ();
1047 auditioner->connect ();
1049 Config->ParameterChanged ("use-monitor-bus");
1053 Session::add_monitor_section ()
1057 if (_monitor_out || !_master_out || Profile->get_trx()) {
1061 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1067 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1068 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
1071 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1072 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1073 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1075 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1080 add_routes (rl, false, false, false);
1082 assert (_monitor_out);
1084 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1085 are undefined, at best.
1088 uint32_t limit = _monitor_out->n_inputs().n_audio();
1092 /* connect the inputs to the master bus outputs. this
1093 * represents a separate data feed from the internal sends from
1094 * each route. as of jan 2011, it allows the monitor section to
1095 * conditionally ignore either the internal sends or the normal
1096 * input feed, but we should really find a better way to do
1100 _master_out->output()->disconnect (this);
1102 for (uint32_t n = 0; n < limit; ++n) {
1103 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1104 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1107 string connect_to = o->name();
1108 if (_monitor_out->input()->connect (p, connect_to, this)) {
1109 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1117 /* if monitor section is not connected, connect it to physical outs
1120 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
1122 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1124 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1127 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1129 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1130 Config->get_monitor_bus_preferred_bundle())
1136 /* Monitor bus is audio only */
1138 vector<string> outputs[DataType::num_types];
1140 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1141 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1144 uint32_t mod = outputs[DataType::AUDIO].size();
1145 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1149 for (uint32_t n = 0; n < limit; ++n) {
1151 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1153 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1154 connect_to = outputs[DataType::AUDIO][n % mod];
1157 if (!connect_to.empty()) {
1158 if (_monitor_out->output()->connect (p, connect_to, this)) {
1159 error << string_compose (
1160 _("cannot connect control output %1 to %2"),
1171 /* Hold process lock while doing this so that we don't hear bits and
1172 * pieces of audio as we work on each route.
1175 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1177 /* Connect tracks to monitor section. Note that in an
1178 existing session, the internal sends will already exist, but we want the
1179 routes to notice that they connect to the control out specifically.
1183 boost::shared_ptr<RouteList> rls = routes.reader ();
1185 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1187 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1189 if ((*x)->is_monitor()) {
1191 } else if ((*x)->is_master()) {
1194 (*x)->enable_monitor_send ();
1199 auditioner->connect ();
1201 Config->ParameterChanged ("use-monitor-bus");
1205 Session::reset_monitor_section ()
1207 /* Process lock should be held by the caller.*/
1209 if (!_monitor_out || Profile->get_trx()) {
1213 uint32_t limit = _master_out->n_outputs().n_audio();
1215 /* connect the inputs to the master bus outputs. this
1216 * represents a separate data feed from the internal sends from
1217 * each route. as of jan 2011, it allows the monitor section to
1218 * conditionally ignore either the internal sends or the normal
1219 * input feed, but we should really find a better way to do
1223 _master_out->output()->disconnect (this);
1224 _monitor_out->output()->disconnect (this);
1226 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1227 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1229 for (uint32_t n = 0; n < limit; ++n) {
1230 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1231 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1234 string connect_to = o->name();
1235 if (_monitor_out->input()->connect (p, connect_to, this)) {
1236 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1243 /* connect monitor section to physical outs
1246 if (Config->get_auto_connect_standard_busses()) {
1248 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1250 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1253 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1255 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1256 Config->get_monitor_bus_preferred_bundle())
1262 /* Monitor bus is audio only */
1264 vector<string> outputs[DataType::num_types];
1266 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1267 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1270 uint32_t mod = outputs[DataType::AUDIO].size();
1271 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1275 for (uint32_t n = 0; n < limit; ++n) {
1277 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1279 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1280 connect_to = outputs[DataType::AUDIO][n % mod];
1283 if (!connect_to.empty()) {
1284 if (_monitor_out->output()->connect (p, connect_to, this)) {
1285 error << string_compose (
1286 _("cannot connect control output %1 to %2"),
1297 /* Connect tracks to monitor section. Note that in an
1298 existing session, the internal sends will already exist, but we want the
1299 routes to notice that they connect to the control out specifically.
1303 boost::shared_ptr<RouteList> rls = routes.reader ();
1305 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1307 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1309 if ((*x)->is_monitor()) {
1311 } else if ((*x)->is_master()) {
1314 (*x)->enable_monitor_send ();
1320 Session::hookup_io ()
1322 /* stop graph reordering notifications from
1323 causing resorts, etc.
1326 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1330 /* we delay creating the auditioner till now because
1331 it makes its own connections to ports.
1335 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1337 throw failed_constructor ();
1339 a->use_new_diskstream ();
1343 catch (failed_constructor& err) {
1344 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1348 /* load bundles, which we may have postponed earlier on */
1349 if (_bundle_xml_node) {
1350 load_bundles (*_bundle_xml_node);
1351 delete _bundle_xml_node;
1354 /* Tell all IO objects to connect themselves together */
1356 IO::enable_connecting ();
1358 /* Now tell all "floating" ports to connect to whatever
1359 they should be connected to.
1362 AudioEngine::instance()->reconnect_ports ();
1364 /* Anyone who cares about input state, wake up and do something */
1366 IOConnectionsComplete (); /* EMIT SIGNAL */
1368 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1370 /* now handle the whole enchilada as if it was one
1371 graph reorder event.
1376 /* update the full solo state, which can't be
1377 correctly determined on a per-route basis, but
1378 needs the global overview that only the session
1382 update_route_solo_state ();
1386 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1388 boost::shared_ptr<Track> track = wp.lock ();
1393 boost::shared_ptr<Playlist> playlist;
1395 if ((playlist = track->playlist()) != 0) {
1396 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1397 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1398 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1403 Session::record_enabling_legal () const
1405 /* this used to be in here, but survey says.... we don't need to restrict it */
1406 // if (record_status() == Recording) {
1410 if (Config->get_all_safe()) {
1417 Session::set_track_monitor_input_status (bool yn)
1419 boost::shared_ptr<RouteList> rl = routes.reader ();
1420 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1421 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1422 if (tr && tr->record_enabled ()) {
1423 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1424 tr->request_input_monitoring (yn);
1430 Session::auto_punch_start_changed (Location* location)
1432 replace_event (SessionEvent::PunchIn, location->start());
1434 if (get_record_enabled() && config.get_punch_in()) {
1435 /* capture start has been changed, so save new pending state */
1436 save_state ("", true);
1441 Session::auto_punch_end_changed (Location* location)
1443 framepos_t when_to_stop = location->end();
1444 // when_to_stop += _worst_output_latency + _worst_input_latency;
1445 replace_event (SessionEvent::PunchOut, when_to_stop);
1449 Session::auto_punch_changed (Location* location)
1451 framepos_t when_to_stop = location->end();
1453 replace_event (SessionEvent::PunchIn, location->start());
1454 //when_to_stop += _worst_output_latency + _worst_input_latency;
1455 replace_event (SessionEvent::PunchOut, when_to_stop);
1458 /** @param loc A loop location.
1459 * @param pos Filled in with the start time of the required fade-out (in session frames).
1460 * @param length Filled in with the length of the required fade-out.
1463 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1465 pos = max (loc->start(), loc->end() - 64);
1466 length = loc->end() - pos;
1470 Session::auto_loop_changed (Location* location)
1472 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1475 auto_loop_declick_range (location, dcp, dcl);
1477 if (transport_rolling() && play_loop) {
1479 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1481 // if (_transport_frame > location->end()) {
1483 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1484 // relocate to beginning of loop
1485 clear_events (SessionEvent::LocateRoll);
1487 request_locate (location->start(), true);
1490 else if (Config->get_seamless_loop() && !loop_changing) {
1492 // schedule a locate-roll to refill the diskstreams at the
1493 // previous loop end
1494 loop_changing = true;
1496 if (location->end() > last_loopend) {
1497 clear_events (SessionEvent::LocateRoll);
1498 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1504 clear_events (SessionEvent::AutoLoopDeclick);
1505 clear_events (SessionEvent::AutoLoop);
1508 /* possibly move playhead if not rolling; if we are rolling we'll move
1509 to the loop start on stop if that is appropriate.
1514 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1515 if (pos == location->start()) {
1516 request_locate (pos);
1521 last_loopend = location->end();
1526 Session::set_auto_punch_location (Location* location)
1530 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1531 punch_connections.drop_connections();
1532 existing->set_auto_punch (false, this);
1533 remove_event (existing->start(), SessionEvent::PunchIn);
1534 clear_events (SessionEvent::PunchOut);
1535 auto_punch_location_changed (0);
1540 if (location == 0) {
1544 if (location->end() <= location->start()) {
1545 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1549 punch_connections.drop_connections ();
1551 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1552 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1553 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1555 location->set_auto_punch (true, this);
1557 auto_punch_changed (location);
1559 auto_punch_location_changed (location);
1563 Session::set_session_extents (framepos_t start, framepos_t end)
1566 if ((existing = _locations->session_range_location()) == 0) {
1567 //if there is no existing session, we need to make a new session location (should never happen)
1568 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1572 error << _("Session: you can't use that location for session start/end)") << endmsg;
1576 existing->set( start, end );
1582 Session::set_auto_loop_location (Location* location)
1586 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1587 loop_connections.drop_connections ();
1588 existing->set_auto_loop (false, this);
1589 remove_event (existing->end(), SessionEvent::AutoLoop);
1592 auto_loop_declick_range (existing, dcp, dcl);
1593 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1594 auto_loop_location_changed (0);
1599 if (location == 0) {
1603 if (location->end() <= location->start()) {
1604 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1608 last_loopend = location->end();
1610 loop_connections.drop_connections ();
1612 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1613 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1614 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1615 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1617 location->set_auto_loop (true, this);
1619 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1620 // set all tracks to use internal looping
1621 boost::shared_ptr<RouteList> rl = routes.reader ();
1622 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1623 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1624 if (tr && !tr->hidden()) {
1625 tr->set_loop (location);
1630 /* take care of our stuff first */
1632 auto_loop_changed (location);
1634 /* now tell everyone else */
1636 auto_loop_location_changed (location);
1640 Session::update_marks (Location*)
1646 Session::update_skips (Location* loc, bool consolidate)
1648 if (_ignore_skips_updates) {
1652 Locations::LocationList skips;
1655 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1656 consolidate_skips (loc);
1659 sync_locations_to_skips ();
1665 Session::consolidate_skips (Location* loc)
1667 Locations::LocationList all_locations = _locations->list ();
1669 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1671 if (!(*l)->is_skip ()) {
1676 /* don't test against self */
1683 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1684 case Evoral::OverlapInternal:
1685 case Evoral::OverlapExternal:
1686 case Evoral::OverlapStart:
1687 case Evoral::OverlapEnd:
1688 /* adjust new location to cover existing one */
1689 loc->set_start (min (loc->start(), (*l)->start()));
1690 loc->set_end (max (loc->end(), (*l)->end()));
1691 /* we don't need this one any more */
1692 _locations->remove (*l);
1693 /* the location has been deleted, so remove reference to it in our local list */
1694 l = all_locations.erase (l);
1697 case Evoral::OverlapNone:
1705 Session::sync_locations_to_skips ()
1707 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1708 * Session::_sync_locations_to_skips() from the audioengine thread.
1710 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1714 Session::_sync_locations_to_skips ()
1716 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1718 Locations::LocationList const & locs (_locations->list());
1720 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1722 Location* location = *i;
1724 if (location->is_skip() && location->is_skipping()) {
1725 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1733 Session::location_added (Location *location)
1735 if (location->is_auto_punch()) {
1736 set_auto_punch_location (location);
1739 if (location->is_auto_loop()) {
1740 set_auto_loop_location (location);
1743 if (location->is_session_range()) {
1744 /* no need for any signal handling or event setting with the session range,
1745 because we keep a direct reference to it and use its start/end directly.
1747 _session_range_location = location;
1750 if (location->is_mark()) {
1751 /* listen for per-location signals that require us to do any * global updates for marks */
1753 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1754 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1755 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1756 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1759 if (location->is_skip()) {
1760 /* listen for per-location signals that require us to update skip-locate events */
1762 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1763 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1764 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1765 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1767 update_skips (location, true);
1774 Session::location_removed (Location *location)
1776 if (location->is_auto_loop()) {
1777 set_auto_loop_location (0);
1778 set_track_loop (false);
1781 if (location->is_auto_punch()) {
1782 set_auto_punch_location (0);
1785 if (location->is_session_range()) {
1786 /* this is never supposed to happen */
1787 error << _("programming error: session range removed!") << endl;
1790 if (location->is_skip()) {
1792 update_skips (location, false);
1799 Session::locations_changed ()
1801 _locations->apply (*this, &Session::_locations_changed);
1805 Session::_locations_changed (const Locations::LocationList& locations)
1807 /* There was some mass-change in the Locations object.
1809 We might be re-adding a location here but it doesn't actually matter
1810 for all the locations that the Session takes an interest in.
1814 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1815 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1816 location_added (*i);
1820 update_skips (NULL, false);
1824 Session::enable_record ()
1826 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1827 /* no recording at anything except normal speed */
1832 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1834 if (rs == Recording) {
1838 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1840 _last_record_location = _transport_frame;
1841 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1843 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1844 set_track_monitor_input_status (true);
1847 RecordStateChanged ();
1854 Session::set_all_tracks_record_enabled (bool enable )
1856 boost::shared_ptr<RouteList> rl = routes.reader();
1857 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1858 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1860 tr->set_record_enabled (enable, Controllable::NoGroup);
1867 Session::disable_record (bool rt_context, bool force)
1871 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1873 if (!Config->get_latched_record_enable () || force) {
1874 g_atomic_int_set (&_record_status, Disabled);
1875 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1877 if (rs == Recording) {
1878 g_atomic_int_set (&_record_status, Enabled);
1882 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1883 set_track_monitor_input_status (false);
1886 RecordStateChanged (); /* emit signal */
1889 remove_pending_capture_state ();
1895 Session::step_back_from_record ()
1897 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1899 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1900 set_track_monitor_input_status (false);
1903 RecordStateChanged (); /* emit signal */
1908 Session::maybe_enable_record ()
1910 if (_step_editors > 0) {
1914 g_atomic_int_set (&_record_status, Enabled);
1916 /* This function is currently called from somewhere other than an RT thread.
1917 This save_state() call therefore doesn't impact anything. Doing it here
1918 means that we save pending state of which sources the next record will use,
1919 which gives us some chance of recovering from a crash during the record.
1922 save_state ("", true);
1924 if (_transport_speed) {
1925 if (!config.get_punch_in()) {
1929 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1930 RecordStateChanged (); /* EMIT SIGNAL */
1937 Session::audible_frame () const
1943 offset = worst_playback_latency ();
1945 if (synced_to_engine()) {
1946 /* Note: this is basically just sync-to-JACK */
1947 tf = _engine.transport_frame();
1949 tf = _transport_frame;
1954 if (!non_realtime_work_pending()) {
1958 /* Check to see if we have passed the first guaranteed
1959 audible frame past our last start position. if not,
1960 return that last start point because in terms
1961 of audible frames, we have not moved yet.
1963 `Start position' in this context means the time we last
1964 either started, located, or changed transport direction.
1967 if (_transport_speed > 0.0f) {
1969 if (!play_loop || !have_looped) {
1970 if (tf < _last_roll_or_reversal_location + offset) {
1971 return _last_roll_or_reversal_location;
1979 } else if (_transport_speed < 0.0f) {
1981 /* XXX wot? no backward looping? */
1983 if (tf > _last_roll_or_reversal_location - offset) {
1984 return _last_roll_or_reversal_location;
1996 Session::set_frame_rate (framecnt_t frames_per_second)
1998 /** \fn void Session::set_frame_size(framecnt_t)
1999 the AudioEngine object that calls this guarantees
2000 that it will not be called while we are also in
2001 ::process(). Its fine to do things that block
2005 _base_frame_rate = frames_per_second;
2006 _nominal_frame_rate = frames_per_second;
2011 reset_write_sources (false);
2013 // XXX we need some equivalent to this, somehow
2014 // SndFileSource::setup_standard_crossfades (frames_per_second);
2018 /* XXX need to reset/reinstantiate all LADSPA plugins */
2022 Session::set_block_size (pframes_t nframes)
2024 /* the AudioEngine guarantees
2025 that it will not be called while we are also in
2026 ::process(). It is therefore fine to do things that block
2031 current_block_size = nframes;
2035 boost::shared_ptr<RouteList> r = routes.reader ();
2037 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2038 (*i)->set_block_size (nframes);
2041 boost::shared_ptr<RouteList> rl = routes.reader ();
2042 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2043 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2045 tr->set_block_size (nframes);
2049 set_worst_io_latencies ();
2055 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2057 boost::shared_ptr<Route> r2;
2059 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2060 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2064 /* make a copy of the existing list of routes that feed r1 */
2066 Route::FedBy existing (r1->fed_by());
2068 /* for each route that feeds r1, recurse, marking it as feeding
2072 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2073 if (!(r2 = i->r.lock ())) {
2074 /* (*i) went away, ignore it */
2078 /* r2 is a route that feeds r1 which somehow feeds base. mark
2079 base as being fed by r2
2082 rbase->add_fed_by (r2, i->sends_only);
2086 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2090 if (r1->feeds (r2) && r2->feeds (r1)) {
2094 /* now recurse, so that we can mark base as being fed by
2095 all routes that feed r2
2098 trace_terminal (r2, rbase);
2105 Session::resort_routes ()
2107 /* don't do anything here with signals emitted
2108 by Routes during initial setup or while we
2109 are being destroyed.
2112 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2116 if (_route_deletion_in_progress) {
2121 RCUWriter<RouteList> writer (routes);
2122 boost::shared_ptr<RouteList> r = writer.get_copy ();
2123 resort_routes_using (r);
2124 /* writer goes out of scope and forces update */
2128 boost::shared_ptr<RouteList> rl = routes.reader ();
2129 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2130 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2132 const Route::FedBy& fb ((*i)->fed_by());
2134 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2135 boost::shared_ptr<Route> sf = f->r.lock();
2137 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2145 /** This is called whenever we need to rebuild the graph of how we will process
2147 * @param r List of routes, in any order.
2151 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2153 /* We are going to build a directed graph of our routes;
2154 this is where the edges of that graph are put.
2159 /* Go through all routes doing two things:
2161 * 1. Collect the edges of the route graph. Each of these edges
2162 * is a pair of routes, one of which directly feeds the other
2163 * either by a JACK connection or by an internal send.
2165 * 2. Begin the process of making routes aware of which other
2166 * routes directly or indirectly feed them. This information
2167 * is used by the solo code.
2170 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2172 /* Clear out the route's list of direct or indirect feeds */
2173 (*i)->clear_fed_by ();
2175 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2177 bool via_sends_only;
2179 /* See if this *j feeds *i according to the current state of the JACK
2180 connections and internal sends.
2182 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2183 /* add the edge to the graph (part #1) */
2184 edges.add (*j, *i, via_sends_only);
2185 /* tell the route (for part #2) */
2186 (*i)->add_fed_by (*j, via_sends_only);
2191 /* Attempt a topological sort of the route graph */
2192 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2194 if (sorted_routes) {
2195 /* We got a satisfactory topological sort, so there is no feedback;
2198 Note: the process graph rechain does not require a
2199 topologically-sorted list, but hey ho.
2201 if (_process_graph) {
2202 _process_graph->rechain (sorted_routes, edges);
2205 _current_route_graph = edges;
2207 /* Complete the building of the routes' lists of what directly
2208 or indirectly feeds them.
2210 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2211 trace_terminal (*i, *i);
2214 *r = *sorted_routes;
2217 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2218 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2219 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2220 (*i)->name(), (*i)->order_key ()));
2224 SuccessfulGraphSort (); /* EMIT SIGNAL */
2227 /* The topological sort failed, so we have a problem. Tell everyone
2228 and stick to the old graph; this will continue to be processed, so
2229 until the feedback is fixed, what is played back will not quite
2230 reflect what is actually connected. Note also that we do not
2231 do trace_terminal here, as it would fail due to an endless recursion,
2232 so the solo code will think that everything is still connected
2236 FeedbackDetected (); /* EMIT SIGNAL */
2241 /** Find a route name starting with \a base, maybe followed by the
2242 * lowest \a id. \a id will always be added if \a definitely_add_number
2243 * is true on entry; otherwise it will only be added if required
2244 * to make the name unique.
2246 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2247 * The available route name with the lowest ID will be used, and \a id
2248 * will be set to the ID.
2250 * \return false if a route name could not be found, and \a track_name
2251 * and \a id do not reflect a free route name.
2254 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2256 /* the base may conflict with ports that do not belong to existing
2257 routes, but hidden objects like the click track. So check port names
2258 before anything else.
2261 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2262 if (base == *reserved) {
2263 /* Check if this reserved name already exists, and if
2264 so, disallow it without a numeric suffix.
2266 if (route_by_name (*reserved)) {
2267 definitely_add_number = true;
2276 if (!definitely_add_number && route_by_name (base) == 0) {
2277 /* juse use the base */
2283 name = string_compose ("%1 %2", base, id);
2285 if (route_by_name (name) == 0) {
2291 } while (id < (UINT_MAX-1));
2296 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2298 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2300 in = ChanCount::ZERO;
2301 out = ChanCount::ZERO;
2303 boost::shared_ptr<RouteList> r = routes.reader ();
2305 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2306 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2307 if (tr && !tr->is_auditioner()) {
2308 in += tr->n_inputs();
2309 out += tr->n_outputs();
2315 Session::default_track_name_pattern (DataType t)
2318 case DataType::AUDIO:
2319 if (Profile->get_trx()) {
2326 case DataType::MIDI:
2333 /** Caller must not hold process lock
2334 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2335 * @param instrument plugin info for the instrument to insert pre-fader, if any
2337 list<boost::shared_ptr<MidiTrack> >
2338 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2339 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2342 uint32_t track_id = 0;
2344 RouteList new_routes;
2345 list<boost::shared_ptr<MidiTrack> > ret;
2347 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2348 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2351 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2352 error << "cannot find name for new midi track" << endmsg;
2356 boost::shared_ptr<MidiTrack> track;
2359 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2361 if (track->init ()) {
2365 track->use_new_diskstream();
2367 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2368 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2371 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2372 if (track->input()->ensure_io (input, false, this)) {
2373 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2377 if (track->output()->ensure_io (output, false, this)) {
2378 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2383 track->non_realtime_input_change();
2386 route_group->add (track);
2389 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2391 if (Config->get_remote_model() == UserOrdered) {
2392 track->set_remote_control_id (next_control_id());
2395 new_routes.push_back (track);
2396 ret.push_back (track);
2398 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2401 catch (failed_constructor &err) {
2402 error << _("Session: could not create new midi track.") << endmsg;
2406 catch (AudioEngine::PortRegistrationFailure& pfe) {
2408 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;
2416 if (!new_routes.empty()) {
2417 StateProtector sp (this);
2418 if (Profile->get_trx()) {
2419 add_routes (new_routes, false, false, false);
2421 add_routes (new_routes, true, true, false);
2425 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2426 PluginPtr plugin = instrument->load (*this);
2427 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2428 (*r)->add_processor (p, PreFader);
2438 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2440 boost::shared_ptr<Route> midi_track (wmt.lock());
2446 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2448 if (change.after.n_audio() <= change.before.n_audio()) {
2452 /* new audio ports: make sure the audio goes somewhere useful,
2453 unless the user has no-auto-connect selected.
2455 The existing ChanCounts don't matter for this call as they are only
2456 to do with matching input and output indices, and we are only changing
2462 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
2466 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
2467 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
2468 * @param output_start As \a input_start, but for outputs.
2471 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
2472 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
2474 if (!IO::connecting_legal) {
2478 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2484 /* If both inputs and outputs are auto-connected to physical ports,
2485 use the max of input and output offsets to ensure auto-connected
2486 port numbers always match up (e.g. the first audio input and the
2487 first audio output of the route will have the same physical
2488 port number). Otherwise just use the lowest input or output
2492 DEBUG_TRACE (DEBUG::Graph,
2493 string_compose("Auto-connect: existing in = %1 out = %2\n",
2494 existing_inputs, existing_outputs));
2496 const bool in_out_physical =
2497 (Config->get_input_auto_connect() & AutoConnectPhysical)
2498 && (Config->get_output_auto_connect() & AutoConnectPhysical)
2501 const ChanCount in_offset = in_out_physical
2502 ? ChanCount::max(existing_inputs, existing_outputs)
2505 const ChanCount out_offset = in_out_physical
2506 ? ChanCount::max(existing_inputs, existing_outputs)
2509 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2510 vector<string> physinputs;
2511 vector<string> physoutputs;
2513 _engine.get_physical_outputs (*t, physoutputs);
2514 _engine.get_physical_inputs (*t, physinputs);
2516 if (!physinputs.empty() && connect_inputs) {
2517 uint32_t nphysical_in = physinputs.size();
2519 DEBUG_TRACE (DEBUG::Graph,
2520 string_compose("There are %1 physical inputs of type %2\n",
2523 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2526 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2527 DEBUG_TRACE (DEBUG::Graph,
2528 string_compose("Get index %1 + %2 % %3 = %4\n",
2529 in_offset.get(*t), i, nphysical_in,
2530 (in_offset.get(*t) + i) % nphysical_in));
2531 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2534 DEBUG_TRACE (DEBUG::Graph,
2535 string_compose("Connect route %1 IN to %2\n",
2536 route->name(), port));
2538 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2542 ChanCount one_added (*t, 1);
2543 existing_inputs += one_added;
2547 if (!physoutputs.empty()) {
2548 uint32_t nphysical_out = physoutputs.size();
2549 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2553 * do not create new connections if we reached the limit of physical outputs
2557 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
2558 ARDOUR::Profile->get_trx () &&
2559 existing_outputs.get(*t) == nphysical_out ) {
2563 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2564 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2565 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2566 /* master bus is audio only */
2567 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2568 port = _master_out->input()->ports().port(*t,
2569 i % _master_out->input()->n_ports().get(*t))->name();
2573 DEBUG_TRACE (DEBUG::Graph,
2574 string_compose("Connect route %1 OUT to %2\n",
2575 route->name(), port));
2577 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2581 ChanCount one_added (*t, 1);
2582 existing_outputs += one_added;
2588 #ifdef USE_TRACKS_CODE_FEATURES
2591 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2593 return route1->remote_control_id() < route2->remote_control_id();
2597 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2599 // it is not allowed to perform connection
2600 if (!IO::connecting_legal) {
2604 // if we are deleting routes we will call this once at the end
2605 if (_route_deletion_in_progress) {
2609 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2615 // We need to disconnect the route's inputs and outputs first
2616 // basing on autoconnect configuration
2617 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2618 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2620 ChanCount existing_inputs;
2621 ChanCount existing_outputs;
2622 count_existing_track_channels (existing_inputs, existing_outputs);
2624 //ChanCount inputs = ChanCount::ZERO;
2625 //ChanCount outputs = ChanCount::ZERO;
2627 RouteList existing_routes = *routes.reader ();
2628 existing_routes.sort (compare_routes_by_remote_id);
2631 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2633 vector<string> physinputs;
2634 vector<string> physoutputs;
2636 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2637 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2639 uint32_t input_n = 0;
2640 uint32_t output_n = 0;
2641 RouteList::iterator rIter = existing_routes.begin();
2642 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2643 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2644 for (; rIter != existing_routes.end(); ++rIter) {
2645 if (*rIter == _master_out || *rIter == _monitor_out ) {
2649 if (current_output_auto_connection == AutoConnectPhysical) {
2650 (*rIter)->amp()->deactivate();
2651 } else if (current_output_auto_connection == AutoConnectMaster) {
2652 (*rIter)->amp()->activate();
2655 if (reconnectIputs) {
2656 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2658 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2660 if (current_input_auto_connection & AutoConnectPhysical) {
2662 if ( input_n == physinputs.size() ) {
2666 string port = physinputs[input_n];
2668 if (port.empty() ) {
2669 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2672 //GZ: check this; could be heavy
2673 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2679 if (reconnectOutputs) {
2681 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2682 if (current_output_auto_connection & AutoConnectPhysical) {
2684 //GZ: check this; could be heavy
2685 (*rIter)->output()->disconnect (this);
2686 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2688 //GZ: check this; could be heavy
2689 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2691 } else if (current_output_auto_connection & AutoConnectMaster){
2693 if (!reconnect_master) {
2697 //GZ: check this; could be heavy
2698 (*rIter)->output()->disconnect (this);
2701 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2702 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2704 error << error << "Master bus is not available" << endmsg;
2709 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2710 if (current_output_auto_connection & AutoConnectPhysical) {
2712 if ( output_n == physoutputs.size() ) {
2716 string port = physoutputs[output_n];
2718 if (port.empty() ) {
2719 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2722 //GZ: check this; could be heavy
2723 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2726 } else if (current_output_auto_connection & AutoConnectMaster) {
2728 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2732 // connect to master bus
2733 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2735 if (port.empty() ) {
2736 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2740 //GZ: check this; could be heavy
2741 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2747 //auto_connect_route (*rIter, inputs, outputs, false, reconnectIputs);
2750 _master_out->output()->disconnect (this);
2751 auto_connect_master_bus ();
2756 session_routes_reconnected (); /* EMIT SIGNAL */
2760 Session::reconnect_midi_scene_ports(bool inputs)
2764 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2766 scene_in_ptr->disconnect_all ();
2768 std::vector<EngineStateController::MidiPortState> midi_port_states;
2769 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2771 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2773 for (; state_iter != midi_port_states.end(); ++state_iter) {
2774 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2775 scene_in_ptr->connect (state_iter->name);
2782 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2784 if (scene_out_ptr ) {
2785 scene_out_ptr->disconnect_all ();
2787 std::vector<EngineStateController::MidiPortState> midi_port_states;
2788 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2790 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2792 for (; state_iter != midi_port_states.end(); ++state_iter) {
2793 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2794 scene_out_ptr->connect (state_iter->name);
2802 Session::reconnect_mtc_ports ()
2804 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2810 mtc_in_ptr->disconnect_all ();
2812 std::vector<EngineStateController::MidiPortState> midi_port_states;
2813 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2815 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2817 for (; state_iter != midi_port_states.end(); ++state_iter) {
2818 if (state_iter->available && state_iter->mtc_in) {
2819 mtc_in_ptr->connect (state_iter->name);
2823 if (!_midi_ports->mtc_input_port ()->connected () &&
2824 config.get_external_sync () &&
2825 (Config->get_sync_source () == MTC) ) {
2826 config.set_external_sync (false);
2829 if ( ARDOUR::Profile->get_trx () ) {
2830 // Tracks need this signal to update timecode_source_dropdown
2831 MtcOrLtcInputPortChanged (); //emit signal
2836 Session::reconnect_mmc_ports(bool inputs)
2838 if (inputs ) { // get all enabled midi input ports
2840 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2842 mmc_in_ptr->disconnect_all ();
2843 std::vector<std::string> enabled_midi_inputs;
2844 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2846 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2848 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2849 mmc_in_ptr->connect (*port_iter);
2853 } else { // get all enabled midi output ports
2855 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2857 mmc_out_ptr->disconnect_all ();
2858 std::vector<std::string> enabled_midi_outputs;
2859 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2861 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2863 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2864 mmc_out_ptr->connect (*port_iter);
2872 /** Caller must not hold process lock
2873 * @param name_template string to use for the start of the name, or "" to use "Audio".
2875 list< boost::shared_ptr<AudioTrack> >
2876 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2877 uint32_t how_many, string name_template)
2880 uint32_t track_id = 0;
2882 RouteList new_routes;
2883 list<boost::shared_ptr<AudioTrack> > ret;
2885 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2886 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2890 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2891 error << "cannot find name for new audio track" << endmsg;
2895 boost::shared_ptr<AudioTrack> track;
2898 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2900 if (track->init ()) {
2904 if (ARDOUR::Profile->get_trx ()) {
2905 // TRACKS considers it's not a USE CASE, it's
2906 // a piece of behavior of the session model:
2908 // Gain for a newly created route depends on
2909 // the current output_auto_connect mode:
2911 // 0 for Stereo Out mode
2913 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2914 track->set_gain (dB_to_coefficient (0), Controllable::NoGroup);
2918 track->use_new_diskstream();
2920 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2921 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2924 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2926 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2927 error << string_compose (
2928 _("cannot configure %1 in/%2 out configuration for new audio track"),
2929 input_channels, output_channels)
2934 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2935 error << string_compose (
2936 _("cannot configure %1 in/%2 out configuration for new audio track"),
2937 input_channels, output_channels)
2944 route_group->add (track);
2947 track->non_realtime_input_change();
2949 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2950 if (Config->get_remote_model() == UserOrdered) {
2951 track->set_remote_control_id (next_control_id());
2954 new_routes.push_back (track);
2955 ret.push_back (track);
2957 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2960 catch (failed_constructor &err) {
2961 error << _("Session: could not create new audio track.") << endmsg;
2965 catch (AudioEngine::PortRegistrationFailure& pfe) {
2967 error << pfe.what() << endmsg;
2975 if (!new_routes.empty()) {
2976 StateProtector sp (this);
2977 if (Profile->get_trx()) {
2978 add_routes (new_routes, false, false, false);
2980 add_routes (new_routes, true, true, false);
2987 /** Caller must not hold process lock.
2988 * @param name_template string to use for the start of the name, or "" to use "Bus".
2991 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2994 uint32_t bus_id = 0;
2998 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3001 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3002 error << "cannot find name for new audio bus" << endmsg;
3007 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3013 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
3014 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
3017 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3019 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3020 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3021 input_channels, output_channels)
3027 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3028 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3029 input_channels, output_channels)
3036 route_group->add (bus);
3038 if (Config->get_remote_model() == UserOrdered) {
3039 bus->set_remote_control_id (next_control_id());
3042 bus->add_internal_return ();
3044 ret.push_back (bus);
3046 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3052 catch (failed_constructor &err) {
3053 error << _("Session: could not create new audio route.") << endmsg;
3057 catch (AudioEngine::PortRegistrationFailure& pfe) {
3058 error << pfe.what() << endmsg;
3068 StateProtector sp (this);
3069 if (Profile->get_trx()) {
3070 add_routes (ret, false, false, false);
3072 add_routes (ret, false, true, true); // autoconnect // outputs only
3081 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3085 if (!tree.read (template_path.c_str())) {
3089 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3093 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3096 uint32_t control_id;
3097 uint32_t number = 0;
3098 const uint32_t being_added = how_many;
3099 /* This will prevent the use of any existing XML-provided PBD::ID
3102 Stateful::ForceIDRegeneration force_ids;
3103 IO::disable_connecting ();
3105 control_id = next_control_id ();
3109 /* We're going to modify the node contents a bit so take a
3110 * copy. The node may be re-used when duplicating more than once.
3113 XMLNode node_copy (node);
3118 if (!name_base.empty()) {
3120 /* if we're adding more than one routes, force
3121 * all the names of the new routes to be
3122 * numbered, via the final parameter.
3125 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3126 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3132 string const route_name = node_copy.property(X_("name"))->value ();
3134 /* generate a new name by adding a number to the end of the template name */
3135 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3136 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3137 abort(); /*NOTREACHED*/
3141 /* set this name in the XML description that we are about to use */
3143 bool rename_playlist;
3146 rename_playlist = true;
3150 rename_playlist = false;
3153 Route::set_name_in_state (node_copy, name, rename_playlist);
3155 /* trim bitslots from listen sends so that new ones are used */
3156 XMLNodeList children = node_copy.children ();
3157 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3158 if ((*i)->name() == X_("Processor")) {
3159 XMLProperty* role = (*i)->property (X_("role"));
3160 if (role && role->value() == X_("Listen")) {
3161 (*i)->remove_property (X_("bitslot"));
3166 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3169 error << _("Session: cannot create track/bus from template description") << endmsg;
3173 if (boost::dynamic_pointer_cast<Track>(route)) {
3174 /* force input/output change signals so that the new diskstream
3175 picks up the configuration of the route. During session
3176 loading this normally happens in a different way.
3179 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3181 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3182 change.after = route->input()->n_ports();
3183 route->input()->changed (change, this);
3184 change.after = route->output()->n_ports();
3185 route->output()->changed (change, this);
3188 route->set_remote_control_id (control_id);
3191 boost::shared_ptr<Track> track;
3193 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3196 track->use_new_playlist ();
3199 track->use_copy_playlist ();
3206 ret.push_back (route);
3208 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3211 catch (failed_constructor &err) {
3212 error << _("Session: could not create new route from template") << endmsg;
3216 catch (AudioEngine::PortRegistrationFailure& pfe) {
3217 error << pfe.what() << endmsg;
3226 StateProtector sp (this);
3227 if (Profile->get_trx()) {
3228 add_routes (ret, false, false, false);
3230 add_routes (ret, true, true, false);
3232 IO::enable_connecting ();
3239 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3242 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3243 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3246 error << _("Adding new tracks/busses failed") << endmsg;
3251 update_latency (true);
3252 update_latency (false);
3257 save_state (_current_snapshot_name);
3260 reassign_track_numbers();
3262 update_route_record_state ();
3264 RouteAdded (new_routes); /* EMIT SIGNAL */
3268 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3270 ChanCount existing_inputs;
3271 ChanCount existing_outputs;
3272 uint32_t order = next_control_id();
3274 if (_order_hint > -1) {
3275 order = _order_hint;
3279 count_existing_track_channels (existing_inputs, existing_outputs);
3282 RCUWriter<RouteList> writer (routes);
3283 boost::shared_ptr<RouteList> r = writer.get_copy ();
3284 r->insert (r->end(), new_routes.begin(), new_routes.end());
3286 /* if there is no control out and we're not in the middle of loading,
3287 resort the graph here. if there is a control out, we will resort
3288 toward the end of this method. if we are in the middle of loading,
3289 we will resort when done.
3292 if (!_monitor_out && IO::connecting_legal) {
3293 resort_routes_using (r);
3297 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3299 boost::weak_ptr<Route> wpr (*x);
3300 boost::shared_ptr<Route> r (*x);
3302 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
3303 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3304 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3305 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3306 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3307 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3309 if (r->is_master()) {
3313 if (r->is_monitor()) {
3317 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3319 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3320 track_playlist_changed (boost::weak_ptr<Track> (tr));
3321 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3323 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3325 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3326 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3331 if (input_auto_connect || output_auto_connect) {
3332 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
3335 /* order keys are a GUI responsibility but we need to set up
3336 reasonable defaults because they also affect the remote control
3337 ID in most situations.
3340 if (!r->has_order_key ()) {
3341 if (r->is_auditioner()) {
3342 /* use an arbitrarily high value */
3343 r->set_order_key (UINT_MAX);
3345 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3346 r->set_order_key (order);
3354 if (_monitor_out && IO::connecting_legal) {
3355 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3357 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3358 if ((*x)->is_monitor()) {
3360 } else if ((*x)->is_master()) {
3363 (*x)->enable_monitor_send ();
3370 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3372 boost::shared_ptr<RouteList> r = routes.reader ();
3373 boost::shared_ptr<Send> s;
3375 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3376 if ((s = (*i)->internal_send_for (dest)) != 0) {
3377 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3383 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3385 boost::shared_ptr<RouteList> r = routes.reader ();
3386 boost::shared_ptr<Send> s;
3388 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3389 if ((s = (*i)->internal_send_for (dest)) != 0) {
3390 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3396 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3398 boost::shared_ptr<RouteList> r = routes.reader ();
3399 boost::shared_ptr<Send> s;
3401 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3402 if ((s = (*i)->internal_send_for (dest)) != 0) {
3403 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3408 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3410 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3412 boost::shared_ptr<RouteList> r = routes.reader ();
3413 boost::shared_ptr<RouteList> t (new RouteList);
3415 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3416 /* no MIDI sends because there are no MIDI busses yet */
3417 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3422 add_internal_sends (dest, p, t);
3426 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3428 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3429 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3434 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3436 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3440 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3442 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3446 if (!dest->internal_return()) {
3447 dest->add_internal_return ();
3450 sender->add_aux_send (dest, before);
3457 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3459 { // RCU Writer scope
3460 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3461 RCUWriter<RouteList> writer (routes);
3462 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3465 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3467 if (*iter == _master_out) {
3471 (*iter)->set_solo (false, Controllable::NoGroup);
3475 /* deleting the master out seems like a dumb
3476 idea, but its more of a UI policy issue
3480 if (*iter == _master_out) {
3481 _master_out = boost::shared_ptr<Route> ();
3484 if (*iter == _monitor_out) {
3485 _monitor_out.reset ();
3488 // We need to disconnect the route's inputs and outputs
3490 (*iter)->input()->disconnect (0);
3491 (*iter)->output()->disconnect (0);
3493 /* if the route had internal sends sending to it, remove them */
3494 if ((*iter)->internal_return()) {
3496 boost::shared_ptr<RouteList> r = routes.reader ();
3497 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3498 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3500 (*i)->remove_processor (s);
3505 /* if the monitoring section had a pointer to this route, remove it */
3506 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3507 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3508 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3509 (*iter)->remove_aux_or_listen (_monitor_out);
3512 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3513 if (mt && mt->step_editing()) {
3514 if (_step_editors > 0) {
3520 /* writer goes out of scope, forces route list update */
3522 } // end of RCU Writer scope
3524 update_route_solo_state ();
3525 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3526 update_latency_compensation ();
3529 /* Re-sort routes to remove the graph's current references to the one that is
3530 * going away, then flush old references out of the graph.
3531 * Wave Tracks: reconnect routes
3534 #ifdef USE_TRACKS_CODE_FEATURES
3535 reconnect_existing_routes(true, false);
3537 routes.flush (); // maybe unsafe, see below.
3541 if (_process_graph) {
3542 _process_graph->clear_other_chain ();
3545 /* get rid of it from the dead wood collection in the route list manager */
3546 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3550 /* try to cause everyone to drop their references
3551 * and unregister ports from the backend
3554 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3555 (*iter)->drop_references ();
3558 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3560 /* save the new state of the world */
3562 if (save_state (_current_snapshot_name)) {
3563 save_history (_current_snapshot_name);
3566 reassign_track_numbers();
3567 update_route_record_state ();
3571 Session::remove_route (boost::shared_ptr<Route> route)
3573 boost::shared_ptr<RouteList> rl (new RouteList);
3574 rl->push_back (route);
3579 Session::route_mute_changed ()
3585 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3587 boost::shared_ptr<Route> route = wpr.lock();
3589 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_listen_changed")) << endmsg;
3593 if (route->listening_via_monitor ()) {
3595 if (Config->get_exclusive_solo()) {
3597 RouteGroup* rg = route->route_group ();
3598 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3600 boost::shared_ptr<RouteList> r = routes.reader ();
3602 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3603 if ((*i) == route) {
3604 /* already changed */
3608 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3609 /* route does not get solo propagated to it */
3613 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3614 /* this route is a part of the same solo group as the route
3615 * that was changed. Changing that route did change or will
3616 * change all group members appropriately, so we can ignore it
3621 (*i)->set_listen (false, Controllable::NoGroup);
3627 } else if (_listen_cnt > 0) {
3632 update_route_solo_state ();
3635 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3637 boost::shared_ptr<Route> route = wpr.lock ();
3640 /* should not happen */
3641 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_isolated_changed")) << endmsg;
3645 bool send_changed = false;
3647 if (route->solo_isolated()) {
3648 if (_solo_isolated_cnt == 0) {
3649 send_changed = true;
3651 _solo_isolated_cnt++;
3652 } else if (_solo_isolated_cnt > 0) {
3653 _solo_isolated_cnt--;
3654 if (_solo_isolated_cnt == 0) {
3655 send_changed = true;
3660 IsolatedChanged (); /* EMIT SIGNAL */
3665 Session::route_solo_changed (bool self_solo_change, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3667 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3669 if (!self_solo_change) {
3670 // session doesn't care about changes to soloed-by-others
3674 boost::shared_ptr<Route> route = wpr.lock ();
3677 boost::shared_ptr<RouteList> r = routes.reader ();
3680 if (route->self_soloed()) {
3686 /* the route may be a member of a group that has shared-solo
3687 * semantics. If so, then all members of that group should follow the
3688 * solo of the changed route. But ... this is optional, controlled by a
3689 * Controllable::GroupControlDisposition.
3691 * The first argument to the signal that this method is connected to is the
3692 * GroupControlDisposition value that was used to change solo.
3694 * If the solo change was done with group semantics (either InverseGroup
3695 * (force the entire group to change even if the group shared solo is
3696 * disabled) or UseGroup (use the group, which may or may not have the
3697 * shared solo property enabled)) then as we propagate the change to
3698 * the entire session we should IGNORE THE GROUP that the changed route
3702 RouteGroup* rg = route->route_group ();
3703 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3705 if (delta == 1 && Config->get_exclusive_solo()) {
3707 /* new solo: disable all other solos, but not the group if its solo-enabled */
3709 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3711 if ((*i) == route) {
3712 /* already changed */
3716 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3717 /* route does not get solo propagated to it */
3721 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3722 /* this route is a part of the same solo group as the route
3723 * that was changed. Changing that route did change or will
3724 * change all group members appropriately, so we can ignore it
3730 (*i)->set_solo (false, group_override);
3734 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3736 RouteList uninvolved;
3738 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3740 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3741 bool via_sends_only;
3742 bool in_signal_flow;
3744 if ((*i) == route) {
3745 /* already changed */
3749 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3750 /* route does not get solo propagated to it */
3754 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3755 /* this route is a part of the same solo group as the route
3756 * that was changed. Changing that route did change or will
3757 * change all group members appropriately, so we can ignore it
3763 in_signal_flow = false;
3765 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3767 if ((*i)->feeds (route, &via_sends_only)) {
3768 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3769 if (!via_sends_only) {
3770 if (!route->soloed_by_others_upstream()) {
3771 (*i)->mod_solo_by_others_downstream (delta);
3773 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3776 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3778 in_signal_flow = true;
3780 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3783 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3785 if (route->feeds (*i, &via_sends_only)) {
3786 /* propagate solo upstream only if routing other than
3787 sends is involved, but do consider the other route
3788 (*i) to be part of the signal flow even if only
3791 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3795 route->soloed_by_others_downstream(),
3796 route->soloed_by_others_upstream()));
3797 if (!via_sends_only) {
3798 //NB. Triggers Invert Push, which handles soloed by downstream
3799 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3800 (*i)->mod_solo_by_others_upstream (delta);
3802 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3804 in_signal_flow = true;
3806 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3809 if (!in_signal_flow) {
3810 uninvolved.push_back (*i);
3814 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3816 update_route_solo_state (r);
3818 /* now notify that the mute state of the routes not involved in the signal
3819 pathway of the just-solo-changed route may have altered.
3822 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3823 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3824 (*i)->act_on_mute ();
3825 (*i)->mute_changed ();
3828 SoloChanged (); /* EMIT SIGNAL */
3833 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3835 /* now figure out if anything that matters is soloed (or is "listening")*/
3837 bool something_soloed = false;
3838 bool something_listening = false;
3839 uint32_t listeners = 0;
3840 uint32_t isolated = 0;
3843 r = routes.reader();
3846 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3847 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3848 something_soloed = true;
3851 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3852 if (Config->get_solo_control_is_listen_control()) {
3854 something_listening = true;
3856 (*i)->set_listen (false, Controllable::NoGroup);
3860 if ((*i)->solo_isolated()) {
3865 if (something_soloed != _non_soloed_outs_muted) {
3866 _non_soloed_outs_muted = something_soloed;
3867 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3870 if (something_listening != _listening) {
3871 _listening = something_listening;
3872 SoloActive (_listening);
3875 _listen_cnt = listeners;
3877 if (isolated != _solo_isolated_cnt) {
3878 _solo_isolated_cnt = isolated;
3879 IsolatedChanged (); /* EMIT SIGNAL */
3882 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3883 something_soloed, listeners, isolated));
3886 boost::shared_ptr<RouteList>
3887 Session::get_routes_with_internal_returns() const
3889 boost::shared_ptr<RouteList> r = routes.reader ();
3890 boost::shared_ptr<RouteList> rl (new RouteList);
3892 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3893 if ((*i)->internal_return ()) {
3901 Session::io_name_is_legal (const std::string& name)
3903 boost::shared_ptr<RouteList> r = routes.reader ();
3905 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
3906 if (name == *reserved) {
3907 if (!route_by_name (*reserved)) {
3908 /* first instance of a reserved name is allowed */
3911 /* all other instances of a reserved name are not allowed */
3916 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3917 if ((*i)->name() == name) {
3921 if ((*i)->has_io_processor_named (name)) {
3930 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3933 vector<string> connections;
3935 /* if we are passed only a single route and we're not told to turn
3936 * others off, then just do the simple thing.
3939 if (flip_others == false && rl->size() == 1) {
3940 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3942 mt->set_input_active (onoff);
3947 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3949 PortSet& ps ((*rt)->input()->ports());
3951 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3952 p->get_connections (connections);
3955 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3956 routes_using_input_from (*s, rl2);
3959 /* scan all relevant routes to see if others are on or off */
3961 bool others_are_already_on = false;
3963 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3965 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3971 if ((*r) != (*rt)) {
3972 if (mt->input_active()) {
3973 others_are_already_on = true;
3976 /* this one needs changing */
3977 mt->set_input_active (onoff);
3983 /* globally reverse other routes */
3985 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3986 if ((*r) != (*rt)) {
3987 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3989 mt->set_input_active (!others_are_already_on);
3998 Session::routes_using_input_from (const string& str, RouteList& rl)
4000 boost::shared_ptr<RouteList> r = routes.reader();
4002 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4003 if ((*i)->input()->connected_to (str)) {
4009 boost::shared_ptr<Route>
4010 Session::route_by_name (string name)
4012 boost::shared_ptr<RouteList> r = routes.reader ();
4014 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4015 if ((*i)->name() == name) {
4020 return boost::shared_ptr<Route> ((Route*) 0);
4023 boost::shared_ptr<Route>
4024 Session::route_by_id (PBD::ID id)
4026 boost::shared_ptr<RouteList> r = routes.reader ();
4028 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4029 if ((*i)->id() == id) {
4034 return boost::shared_ptr<Route> ((Route*) 0);
4037 boost::shared_ptr<Processor>
4038 Session::processor_by_id (PBD::ID id) const
4040 boost::shared_ptr<RouteList> r = routes.reader ();
4042 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4043 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4049 return boost::shared_ptr<Processor> ();
4052 boost::shared_ptr<Track>
4053 Session::track_by_diskstream_id (PBD::ID id)
4055 boost::shared_ptr<RouteList> r = routes.reader ();
4057 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4058 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4059 if (t && t->using_diskstream_id (id)) {
4064 return boost::shared_ptr<Track> ();
4067 boost::shared_ptr<Route>
4068 Session::route_by_remote_id (uint32_t id)
4070 boost::shared_ptr<RouteList> r = routes.reader ();
4072 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4073 if ((*i)->remote_control_id() == id) {
4078 return boost::shared_ptr<Route> ((Route*) 0);
4082 boost::shared_ptr<Route>
4083 Session::route_by_selected_count (uint32_t id)
4085 boost::shared_ptr<RouteList> r = routes.reader ();
4087 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4088 /* NOT IMPLEMENTED */
4091 return boost::shared_ptr<Route> ((Route*) 0);
4096 Session::reassign_track_numbers ()
4100 RouteList r (*(routes.reader ()));
4101 SignalOrderRouteSorter sorter;
4104 StateProtector sp (this);
4106 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4107 if (boost::dynamic_pointer_cast<Track> (*i)) {
4108 (*i)->set_track_number(++tn);
4110 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4111 (*i)->set_track_number(--bn);
4114 const uint32_t decimals = ceilf (log10f (tn + 1));
4115 const bool decimals_changed = _track_number_decimals != decimals;
4116 _track_number_decimals = decimals;
4118 if (decimals_changed && config.get_track_name_number ()) {
4119 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4120 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4122 t->resync_track_name();
4125 // trigger GUI re-layout
4126 config.ParameterChanged("track-name-number");
4131 Session::playlist_region_added (boost::weak_ptr<Region> w)
4133 boost::shared_ptr<Region> r = w.lock ();
4138 /* These are the operations that are currently in progress... */
4139 list<GQuark> curr = _current_trans_quarks;
4142 /* ...and these are the operations during which we want to update
4143 the session range location markers.
4146 ops.push_back (Operations::capture);
4147 ops.push_back (Operations::paste);
4148 ops.push_back (Operations::duplicate_region);
4149 ops.push_back (Operations::insert_file);
4150 ops.push_back (Operations::insert_region);
4151 ops.push_back (Operations::drag_region_brush);
4152 ops.push_back (Operations::region_drag);
4153 ops.push_back (Operations::selection_grab);
4154 ops.push_back (Operations::region_fill);
4155 ops.push_back (Operations::fill_selection);
4156 ops.push_back (Operations::create_region);
4157 ops.push_back (Operations::region_copy);
4158 ops.push_back (Operations::fixed_time_region_copy);
4161 /* See if any of the current operations match the ones that we want */
4163 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4165 /* If so, update the session range markers */
4167 maybe_update_session_range (r->position (), r->last_frame ());
4171 /** Update the session range markers if a is before the current start or
4172 * b is after the current end.
4175 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4177 if (_state_of_the_state & Loading) {
4181 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4183 if (_session_range_location == 0) {
4185 set_session_range_location (a, b + session_end_marker_shift_samples);
4189 if (a < _session_range_location->start()) {
4190 _session_range_location->set_start (a);
4193 if (b > _session_range_location->end()) {
4194 _session_range_location->set_end (b);
4200 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4202 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4203 maybe_update_session_range (i->to, i->to + i->length);
4208 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4210 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4211 maybe_update_session_range (i->from, i->to);
4215 /* Region management */
4217 boost::shared_ptr<Region>
4218 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4220 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4221 RegionFactory::RegionMap::const_iterator i;
4222 boost::shared_ptr<Region> region;
4224 Glib::Threads::Mutex::Lock lm (region_lock);
4226 for (i = regions.begin(); i != regions.end(); ++i) {
4230 if (region->whole_file()) {
4232 if (child->source_equivalent (region)) {
4238 return boost::shared_ptr<Region> ();
4242 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4244 set<boost::shared_ptr<Region> > relevant_regions;
4246 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4247 RegionFactory::get_regions_using_source (*s, relevant_regions);
4250 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4251 set<boost::shared_ptr<Region> >::iterator tmp;
4256 playlists->destroy_region (*r);
4257 RegionFactory::map_remove (*r);
4259 (*r)->drop_sources ();
4260 (*r)->drop_references ();
4262 relevant_regions.erase (r);
4267 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4270 Glib::Threads::Mutex::Lock ls (source_lock);
4271 /* remove from the main source list */
4272 sources.erase ((*s)->id());
4275 (*s)->mark_for_remove ();
4276 (*s)->drop_references ();
4285 Session::remove_last_capture ()
4287 list<boost::shared_ptr<Source> > srcs;
4289 boost::shared_ptr<RouteList> rl = routes.reader ();
4290 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4291 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4296 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4299 srcs.insert (srcs.end(), l.begin(), l.end());
4304 destroy_sources (srcs);
4306 save_state (_current_snapshot_name);
4311 /* Source Management */
4314 Session::add_source (boost::shared_ptr<Source> source)
4316 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4317 pair<SourceMap::iterator,bool> result;
4319 entry.first = source->id();
4320 entry.second = source;
4323 Glib::Threads::Mutex::Lock lm (source_lock);
4324 result = sources.insert (entry);
4327 if (result.second) {
4329 /* yay, new source */
4331 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4334 if (!fs->within_session()) {
4335 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4341 boost::shared_ptr<AudioFileSource> afs;
4343 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4344 if (Config->get_auto_analyse_audio()) {
4345 Analyser::queue_source_for_analysis (source, false);
4349 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4354 Session::remove_source (boost::weak_ptr<Source> src)
4356 if (_state_of_the_state & Deletion) {
4360 SourceMap::iterator i;
4361 boost::shared_ptr<Source> source = src.lock();
4368 Glib::Threads::Mutex::Lock lm (source_lock);
4370 if ((i = sources.find (source->id())) != sources.end()) {
4375 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4377 /* save state so we don't end up with a session file
4378 referring to non-existent sources.
4381 save_state (_current_snapshot_name);
4385 boost::shared_ptr<Source>
4386 Session::source_by_id (const PBD::ID& id)
4388 Glib::Threads::Mutex::Lock lm (source_lock);
4389 SourceMap::iterator i;
4390 boost::shared_ptr<Source> source;
4392 if ((i = sources.find (id)) != sources.end()) {
4399 boost::shared_ptr<AudioFileSource>
4400 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4402 /* Restricted to audio files because only audio sources have channel
4406 Glib::Threads::Mutex::Lock lm (source_lock);
4408 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4409 boost::shared_ptr<AudioFileSource> afs
4410 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4412 if (afs && afs->path() == path && chn == afs->channel()) {
4417 return boost::shared_ptr<AudioFileSource>();
4420 boost::shared_ptr<MidiSource>
4421 Session::midi_source_by_path (const std::string& path) const
4423 /* Restricted to MIDI files because audio sources require a channel
4424 for unique identification, in addition to a path.
4427 Glib::Threads::Mutex::Lock lm (source_lock);
4429 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4430 boost::shared_ptr<MidiSource> ms
4431 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4432 boost::shared_ptr<FileSource> fs
4433 = boost::dynamic_pointer_cast<FileSource>(s->second);
4435 if (ms && fs && fs->path() == path) {
4440 return boost::shared_ptr<MidiSource>();
4444 Session::count_sources_by_origin (const string& path)
4447 Glib::Threads::Mutex::Lock lm (source_lock);
4449 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4450 boost::shared_ptr<FileSource> fs
4451 = boost::dynamic_pointer_cast<FileSource>(i->second);
4453 if (fs && fs->origin() == path) {
4462 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4464 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4465 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4467 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4472 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4474 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4476 if (Glib::path_is_absolute (filepath)) {
4478 /* rip the session dir from the audiofile source */
4480 string session_path;
4481 bool in_another_session = true;
4483 if (filepath.find (interchange_dir_string) != string::npos) {
4485 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4486 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4487 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4488 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4490 /* see if it is within our session */
4492 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4493 if (i->path == session_path) {
4494 in_another_session = false;
4499 in_another_session = false;
4503 if (in_another_session) {
4504 SessionDirectory sd (session_path);
4505 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4509 /* 1) if file belongs to this session
4510 * it may be a relative path (interchange/...)
4511 * or just basename (session_state, remove source)
4512 * -> just use the basename
4514 std::string filename = Glib::path_get_basename (filepath);
4517 /* 2) if the file is outside our session dir:
4518 * (imported but not copied) add the path for check-summming */
4520 path = Glib::path_get_dirname (filepath);
4523 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4527 Session::new_audio_source_path_for_embedded (const std::string& path)
4531 * we know that the filename is already unique because it exists
4532 * out in the filesystem.
4534 * However, when we bring it into the session, we could get a
4537 * Eg. two embedded files:
4542 * When merged into session, these collide.
4544 * There will not be a conflict with in-memory sources
4545 * because when the source was created we already picked
4546 * a unique name for it.
4548 * This collision is not likely to be common, but we have to guard
4549 * against it. So, if there is a collision, take the md5 hash of the
4550 * the path, and use that as the filename instead.
4553 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4554 string base = Glib::path_get_basename (path);
4555 string newpath = Glib::build_filename (sdir.sound_path(), base);
4557 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4561 md5.digestString (path.c_str());
4562 md5.writeToString ();
4563 base = md5.digestChars;
4565 string ext = get_suffix (path);
4572 newpath = Glib::build_filename (sdir.sound_path(), base);
4574 /* if this collides, we're screwed */
4576 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4577 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4586 /** Return true if there are no audio file sources that use @param name as
4587 * the filename component of their path.
4589 * Return false otherwise.
4591 * This method MUST ONLY be used to check in-session, mono files since it
4592 * hard-codes the channel of the audio file source we are looking for as zero.
4594 * If/when Ardour supports native files in non-mono formats, the logic here
4595 * will need to be revisited.
4598 Session::audio_source_name_is_unique (const string& name)
4600 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4601 vector<space_and_path>::iterator i;
4602 uint32_t existing = 0;
4604 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4606 /* note that we search *without* the extension so that
4607 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4608 in the event that this new name is required for
4609 a file format change.
4612 const string spath = *i;
4614 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4619 /* it is possible that we have the path already
4620 * assigned to a source that has not yet been written
4621 * (ie. the write source for a diskstream). we have to
4622 * check this in order to make sure that our candidate
4623 * path isn't used again, because that can lead to
4624 * two Sources point to the same file with different
4625 * notions of their removability.
4629 string possible_path = Glib::build_filename (spath, name);
4631 if (audio_source_by_path_and_channel (possible_path, 0)) {
4637 return (existing == 0);
4641 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)
4644 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4646 if (Profile->get_trx() && destructive) {
4648 sstr << setfill ('0') << setw (4) << cnt;
4649 sstr << legalized_base;
4651 sstr << legalized_base;
4653 if (take_required || related_exists) {
4665 } else if (nchan > 2) {
4670 /* XXX what? more than 26 channels! */
4681 /** Return a unique name based on \a base for a new internal audio source */
4683 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4686 string possible_name;
4687 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4689 bool some_related_source_name_exists = false;
4691 legalized = legalize_for_path (base);
4693 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4695 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4697 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4699 if (audio_source_name_is_unique (possible_name)) {
4703 some_related_source_name_exists = true;
4706 error << string_compose(
4707 _("There are already %1 recordings for %2, which I consider too many."),
4708 limit, base) << endmsg;
4710 throw failed_constructor();
4714 /* We've established that the new name does not exist in any session
4715 * directory, so now find out which one we should use for this new
4719 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4721 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4726 /** Return a unique name based on `base` for a new internal MIDI source */
4728 Session::new_midi_source_path (const string& base)
4731 char buf[PATH_MAX+1];
4732 const uint32_t limit = 10000;
4734 string possible_path;
4735 string possible_name;
4738 legalized = legalize_for_path (base);
4740 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4741 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4743 /* - the main session folder is the first in the vector.
4744 * - after checking all locations for file-name uniqueness,
4745 * we keep the one from the last iteration as new file name
4746 * - midi files are small and should just be kept in the main session-folder
4748 * -> reverse the array, check main session folder last and use that as location
4751 std::reverse(sdirs.begin(), sdirs.end());
4753 for (cnt = 1; cnt <= limit; ++cnt) {
4755 vector<space_and_path>::iterator i;
4756 uint32_t existing = 0;
4758 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4760 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4761 possible_name = buf;
4763 possible_path = Glib::build_filename (*i, possible_name);
4765 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4769 if (midi_source_by_path (possible_path)) {
4774 if (existing == 0) {
4779 error << string_compose(
4780 _("There are already %1 recordings for %2, which I consider too many."),
4781 limit, base) << endmsg;
4787 /* No need to "find best location" for software/app-based RAID, because
4788 MIDI is so small that we always put it in the same place.
4791 return possible_path;
4795 /** Create a new within-session audio source */
4796 boost::shared_ptr<AudioFileSource>
4797 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4799 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4801 if (!path.empty()) {
4802 return boost::dynamic_pointer_cast<AudioFileSource> (
4803 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4805 throw failed_constructor ();
4809 /** Create a new within-session MIDI source */
4810 boost::shared_ptr<MidiSource>
4811 Session::create_midi_source_for_session (string const & basic_name)
4813 const string path = new_midi_source_path (basic_name);
4815 if (!path.empty()) {
4816 return boost::dynamic_pointer_cast<SMFSource> (
4817 SourceFactory::createWritable (
4818 DataType::MIDI, *this, path, false, frame_rate()));
4820 throw failed_constructor ();
4824 /** Create a new within-session MIDI source */
4825 boost::shared_ptr<MidiSource>
4826 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4828 /* the caller passes in the track the source will be used in,
4829 so that we can keep the numbering sane.
4831 Rationale: a track with the name "Foo" that has had N
4832 captures carried out so far will ALREADY have a write source
4833 named "Foo-N+1.mid" waiting to be used for the next capture.
4835 If we call new_midi_source_name() we will get "Foo-N+2". But
4836 there is no region corresponding to "Foo-N+1", so when
4837 "Foo-N+2" appears in the track, the gap presents the user
4838 with odd behaviour - why did it skip past Foo-N+1?
4840 We could explain this to the user in some odd way, but
4841 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4844 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4847 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4849 std::string name = track->steal_write_source_name ();
4852 return boost::shared_ptr<MidiSource>();
4855 /* MIDI files are small, just put them in the first location of the
4856 session source search path.
4859 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4861 return boost::dynamic_pointer_cast<SMFSource> (
4862 SourceFactory::createWritable (
4863 DataType::MIDI, *this, path, false, frame_rate()));
4868 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4870 if (playlist->hidden()) {
4874 playlists->add (playlist);
4877 playlist->release();
4884 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4886 if (_state_of_the_state & Deletion) {
4890 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4896 playlists->remove (playlist);
4902 Session::set_audition (boost::shared_ptr<Region> r)
4904 pending_audition_region = r;
4905 add_post_transport_work (PostTransportAudition);
4906 _butler->schedule_transport_work ();
4910 Session::audition_playlist ()
4912 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4913 ev->region.reset ();
4919 Session::register_lua_function (
4920 const std::string& name,
4921 const std::string& script,
4922 const LuaScriptParamList& args
4925 Glib::Threads::Mutex::Lock lm (lua_lock);
4927 lua_State* L = lua.getState();
4929 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
4930 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
4931 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
4932 if ((*i)->optional && !(*i)->is_set) { continue; }
4933 tbl_arg[(*i)->name] = (*i)->value;
4935 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
4940 Session::unregister_lua_function (const std::string& name)
4942 Glib::Threads::Mutex::Lock lm (lua_lock);
4943 (*_lua_del)(name); // throws luabridge::LuaException
4944 lua.collect_garbage ();
4948 std::vector<std::string>
4949 Session::registered_lua_functions ()
4951 Glib::Threads::Mutex::Lock lm (lua_lock);
4952 std::vector<std::string> rv;
4955 luabridge::LuaRef list ((*_lua_list)());
4956 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
4957 if (!i.key ().isString ()) { assert(0); continue; }
4958 rv.push_back (i.key ().cast<std::string> ());
4960 } catch (luabridge::LuaException const& e) { }
4965 static void _lua_print (std::string s) {
4966 std::cout << "SessionLua: " << s << "\n";
4971 Session::try_run_lua (pframes_t nframes)
4973 if (_n_lua_scripts == 0) return;
4974 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
4976 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
4981 Session::setup_lua ()
4984 lua.Print.connect (&_lua_print);
4987 "function ArdourSession ()"
4988 " local self = { scripts = {}, instances = {} }"
4990 " local remove = function (n)"
4991 " self.scripts[n] = nil"
4992 " self.instances[n] = nil"
4993 " Session:scripts_changed()" // call back
4996 " local addinternal = function (n, f, a)"
4997 " assert(type(n) == 'string', 'function-name must be string')"
4998 " assert(type(f) == 'function', 'Given script is a not a function')"
4999 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5000 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5001 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5002 " 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"
5003 " 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 }"
5004 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5005 " Session:scripts_changed()" // call back
5008 " local add = function (n, b, a)"
5009 " assert(type(b) == 'string', 'ByteCode must be string')"
5010 " load (b)()" // assigns f
5011 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5012 " addinternal (n, load(f), a)"
5015 " local run = function (...)"
5016 " for n, s in pairs (self.instances) do"
5017 " local status, err = pcall (s, ...)"
5018 " if not status then"
5019 " print ('fn \"'.. n .. '\": ', err)"
5026 " local cleanup = function ()"
5027 " self.scripts = nil"
5028 " self.instances = nil"
5031 " local list = function ()"
5033 " for n, _ in pairs (self.scripts) do"
5039 " local function basic_serialize (o)"
5040 " if type(o) == \"number\" then"
5041 " return tostring(o)"
5043 " return string.format(\"%q\", o)"
5047 " local function serialize (name, value)"
5048 " local rv = name .. ' = '"
5050 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5051 " return rv .. basic_serialize(value) .. ' '"
5052 " elseif type(value) == \"table\" then"
5054 " for k,v in pairs(value) do"
5055 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5056 " rv = rv .. serialize(fieldname, v) .. ' '"
5057 " collectgarbage()" // string concatenation allocates a new string :(
5060 " elseif type(value) == \"function\" then"
5061 " return rv .. string.format(\"%q\", string.dump(value, true))"
5063 " error('cannot save a ' .. type(value))"
5068 " local save = function ()"
5069 " return (serialize('scripts', self.scripts))"
5072 " local restore = function (state)"
5073 " self.scripts = {}"
5075 " for n, s in pairs (scripts) do"
5076 " addinternal (n, load(s['f']), s['a'])"
5080 " return { run = run, add = add, remove = remove,"
5081 " list = list, restore = restore, save = save, cleanup = cleanup}"
5084 " sess = ArdourSession ()"
5085 " ArdourSession = nil"
5087 "function ardour () end"
5090 lua_State* L = lua.getState();
5093 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5094 lua.do_command ("sess = nil"); // hide it.
5095 lua.do_command ("collectgarbage()");
5097 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5098 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5099 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5100 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5101 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5102 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5103 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5104 } catch (luabridge::LuaException const& e) {
5105 fatal << string_compose (_("programming error: %1"),
5106 X_("Failed to setup Lua interpreter"))
5108 abort(); /*NOTREACHED*/
5111 LuaBindings::stddef (L);
5112 LuaBindings::common (L);
5113 LuaBindings::dsp (L);
5114 luabridge::push <Session *> (L, this);
5115 lua_setglobal (L, "Session");
5119 Session::scripts_changed ()
5121 assert (!lua_lock.trylock()); // must hold lua_lock
5124 luabridge::LuaRef list ((*_lua_list)());
5126 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5127 if (!i.key ().isString ()) { assert(0); continue; }
5130 _n_lua_scripts = cnt;
5131 } catch (luabridge::LuaException const& e) {
5132 fatal << string_compose (_("programming error: %1"),
5133 X_("Indexing Lua Session Scripts failed."))
5135 abort(); /*NOTREACHED*/
5140 Session::non_realtime_set_audition ()
5142 assert (pending_audition_region);
5143 auditioner->audition_region (pending_audition_region);
5144 pending_audition_region.reset ();
5145 AuditionActive (true); /* EMIT SIGNAL */
5149 Session::audition_region (boost::shared_ptr<Region> r)
5151 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5157 Session::cancel_audition ()
5162 if (auditioner->auditioning()) {
5163 auditioner->cancel_audition ();
5164 AuditionActive (false); /* EMIT SIGNAL */
5169 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5171 if (a->is_monitor()) {
5174 if (b->is_monitor()) {
5177 return a->order_key () < b->order_key ();
5181 Session::is_auditioning () const
5183 /* can be called before we have an auditioner object */
5185 return auditioner->auditioning();
5192 Session::graph_reordered ()
5194 /* don't do this stuff if we are setting up connections
5195 from a set_state() call or creating new tracks. Ditto for deletion.
5198 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5202 /* every track/bus asked for this to be handled but it was deferred because
5203 we were connecting. do it now.
5206 request_input_change_handling ();
5210 /* force all diskstreams to update their capture offset values to
5211 reflect any changes in latencies within the graph.
5214 boost::shared_ptr<RouteList> rl = routes.reader ();
5215 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5216 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5218 tr->set_capture_offset ();
5223 /** @return Number of frames that there is disk space available to write,
5226 boost::optional<framecnt_t>
5227 Session::available_capture_duration ()
5229 Glib::Threads::Mutex::Lock lm (space_lock);
5231 if (_total_free_4k_blocks_uncertain) {
5232 return boost::optional<framecnt_t> ();
5235 float sample_bytes_on_disk = 4.0; // keep gcc happy
5237 switch (config.get_native_file_data_format()) {
5239 sample_bytes_on_disk = 4.0;
5243 sample_bytes_on_disk = 3.0;
5247 sample_bytes_on_disk = 2.0;
5251 /* impossible, but keep some gcc versions happy */
5252 fatal << string_compose (_("programming error: %1"),
5253 X_("illegal native file data format"))
5255 abort(); /*NOTREACHED*/
5258 double scale = 4096.0 / sample_bytes_on_disk;
5260 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5261 return max_framecnt;
5264 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5268 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5271 RCUWriter<BundleList> writer (_bundles);
5272 boost::shared_ptr<BundleList> b = writer.get_copy ();
5273 b->push_back (bundle);
5277 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5284 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5286 bool removed = false;
5289 RCUWriter<BundleList> writer (_bundles);
5290 boost::shared_ptr<BundleList> b = writer.get_copy ();
5291 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5293 if (i != b->end()) {
5300 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5306 boost::shared_ptr<Bundle>
5307 Session::bundle_by_name (string name) const
5309 boost::shared_ptr<BundleList> b = _bundles.reader ();
5311 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5312 if ((*i)->name() == name) {
5317 return boost::shared_ptr<Bundle> ();
5321 Session::tempo_map_changed (const PropertyChange&)
5325 playlists->update_after_tempo_map_change ();
5327 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5333 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5335 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5336 (*i)->recompute_frames_from_bbt ();
5340 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5341 * the given count with the current block size.
5344 Session::ensure_buffers (ChanCount howmany)
5346 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5350 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5352 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5353 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5358 Session::next_insert_id ()
5360 /* this doesn't really loop forever. just think about it */
5363 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
5364 if (!insert_bitset[n]) {
5365 insert_bitset[n] = true;
5371 /* none available, so resize and try again */
5373 insert_bitset.resize (insert_bitset.size() + 16, false);
5378 Session::next_send_id ()
5380 /* this doesn't really loop forever. just think about it */
5383 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
5384 if (!send_bitset[n]) {
5385 send_bitset[n] = true;
5391 /* none available, so resize and try again */
5393 send_bitset.resize (send_bitset.size() + 16, false);
5398 Session::next_aux_send_id ()
5400 /* this doesn't really loop forever. just think about it */
5403 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
5404 if (!aux_send_bitset[n]) {
5405 aux_send_bitset[n] = true;
5411 /* none available, so resize and try again */
5413 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5418 Session::next_return_id ()
5420 /* this doesn't really loop forever. just think about it */
5423 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
5424 if (!return_bitset[n]) {
5425 return_bitset[n] = true;
5431 /* none available, so resize and try again */
5433 return_bitset.resize (return_bitset.size() + 16, false);
5438 Session::mark_send_id (uint32_t id)
5440 if (id >= send_bitset.size()) {
5441 send_bitset.resize (id+16, false);
5443 if (send_bitset[id]) {
5444 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5446 send_bitset[id] = true;
5450 Session::mark_aux_send_id (uint32_t id)
5452 if (id >= aux_send_bitset.size()) {
5453 aux_send_bitset.resize (id+16, false);
5455 if (aux_send_bitset[id]) {
5456 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5458 aux_send_bitset[id] = true;
5462 Session::mark_return_id (uint32_t id)
5464 if (id >= return_bitset.size()) {
5465 return_bitset.resize (id+16, false);
5467 if (return_bitset[id]) {
5468 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5470 return_bitset[id] = true;
5474 Session::mark_insert_id (uint32_t id)
5476 if (id >= insert_bitset.size()) {
5477 insert_bitset.resize (id+16, false);
5479 if (insert_bitset[id]) {
5480 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5482 insert_bitset[id] = true;
5486 Session::unmark_send_id (uint32_t id)
5488 if (id < send_bitset.size()) {
5489 send_bitset[id] = false;
5494 Session::unmark_aux_send_id (uint32_t id)
5496 if (id < aux_send_bitset.size()) {
5497 aux_send_bitset[id] = false;
5502 Session::unmark_return_id (uint32_t id)
5504 if (_state_of_the_state & Deletion) { return; }
5505 if (id < return_bitset.size()) {
5506 return_bitset[id] = false;
5511 Session::unmark_insert_id (uint32_t id)
5513 if (id < insert_bitset.size()) {
5514 insert_bitset[id] = false;
5519 Session::reset_native_file_format ()
5521 boost::shared_ptr<RouteList> rl = routes.reader ();
5523 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5524 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5526 /* don't save state as we do this, there's no point
5528 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5529 tr->reset_write_sources (false);
5530 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5536 Session::route_name_unique (string n) const
5538 boost::shared_ptr<RouteList> r = routes.reader ();
5540 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5541 if ((*i)->name() == n) {
5550 Session::route_name_internal (string n) const
5552 if (auditioner && auditioner->name() == n) {
5556 if (_click_io && _click_io->name() == n) {
5564 Session::freeze_all (InterThreadInfo& itt)
5566 boost::shared_ptr<RouteList> r = routes.reader ();
5568 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5570 boost::shared_ptr<Track> t;
5572 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5573 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5583 boost::shared_ptr<Region>
5584 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5585 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5586 InterThreadInfo& itt,
5587 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5588 bool for_export, bool for_freeze)
5590 boost::shared_ptr<Region> result;
5591 boost::shared_ptr<Playlist> playlist;
5592 boost::shared_ptr<Source> source;
5593 ChanCount diskstream_channels (track.n_channels());
5594 framepos_t position;
5595 framecnt_t this_chunk;
5597 framepos_t latency_skip;
5599 framepos_t len = end - start;
5600 bool need_block_size_reset = false;
5601 ChanCount const max_proc = track.max_processor_streams ();
5602 string legal_playlist_name;
5603 string possible_path;
5606 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5607 end, start) << endmsg;
5611 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5612 include_endpoint, for_export, for_freeze);
5614 if (diskstream_channels.n(track.data_type()) < 1) {
5615 error << _("Cannot write a range with no data.") << endmsg;
5619 // block all process callback handling
5621 block_processing ();
5624 // synchronize with AudioEngine::process_callback()
5625 // make sure processing is not currently running
5626 // and processing_blocked() is honored before
5627 // acquiring thread buffers
5628 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5631 _bounce_processing_active = true;
5633 /* call tree *MUST* hold route_lock */
5635 if ((playlist = track.playlist()) == 0) {
5639 legal_playlist_name = legalize_for_path (playlist->name());
5641 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5643 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5644 string path = ((track.data_type() == DataType::AUDIO)
5645 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5646 : new_midi_source_path (legal_playlist_name));
5653 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5656 catch (failed_constructor& err) {
5657 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5661 srcs.push_back (source);
5664 /* tell redirects that care that we are about to use a much larger
5665 * blocksize. this will flush all plugins too, so that they are ready
5666 * to be used for this process.
5669 need_block_size_reset = true;
5670 track.set_block_size (bounce_chunk_size);
5671 _engine.main_thread()->get_buffers ();
5675 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5677 /* create a set of reasonably-sized buffers */
5678 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5679 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5681 buffers.set_count (max_proc);
5683 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5684 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5685 boost::shared_ptr<MidiSource> ms;
5687 afs->prepare_for_peakfile_writes ();
5688 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5689 Source::Lock lock(ms->mutex());
5690 ms->mark_streaming_write_started(lock);
5694 while (to_do && !itt.cancel) {
5696 this_chunk = min (to_do, bounce_chunk_size);
5698 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5702 start += this_chunk;
5703 to_do -= this_chunk;
5704 itt.progress = (float) (1.0 - ((double) to_do / len));
5706 if (latency_skip >= bounce_chunk_size) {
5707 latency_skip -= bounce_chunk_size;
5711 const framecnt_t current_chunk = this_chunk - latency_skip;
5714 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5715 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5716 boost::shared_ptr<MidiSource> ms;
5719 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5722 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5723 Source::Lock lock(ms->mutex());
5725 const MidiBuffer& buf = buffers.get_midi(0);
5726 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5727 Evoral::Event<framepos_t> ev = *i;
5728 ev.set_time(ev.time() - position);
5729 ms->append_event_frames(lock, ev, ms->timeline_position());
5736 /* post-roll, pick up delayed processor output */
5737 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5739 while (latency_skip && !itt.cancel) {
5740 this_chunk = min (latency_skip, bounce_chunk_size);
5741 latency_skip -= this_chunk;
5743 buffers.silence (this_chunk, 0);
5744 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5747 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5748 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5751 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5763 xnow = localtime (&now);
5765 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5766 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5767 boost::shared_ptr<MidiSource> ms;
5770 afs->update_header (position, *xnow, now);
5771 afs->flush_header ();
5772 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5773 Source::Lock lock(ms->mutex());
5774 ms->mark_streaming_write_completed(lock);
5778 /* construct a region to represent the bounced material */
5782 plist.add (Properties::start, 0);
5783 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5784 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5786 result = RegionFactory::create (srcs, plist);
5792 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5793 (*src)->mark_for_remove ();
5794 (*src)->drop_references ();
5798 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5799 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5802 afs->done_with_peakfile_writes ();
5806 _bounce_processing_active = false;
5808 if (need_block_size_reset) {
5809 _engine.main_thread()->drop_buffers ();
5810 track.set_block_size (get_block_size());
5813 unblock_processing ();
5819 Session::gain_automation_buffer() const
5821 return ProcessThread::gain_automation_buffer ();
5825 Session::trim_automation_buffer() const
5827 return ProcessThread::trim_automation_buffer ();
5831 Session::send_gain_automation_buffer() const
5833 return ProcessThread::send_gain_automation_buffer ();
5837 Session::pan_automation_buffer() const
5839 return ProcessThread::pan_automation_buffer ();
5843 Session::get_silent_buffers (ChanCount count)
5845 return ProcessThread::get_silent_buffers (count);
5849 Session::get_scratch_buffers (ChanCount count, bool silence)
5851 return ProcessThread::get_scratch_buffers (count, silence);
5855 Session::get_route_buffers (ChanCount count, bool silence)
5857 return ProcessThread::get_route_buffers (count, silence);
5862 Session::get_mix_buffers (ChanCount count)
5864 return ProcessThread::get_mix_buffers (count);
5868 Session::ntracks () const
5871 boost::shared_ptr<RouteList> r = routes.reader ();
5873 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5874 if (boost::dynamic_pointer_cast<Track> (*i)) {
5883 Session::nbusses () const
5886 boost::shared_ptr<RouteList> r = routes.reader ();
5888 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5889 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5898 Session::add_automation_list(AutomationList *al)
5900 automation_lists[al->id()] = al;
5903 /** @return true if there is at least one record-enabled track, otherwise false */
5905 Session::have_rec_enabled_track () const
5907 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
5911 Session::have_rec_disabled_track () const
5913 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
5916 /** Update the state of our rec-enabled tracks flag */
5918 Session::update_route_record_state ()
5920 boost::shared_ptr<RouteList> rl = routes.reader ();
5921 RouteList::iterator i = rl->begin();
5922 while (i != rl->end ()) {
5924 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5925 if (tr && tr->record_enabled ()) {
5932 int const old = g_atomic_int_get (&_have_rec_enabled_track);
5934 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5936 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5937 RecordStateChanged (); /* EMIT SIGNAL */
5940 for (i = rl->begin(); i != rl->end (); ++i) {
5941 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5942 if (tr && !tr->record_enabled ()) {
5947 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
5949 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
5951 if (record_status() == Recording && record_arm_state_changed ) {
5952 RecordArmStateChanged ();
5958 Session::listen_position_changed ()
5960 boost::shared_ptr<RouteList> r = routes.reader ();
5962 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5963 (*i)->listen_position_changed ();
5968 Session::solo_control_mode_changed ()
5970 /* cancel all solo or all listen when solo control mode changes */
5973 set_solo (get_routes(), false);
5974 } else if (listening()) {
5975 set_listen (get_routes(), false);
5979 /** Called when a property of one of our route groups changes */
5981 Session::route_group_property_changed (RouteGroup* rg)
5983 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
5986 /** Called when a route is added to one of our route groups */
5988 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5990 RouteAddedToRouteGroup (rg, r);
5993 /** Called when a route is removed from one of our route groups */
5995 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5997 update_route_record_state ();
5998 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6001 boost::shared_ptr<RouteList>
6002 Session::get_tracks () const
6004 boost::shared_ptr<RouteList> rl = routes.reader ();
6005 boost::shared_ptr<RouteList> tl (new RouteList);
6007 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6008 if (boost::dynamic_pointer_cast<Track> (*r)) {
6009 if (!(*r)->is_auditioner()) {
6017 boost::shared_ptr<RouteList>
6018 Session::get_routes_with_regions_at (framepos_t const p) const
6020 boost::shared_ptr<RouteList> r = routes.reader ();
6021 boost::shared_ptr<RouteList> rl (new RouteList);
6023 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6024 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6029 boost::shared_ptr<Playlist> pl = tr->playlist ();
6034 if (pl->has_region_at (p)) {
6043 Session::goto_end ()
6045 if (_session_range_location) {
6046 request_locate (_session_range_location->end(), false);
6048 request_locate (0, false);
6053 Session::goto_start ()
6055 if (_session_range_location) {
6056 request_locate (_session_range_location->start(), false);
6058 request_locate (0, false);
6063 Session::current_start_frame () const
6065 return _session_range_location ? _session_range_location->start() : 0;
6069 Session::current_end_frame () const
6071 return _session_range_location ? _session_range_location->end() : 0;
6075 Session::set_session_range_location (framepos_t start, framepos_t end)
6077 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6078 _locations->add (_session_range_location);
6082 Session::step_edit_status_change (bool yn)
6088 send = (_step_editors == 0);
6093 send = (_step_editors == 1);
6096 if (_step_editors > 0) {
6102 StepEditStatusChange (val);
6108 Session::start_time_changed (framepos_t old)
6110 /* Update the auto loop range to match the session range
6111 (unless the auto loop range has been changed by the user)
6114 Location* s = _locations->session_range_location ();
6119 Location* l = _locations->auto_loop_location ();
6121 if (l && l->start() == old) {
6122 l->set_start (s->start(), true);
6127 Session::end_time_changed (framepos_t old)
6129 /* Update the auto loop range to match the session range
6130 (unless the auto loop range has been changed by the user)
6133 Location* s = _locations->session_range_location ();
6138 Location* l = _locations->auto_loop_location ();
6140 if (l && l->end() == old) {
6141 l->set_end (s->end(), true);
6145 std::vector<std::string>
6146 Session::source_search_path (DataType type) const
6150 if (session_dirs.size() == 1) {
6152 case DataType::AUDIO:
6153 sp.push_back (_session_dir->sound_path());
6155 case DataType::MIDI:
6156 sp.push_back (_session_dir->midi_path());
6160 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6161 SessionDirectory sdir (i->path);
6163 case DataType::AUDIO:
6164 sp.push_back (sdir.sound_path());
6166 case DataType::MIDI:
6167 sp.push_back (sdir.midi_path());
6173 if (type == DataType::AUDIO) {
6174 const string sound_path_2X = _session_dir->sound_path_2X();
6175 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6176 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6177 sp.push_back (sound_path_2X);
6182 // now check the explicit (possibly user-specified) search path
6185 case DataType::AUDIO:
6186 sp += Searchpath(config.get_audio_search_path ());
6188 case DataType::MIDI:
6189 sp += Searchpath(config.get_midi_search_path ());
6197 Session::ensure_search_path_includes (const string& path, DataType type)
6206 case DataType::AUDIO:
6207 sp += Searchpath(config.get_audio_search_path ());
6209 case DataType::MIDI:
6210 sp += Searchpath (config.get_midi_search_path ());
6214 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6215 /* No need to add this new directory if it has the same inode as
6216 an existing one; checking inode rather than name prevents duplicated
6217 directories when we are using symlinks.
6219 On Windows, I think we could just do if (*i == path) here.
6221 if (PBD::equivalent_paths (*i, path)) {
6229 case DataType::AUDIO:
6230 config.set_audio_search_path (sp.to_string());
6232 case DataType::MIDI:
6233 config.set_midi_search_path (sp.to_string());
6239 Session::remove_dir_from_search_path (const string& dir, DataType type)
6244 case DataType::AUDIO:
6245 sp = Searchpath(config.get_audio_search_path ());
6247 case DataType::MIDI:
6248 sp = Searchpath (config.get_midi_search_path ());
6255 case DataType::AUDIO:
6256 config.set_audio_search_path (sp.to_string());
6258 case DataType::MIDI:
6259 config.set_midi_search_path (sp.to_string());
6265 boost::shared_ptr<Speakers>
6266 Session::get_speakers()
6272 Session::unknown_processors () const
6276 boost::shared_ptr<RouteList> r = routes.reader ();
6277 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6278 list<string> t = (*i)->unknown_processors ();
6279 copy (t.begin(), t.end(), back_inserter (p));
6289 Session::update_latency (bool playback)
6291 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6293 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
6297 boost::shared_ptr<RouteList> r = routes.reader ();
6298 framecnt_t max_latency = 0;
6301 /* reverse the list so that we work backwards from the last route to run to the first */
6302 RouteList* rl = routes.reader().get();
6303 r.reset (new RouteList (*rl));
6304 reverse (r->begin(), r->end());
6307 /* compute actual latency values for the given direction and store them all in per-port
6308 structures. this will also publish the same values (to JACK) so that computation of latency
6309 for routes can consistently use public latency values.
6312 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6313 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6316 /* because we latency compensate playback, our published playback latencies should
6317 be the same for all output ports - all material played back by ardour has
6318 the same latency, whether its caused by plugins or by latency compensation. since
6319 these may differ from the values computed above, reset all playback port latencies
6323 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6325 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6326 (*i)->set_public_port_latencies (max_latency, playback);
6331 post_playback_latency ();
6335 post_capture_latency ();
6338 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6342 Session::post_playback_latency ()
6344 set_worst_playback_latency ();
6346 boost::shared_ptr<RouteList> r = routes.reader ();
6348 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6349 if (!(*i)->is_auditioner() && ((*i)->active())) {
6350 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6354 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6355 (*i)->set_latency_compensation (_worst_track_latency);
6360 Session::post_capture_latency ()
6362 set_worst_capture_latency ();
6364 /* reflect any changes in capture latencies into capture offsets
6367 boost::shared_ptr<RouteList> rl = routes.reader();
6368 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6369 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6371 tr->set_capture_offset ();
6377 Session::initialize_latencies ()
6380 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6381 update_latency (false);
6382 update_latency (true);
6385 set_worst_io_latencies ();
6389 Session::set_worst_io_latencies ()
6391 set_worst_playback_latency ();
6392 set_worst_capture_latency ();
6396 Session::set_worst_playback_latency ()
6398 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6402 _worst_output_latency = 0;
6404 if (!_engine.connected()) {
6408 boost::shared_ptr<RouteList> r = routes.reader ();
6410 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6411 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6414 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6418 Session::set_worst_capture_latency ()
6420 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6424 _worst_input_latency = 0;
6426 if (!_engine.connected()) {
6430 boost::shared_ptr<RouteList> r = routes.reader ();
6432 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6433 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6436 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6440 Session::update_latency_compensation (bool force_whole_graph)
6442 bool some_track_latency_changed = false;
6444 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6448 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6450 _worst_track_latency = 0;
6452 boost::shared_ptr<RouteList> r = routes.reader ();
6454 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6455 if (!(*i)->is_auditioner() && ((*i)->active())) {
6457 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6458 some_track_latency_changed = true;
6460 _worst_track_latency = max (tl, _worst_track_latency);
6464 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6465 (some_track_latency_changed ? "yes" : "no")));
6467 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6469 if (some_track_latency_changed || force_whole_graph) {
6470 _engine.update_latencies ();
6474 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6475 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6479 tr->set_capture_offset ();
6484 Session::session_name_is_legal (const string& path)
6486 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6488 for (int i = 0; illegal_chars[i]; ++i) {
6489 if (path.find (illegal_chars[i]) != string::npos) {
6490 return illegal_chars[i];
6498 Session::next_control_id () const
6502 /* the monitor bus remote ID is in a different
6503 * "namespace" than regular routes. its existence doesn't
6504 * affect normal (low) numbered routes.
6511 /* the same about masterbus in Waves Tracks */
6513 if (Profile->get_trx() && _master_out) {
6517 return nroutes() - subtract;
6521 Session::notify_remote_id_change ()
6523 if (deletion_in_progress()) {
6527 switch (Config->get_remote_model()) {
6529 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6535 #ifdef USE_TRACKS_CODE_FEATURES
6536 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6537 * if track order has been changed by user
6539 reconnect_existing_routes(true, true);
6545 Session::sync_order_keys ()
6547 if (deletion_in_progress()) {
6551 /* tell everyone that something has happened to the sort keys
6552 and let them sync up with the change(s)
6553 this will give objects that manage the sort order keys the
6554 opportunity to keep them in sync if they wish to.
6557 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6559 reassign_track_numbers();
6561 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6563 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6567 Session::operation_in_progress (GQuark op) const
6569 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6572 boost::shared_ptr<Port>
6573 Session::ltc_input_port () const
6575 return _ltc_input->nth (0);
6578 boost::shared_ptr<Port>
6579 Session::ltc_output_port () const
6581 return _ltc_output->nth (0);
6585 Session::reconnect_ltc_input ()
6589 string src = Config->get_ltc_source_port();
6591 _ltc_input->disconnect (this);
6593 if (src != _("None") && !src.empty()) {
6594 _ltc_input->nth (0)->connect (src);
6597 if ( ARDOUR::Profile->get_trx () ) {
6598 // Tracks need this signal to update timecode_source_dropdown
6599 MtcOrLtcInputPortChanged (); //emit signal
6605 Session::reconnect_ltc_output ()
6609 string src = Config->get_ltc_output_port();
6611 _ltc_output->disconnect (this);
6613 if (src != _("None") && !src.empty()) {
6614 _ltc_output->nth (0)->connect (src);
6620 Session::set_range_selection (framepos_t start, framepos_t end)
6622 _range_selection = Evoral::Range<framepos_t> (start, end);
6623 #ifdef USE_TRACKS_CODE_FEATURES
6624 follow_playhead_priority ();
6629 Session::set_object_selection (framepos_t start, framepos_t end)
6631 _object_selection = Evoral::Range<framepos_t> (start, end);
6632 #ifdef USE_TRACKS_CODE_FEATURES
6633 follow_playhead_priority ();
6638 Session::clear_range_selection ()
6640 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6641 #ifdef USE_TRACKS_CODE_FEATURES
6642 follow_playhead_priority ();
6647 Session::clear_object_selection ()
6649 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6650 #ifdef USE_TRACKS_CODE_FEATURES
6651 follow_playhead_priority ();