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.
27 #include <cstdio> /* sprintf(3) ... grrr */
33 #include <glibmm/threads.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
37 #include <boost/algorithm/string/erase.hpp>
39 #include "pbd/error.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/unwind.h"
48 #include "pbd/search_path.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/midi_ui.h"
73 #include "ardour/operations.h"
74 #include "ardour/playlist.h"
75 #include "ardour/plugin.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/rc_configuration.h"
79 #include "ardour/recent_sessions.h"
80 #include "ardour/region.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/route_graph.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_playlists.h"
88 #include "ardour/smf_source.h"
89 #include "ardour/source_factory.h"
90 #include "ardour/speakers.h"
91 #include "ardour/utils.h"
93 #include "midi++/port.h"
94 #include "midi++/mmc.h"
105 using namespace ARDOUR;
108 bool Session::_disable_all_loaded_plugins = false;
110 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
111 PBD::Signal1<void,std::string> Session::Dialog;
112 PBD::Signal0<int> Session::AskAboutPendingState;
113 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
114 PBD::Signal0<void> Session::SendFeedback;
115 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
117 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
118 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
119 PBD::Signal2<void,std::string, std::string> Session::Exported;
120 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
121 PBD::Signal0<void> Session::Quit;
122 PBD::Signal0<void> Session::FeedbackDetected;
123 PBD::Signal0<void> Session::SuccessfulGraphSort;
124 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
126 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
127 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
129 /** @param snapshot_name Snapshot name, without .ardour suffix */
130 Session::Session (AudioEngine &eng,
131 const string& fullpath,
132 const string& snapshot_name,
133 BusProfile* bus_profile,
135 : playlists (new SessionPlaylists)
137 , process_function (&Session::process_with_events)
138 , waiting_for_sync_offset (false)
139 , _base_frame_rate (0)
140 , _current_frame_rate (0)
141 , _nominal_frame_rate (0)
142 , transport_sub_state (0)
143 , _record_status (Disabled)
144 , _transport_frame (0)
145 , _session_range_location (0)
148 , _transport_speed (0)
149 , _default_transport_speed (1.0)
150 , _last_transport_speed (0)
151 , _target_transport_speed (0.0)
152 , auto_play_legal (false)
153 , _last_slave_transport_frame (0)
154 , maximum_output_latency (0)
155 , _requested_return_frame (-1)
156 , current_block_size (0)
157 , _worst_output_latency (0)
158 , _worst_input_latency (0)
159 , _worst_track_latency (0)
160 , _have_captured (false)
163 , _non_soloed_outs_muted (false)
165 , _solo_isolated_cnt (0)
167 , _was_seamless (Config->get_seamless_loop ())
168 , _under_nsm_control (false)
169 , delta_accumulator_cnt (0)
170 , average_slave_delta (1800) // !!! why 1800 ???
172 , have_first_delta_accumulator (false)
173 , _slave_state (Stopped)
174 , post_export_sync (false)
175 , post_export_position (0)
177 , _export_started (false)
178 , _export_rolling (false)
179 , _pre_export_mmc_enabled (false)
180 , _name (snapshot_name)
182 , _send_qf_mtc (false)
183 , _pframes_since_last_mtc (0)
184 , session_midi_feedback (0)
186 , loop_changing (false)
188 , _session_dir (new SessionDirectory (fullpath))
189 , _current_snapshot_name (snapshot_name)
191 , state_was_pending (false)
192 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
193 , _last_roll_location (0)
194 , _last_roll_or_reversal_location (0)
195 , _last_record_location (0)
196 , pending_locate_roll (false)
197 , pending_locate_frame (0)
198 , pending_locate_flush (false)
199 , pending_abort (false)
200 , pending_auto_loop (false)
201 , _butler (new Butler (*this))
202 , _post_transport_work (0)
203 , cumulative_rf_motion (0)
205 , _locations (new Locations (*this))
207 , outbound_mtc_timecode_frame (0)
208 , next_quarter_frame_to_send (-1)
209 , _frames_per_timecode_frame (0)
210 , _frames_per_hour (0)
211 , _timecode_frames_per_hour (0)
212 , last_timecode_valid (false)
213 , last_timecode_when (0)
214 , _send_timecode_update (false)
226 , ltc_timecode_offset (0)
227 , ltc_timecode_negative_offset (false)
228 , midi_control_ui (0)
230 , _all_route_group (new RouteGroup (*this, "all"))
231 , routes (new RouteList)
232 , _adding_routes_in_progress (false)
233 , destructive_index (0)
234 , solo_update_disabled (false)
235 , default_fade_steepness (0)
236 , default_fade_msecs (0)
237 , _total_free_4k_blocks (0)
238 , _total_free_4k_blocks_uncertain (false)
239 , no_questions_about_missing_files (false)
242 , _bundles (new BundleList)
243 , _bundle_xml_node (0)
247 , click_emphasis_data (0)
249 , click_emphasis_length (0)
250 , _clicks_cleared (0)
251 , _play_range (false)
253 , first_file_data_format_reset (true)
254 , first_file_header_format_reset (true)
255 , have_looped (false)
256 , _have_rec_enabled_track (false)
258 , _suspend_timecode_transmission (0)
259 , _speakers (new Speakers)
260 , ignore_route_processor_changes (false)
264 pre_engine_init (fullpath);
267 if (create (mix_template, bus_profile)) {
269 throw failed_constructor ();
272 if (load_state (_current_snapshot_name)) {
273 throw failed_constructor ();
276 /* try to get sample rate from XML state so that we
277 * can influence the SR if we set up the audio
282 const XMLProperty* prop;
283 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
284 sr = atoi (prop->value());
289 if (_engine.current_backend() == 0 || _engine.setup_required()) {
290 boost::optional<int> r = AudioEngineSetupRequired (sr);
291 if (r.get_value_or (-1) != 0) {
293 throw failed_constructor();
297 /* at this point the engine should be connected (i.e. interacting
298 with a backend device (or psuedo-device) and available to us
299 for determinining sample rates and other settings.
302 if (!_engine.connected()) {
304 throw failed_constructor();
307 if (post_engine_init ()) {
309 throw failed_constructor ();
312 store_recent_sessions (_name, _path);
314 bool was_dirty = dirty();
316 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
318 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
319 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
322 DirtyChanged (); /* EMIT SIGNAL */
325 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
326 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
330 /* hook us up to the engine since we are now completely constructed */
332 BootMessage (_("Connect to engine"));
334 _engine.set_session (this);
335 _engine.reset_timebase ();
337 BootMessage (_("Session loading complete"));
352 vector<void*> debug_pointers;
354 /* if we got to here, leaving pending capture state around
358 remove_pending_capture_state ();
360 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
362 /* disconnect from any and all signals that we are connected to */
366 _engine.remove_session ();
368 /* deregister all ports - there will be no process or any other
369 * callbacks from the engine any more.
372 Port::PortDrop (); /* EMIT SIGNAL */
376 /* clear history so that no references to objects are held any more */
380 /* clear state tree so that no references to objects are held any more */
384 /* reset dynamic state version back to default */
386 Stateful::loading_state_version = 0;
388 _butler->drop_references ();
392 delete midi_control_ui;
393 delete _all_route_group;
395 if (click_data != default_click) {
396 delete [] click_data;
399 if (click_emphasis_data != default_click_emphasis) {
400 delete [] click_emphasis_data;
405 /* clear out any pending dead wood from RCU managed objects */
410 AudioDiskstream::free_working_buffers();
412 /* tell everyone who is still standing that we're about to die */
415 /* tell everyone to drop references and delete objects as we go */
417 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
418 RegionFactory::delete_all_regions ();
420 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
422 /* reset these three references to special routes before we do the usual route delete thing */
425 _master_out.reset ();
426 _monitor_out.reset ();
429 RCUWriter<RouteList> writer (routes);
430 boost::shared_ptr<RouteList> r = writer.get_copy ();
432 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
433 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
434 (*i)->drop_references ();
438 /* writer goes out of scope and updates master */
442 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
443 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
444 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
445 i->second->drop_references ();
450 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
451 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
456 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
463 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
465 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
466 boost_debug_list_ptrs ();
471 Session::setup_ltc ()
475 _ltc_input.reset (new IO (*this, _("LTC In"), IO::Input));
476 _ltc_output.reset (new IO (*this, _("LTC Out"), IO::Output));
478 if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-In")) != 0) {
479 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
482 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
483 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
485 reconnect_ltc_input ();
488 if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-Out")) != 0) {
489 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
492 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
493 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
495 reconnect_ltc_output ();
498 /* fix up names of LTC ports because we don't want the normal
499 * IO style of NAME/TYPE-{in,out}N
502 _ltc_input->nth (0)->set_name (_("LTC-in"));
503 _ltc_output->nth (0)->set_name (_("LTC-out"));
507 Session::setup_click ()
512 _click_io.reset (new ClickIO (*this, "click"));
513 _click_gain.reset (new Amp (*this));
514 _click_gain->activate ();
516 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
518 /* existing state for Click */
521 if (Stateful::loading_state_version < 3000) {
522 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
524 const XMLNodeList& children (child->children());
525 XMLNodeList::const_iterator i = children.begin();
526 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
528 if (i != children.end()) {
529 c = _click_gain->set_state (**i, Stateful::loading_state_version);
535 _clicking = Config->get_clicking ();
539 error << _("could not setup Click I/O") << endmsg;
546 /* default state for Click: dual-mono to first 2 physical outputs */
549 _engine.get_physical_outputs (DataType::AUDIO, outs);
551 for (uint32_t physport = 0; physport < 2; ++physport) {
552 if (outs.size() > physport) {
553 if (_click_io->add_port (outs[physport], this)) {
554 // relax, even though its an error
559 if (_click_io->n_ports () > ChanCount::ZERO) {
560 _clicking = Config->get_clicking ();
566 Session::setup_bundles ()
568 vector<string> inputs[DataType::num_types];
569 vector<string> outputs[DataType::num_types];
570 for (uint32_t i = 0; i < DataType::num_types; ++i) {
571 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
572 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
575 /* Create a set of Bundle objects that map
576 to the physical I/O currently available. We create both
577 mono and stereo bundles, so that the common cases of mono
578 and stereo tracks get bundles to put in their mixer strip
579 in / out menus. There may be a nicer way of achieving that;
580 it doesn't really scale that well to higher channel counts
583 /* mono output bundles */
585 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
587 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
589 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
590 c->add_channel (_("mono"), DataType::AUDIO);
591 c->set_port (0, outputs[DataType::AUDIO][np]);
596 /* stereo output bundles */
598 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
599 if (np + 1 < outputs[DataType::AUDIO].size()) {
601 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
602 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
603 c->add_channel (_("L"), DataType::AUDIO);
604 c->set_port (0, outputs[DataType::AUDIO][np]);
605 c->add_channel (_("R"), DataType::AUDIO);
606 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
612 /* mono input bundles */
614 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
616 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
618 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
619 c->add_channel (_("mono"), DataType::AUDIO);
620 c->set_port (0, inputs[DataType::AUDIO][np]);
625 /* stereo input bundles */
627 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
628 if (np + 1 < inputs[DataType::AUDIO].size()) {
630 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
632 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
633 c->add_channel (_("L"), DataType::AUDIO);
634 c->set_port (0, inputs[DataType::AUDIO][np]);
635 c->add_channel (_("R"), DataType::AUDIO);
636 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
642 /* MIDI input bundles */
644 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
645 string n = inputs[DataType::MIDI][np];
646 boost::erase_first (n, X_("alsa_pcm:"));
648 boost::shared_ptr<Bundle> c (new Bundle (n, false));
649 c->add_channel ("", DataType::MIDI);
650 c->set_port (0, inputs[DataType::MIDI][np]);
654 /* MIDI output bundles */
656 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
657 string n = outputs[DataType::MIDI][np];
658 boost::erase_first (n, X_("alsa_pcm:"));
660 boost::shared_ptr<Bundle> c (new Bundle (n, true));
661 c->add_channel ("", DataType::MIDI);
662 c->set_port (0, outputs[DataType::MIDI][np]);
669 Session::when_engine_running ()
671 /* every time we reconnect, recompute worst case output latencies */
673 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
675 if (synced_to_jack()) {
676 _engine.transport_stop ();
679 if (config.get_jack_time_master()) {
680 _engine.transport_locate (_transport_frame);
685 BootMessage (_("Set up LTC"));
687 BootMessage (_("Set up Click"));
689 BootMessage (_("Set up standard connections"));
693 catch (failed_constructor& err) {
697 BootMessage (_("Setup signal flow and plugins"));
699 /* Reset all panners */
701 Delivery::reset_panners ();
703 /* this will cause the CPM to instantiate any protocols that are in use
704 * (or mandatory), which will pass it this Session, and then call
705 * set_state() on each instantiated protocol to match stored state.
708 ControlProtocolManager::instance().set_session (this);
710 /* This must be done after the ControlProtocolManager set_session above,
711 as it will set states for ports which the ControlProtocolManager creates.
714 // XXX set state of MIDI::Port's
715 // MidiPortManager::instance()->set_port_states (Config->midi_port_states ());
717 /* And this must be done after the MIDI::Manager::set_port_states as
718 * it will try to make connections whose details are loaded by set_port_states.
723 /* Let control protocols know that we are now all connected, so they
724 * could start talking to surfaces if they want to.
727 ControlProtocolManager::instance().midi_connectivity_established ();
729 if (_is_new && !no_auto_connect()) {
730 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
731 auto_connect_master_bus ();
734 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
736 /* update latencies */
738 initialize_latencies ();
744 Session::auto_connect_master_bus ()
746 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
750 /* if requested auto-connect the outputs to the first N physical ports.
753 uint32_t limit = _master_out->n_outputs().n_total();
754 vector<string> outputs[DataType::num_types];
756 for (uint32_t i = 0; i < DataType::num_types; ++i) {
757 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
760 for (uint32_t n = 0; n < limit; ++n) {
761 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
763 if (outputs[p->type()].size() > n) {
764 connect_to = outputs[p->type()][n];
767 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
768 if (_master_out->output()->connect (p, connect_to, this)) {
769 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
778 Session::remove_monitor_section ()
784 /* force reversion to Solo-In-Place */
785 Config->set_solo_control_is_listen_control (false);
788 /* Hold process lock while doing this so that we don't hear bits and
789 * pieces of audio as we work on each route.
792 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
794 /* Connect tracks to monitor section. Note that in an
795 existing session, the internal sends will already exist, but we want the
796 routes to notice that they connect to the control out specifically.
800 boost::shared_ptr<RouteList> r = routes.reader ();
801 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
803 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
805 if ((*x)->is_monitor()) {
807 } else if ((*x)->is_master()) {
810 (*x)->remove_aux_or_listen (_monitor_out);
815 remove_route (_monitor_out);
816 auto_connect_master_bus ();
820 Session::add_monitor_section ()
824 if (_monitor_out || !_master_out) {
828 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
834 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
835 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
838 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
839 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
840 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
844 add_routes (rl, false, false, false);
846 assert (_monitor_out);
848 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
849 are undefined, at best.
852 uint32_t limit = _monitor_out->n_inputs().n_audio();
856 /* connect the inputs to the master bus outputs. this
857 * represents a separate data feed from the internal sends from
858 * each route. as of jan 2011, it allows the monitor section to
859 * conditionally ignore either the internal sends or the normal
860 * input feed, but we should really find a better way to do
864 _master_out->output()->disconnect (this);
866 for (uint32_t n = 0; n < limit; ++n) {
867 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
868 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
871 string connect_to = o->name();
872 if (_monitor_out->input()->connect (p, connect_to, this)) {
873 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
881 /* if monitor section is not connected, connect it to physical outs
884 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
886 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
888 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
891 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
893 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
894 Config->get_monitor_bus_preferred_bundle())
900 /* Monitor bus is audio only */
902 uint32_t mod = n_physical_outputs.get (DataType::AUDIO);
903 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
904 vector<string> outputs[DataType::num_types];
906 for (uint32_t i = 0; i < DataType::num_types; ++i) {
907 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
913 for (uint32_t n = 0; n < limit; ++n) {
915 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
917 if (outputs[DataType::AUDIO].size() > (n % mod)) {
918 connect_to = outputs[DataType::AUDIO][n % mod];
921 if (!connect_to.empty()) {
922 if (_monitor_out->output()->connect (p, connect_to, this)) {
923 error << string_compose (
924 _("cannot connect control output %1 to %2"),
935 /* Hold process lock while doing this so that we don't hear bits and
936 * pieces of audio as we work on each route.
939 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
941 /* Connect tracks to monitor section. Note that in an
942 existing session, the internal sends will already exist, but we want the
943 routes to notice that they connect to the control out specifically.
947 boost::shared_ptr<RouteList> rls = routes.reader ();
949 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
951 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
953 if ((*x)->is_monitor()) {
955 } else if ((*x)->is_master()) {
958 (*x)->enable_monitor_send ();
964 Session::hookup_io ()
966 /* stop graph reordering notifications from
967 causing resorts, etc.
970 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
974 /* we delay creating the auditioner till now because
975 it makes its own connections to ports.
979 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
981 throw failed_constructor ();
983 a->use_new_diskstream ();
987 catch (failed_constructor& err) {
988 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
992 /* load bundles, which we may have postponed earlier on */
993 if (_bundle_xml_node) {
994 load_bundles (*_bundle_xml_node);
995 delete _bundle_xml_node;
998 /* Tell all IO objects to connect themselves together */
1000 IO::enable_connecting ();
1002 /* Now tell all "floating" ports to connect to whatever
1003 they should be connected to.
1006 AudioEngine::instance()->reconnect_ports ();
1008 /* Anyone who cares about input state, wake up and do something */
1010 IOConnectionsComplete (); /* EMIT SIGNAL */
1012 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1014 /* now handle the whole enchilada as if it was one
1015 graph reorder event.
1020 /* update the full solo state, which can't be
1021 correctly determined on a per-route basis, but
1022 needs the global overview that only the session
1026 update_route_solo_state ();
1030 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1032 boost::shared_ptr<Track> track = wp.lock ();
1037 boost::shared_ptr<Playlist> playlist;
1039 if ((playlist = track->playlist()) != 0) {
1040 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1041 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1042 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1047 Session::record_enabling_legal () const
1049 /* this used to be in here, but survey says.... we don't need to restrict it */
1050 // if (record_status() == Recording) {
1054 if (Config->get_all_safe()) {
1061 Session::set_track_monitor_input_status (bool yn)
1063 boost::shared_ptr<RouteList> rl = routes.reader ();
1064 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1065 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1066 if (tr && tr->record_enabled ()) {
1067 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1068 tr->request_input_monitoring (yn);
1074 Session::auto_punch_start_changed (Location* location)
1076 replace_event (SessionEvent::PunchIn, location->start());
1078 if (get_record_enabled() && config.get_punch_in()) {
1079 /* capture start has been changed, so save new pending state */
1080 save_state ("", true);
1085 Session::auto_punch_end_changed (Location* location)
1087 framepos_t when_to_stop = location->end();
1088 // when_to_stop += _worst_output_latency + _worst_input_latency;
1089 replace_event (SessionEvent::PunchOut, when_to_stop);
1093 Session::auto_punch_changed (Location* location)
1095 framepos_t when_to_stop = location->end();
1097 replace_event (SessionEvent::PunchIn, location->start());
1098 //when_to_stop += _worst_output_latency + _worst_input_latency;
1099 replace_event (SessionEvent::PunchOut, when_to_stop);
1102 /** @param loc A loop location.
1103 * @param pos Filled in with the start time of the required fade-out (in session frames).
1104 * @param length Filled in with the length of the required fade-out.
1107 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1109 pos = max (loc->start(), loc->end() - 64);
1110 length = loc->end() - pos;
1114 Session::auto_loop_changed (Location* location)
1116 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1119 auto_loop_declick_range (location, dcp, dcl);
1120 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1122 if (transport_rolling() && play_loop) {
1125 // if (_transport_frame > location->end()) {
1127 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1128 // relocate to beginning of loop
1129 clear_events (SessionEvent::LocateRoll);
1131 request_locate (location->start(), true);
1134 else if (Config->get_seamless_loop() && !loop_changing) {
1136 // schedule a locate-roll to refill the diskstreams at the
1137 // previous loop end
1138 loop_changing = true;
1140 if (location->end() > last_loopend) {
1141 clear_events (SessionEvent::LocateRoll);
1142 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1149 last_loopend = location->end();
1153 Session::set_auto_punch_location (Location* location)
1157 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1158 punch_connections.drop_connections();
1159 existing->set_auto_punch (false, this);
1160 remove_event (existing->start(), SessionEvent::PunchIn);
1161 clear_events (SessionEvent::PunchOut);
1162 auto_punch_location_changed (0);
1167 if (location == 0) {
1171 if (location->end() <= location->start()) {
1172 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1176 punch_connections.drop_connections ();
1178 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1179 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1180 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1182 location->set_auto_punch (true, this);
1184 auto_punch_changed (location);
1186 auto_punch_location_changed (location);
1190 Session::set_auto_loop_location (Location* location)
1194 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1195 loop_connections.drop_connections ();
1196 existing->set_auto_loop (false, this);
1197 remove_event (existing->end(), SessionEvent::AutoLoop);
1200 auto_loop_declick_range (existing, dcp, dcl);
1201 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1202 auto_loop_location_changed (0);
1207 if (location == 0) {
1211 if (location->end() <= location->start()) {
1212 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1216 last_loopend = location->end();
1218 loop_connections.drop_connections ();
1220 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1221 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1222 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1224 location->set_auto_loop (true, this);
1226 /* take care of our stuff first */
1228 auto_loop_changed (location);
1230 /* now tell everyone else */
1232 auto_loop_location_changed (location);
1236 Session::locations_added (Location *)
1242 Session::locations_changed ()
1244 _locations->apply (*this, &Session::handle_locations_changed);
1248 Session::handle_locations_changed (Locations::LocationList& locations)
1250 Locations::LocationList::iterator i;
1252 bool set_loop = false;
1253 bool set_punch = false;
1255 for (i = locations.begin(); i != locations.end(); ++i) {
1259 if (location->is_auto_punch()) {
1260 set_auto_punch_location (location);
1263 if (location->is_auto_loop()) {
1264 set_auto_loop_location (location);
1268 if (location->is_session_range()) {
1269 _session_range_location = location;
1274 set_auto_loop_location (0);
1277 set_auto_punch_location (0);
1284 Session::enable_record ()
1286 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1287 /* no recording at anything except normal speed */
1292 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1294 if (rs == Recording) {
1298 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1300 _last_record_location = _transport_frame;
1301 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1303 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1304 set_track_monitor_input_status (true);
1307 RecordStateChanged ();
1314 Session::disable_record (bool rt_context, bool force)
1318 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1320 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1321 g_atomic_int_set (&_record_status, Disabled);
1322 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1324 if (rs == Recording) {
1325 g_atomic_int_set (&_record_status, Enabled);
1329 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1330 set_track_monitor_input_status (false);
1333 RecordStateChanged (); /* emit signal */
1336 remove_pending_capture_state ();
1342 Session::step_back_from_record ()
1344 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1346 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1347 set_track_monitor_input_status (false);
1350 RecordStateChanged (); /* emit signal */
1355 Session::maybe_enable_record ()
1357 if (_step_editors > 0) {
1361 g_atomic_int_set (&_record_status, Enabled);
1363 /* This function is currently called from somewhere other than an RT thread.
1364 This save_state() call therefore doesn't impact anything. Doing it here
1365 means that we save pending state of which sources the next record will use,
1366 which gives us some chance of recovering from a crash during the record.
1369 save_state ("", true);
1371 if (_transport_speed) {
1372 if (!config.get_punch_in()) {
1376 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1377 RecordStateChanged (); /* EMIT SIGNAL */
1384 Session::audible_frame () const
1390 /* the first of these two possible settings for "offset"
1391 mean that the audible frame is stationary until
1392 audio emerges from the latency compensation
1395 the second means that the audible frame is stationary
1396 until audio would emerge from a physical port
1397 in the absence of any plugin latency compensation
1400 offset = worst_playback_latency ();
1402 if (offset > current_block_size) {
1403 offset -= current_block_size;
1405 /* XXX is this correct? if we have no external
1406 physical connections and everything is internal
1407 then surely this is zero? still, how
1408 likely is that anyway?
1410 offset = current_block_size;
1413 if (synced_to_jack()) {
1414 tf = _engine.transport_frame();
1416 tf = _transport_frame;
1421 if (!non_realtime_work_pending()) {
1425 /* Check to see if we have passed the first guaranteed
1426 audible frame past our last start position. if not,
1427 return that last start point because in terms
1428 of audible frames, we have not moved yet.
1430 `Start position' in this context means the time we last
1431 either started, located, or changed transport direction.
1434 if (_transport_speed > 0.0f) {
1436 if (!play_loop || !have_looped) {
1437 if (tf < _last_roll_or_reversal_location + offset) {
1438 return _last_roll_or_reversal_location;
1446 } else if (_transport_speed < 0.0f) {
1448 /* XXX wot? no backward looping? */
1450 if (tf > _last_roll_or_reversal_location - offset) {
1451 return _last_roll_or_reversal_location;
1463 Session::set_frame_rate (framecnt_t frames_per_second)
1465 /** \fn void Session::set_frame_size(framecnt_t)
1466 the AudioEngine object that calls this guarantees
1467 that it will not be called while we are also in
1468 ::process(). Its fine to do things that block
1472 _base_frame_rate = frames_per_second;
1473 _nominal_frame_rate = frames_per_second;
1479 // XXX we need some equivalent to this, somehow
1480 // SndFileSource::setup_standard_crossfades (frames_per_second);
1484 /* XXX need to reset/reinstantiate all LADSPA plugins */
1488 Session::set_block_size (pframes_t nframes)
1490 /* the AudioEngine guarantees
1491 that it will not be called while we are also in
1492 ::process(). It is therefore fine to do things that block
1497 current_block_size = nframes;
1501 boost::shared_ptr<RouteList> r = routes.reader ();
1503 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1504 (*i)->set_block_size (nframes);
1507 boost::shared_ptr<RouteList> rl = routes.reader ();
1508 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1509 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1511 tr->set_block_size (nframes);
1515 set_worst_io_latencies ();
1521 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1523 boost::shared_ptr<Route> r2;
1525 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1526 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1530 /* make a copy of the existing list of routes that feed r1 */
1532 Route::FedBy existing (r1->fed_by());
1534 /* for each route that feeds r1, recurse, marking it as feeding
1538 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1539 if (!(r2 = i->r.lock ())) {
1540 /* (*i) went away, ignore it */
1544 /* r2 is a route that feeds r1 which somehow feeds base. mark
1545 base as being fed by r2
1548 rbase->add_fed_by (r2, i->sends_only);
1552 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1556 if (r1->feeds (r2) && r2->feeds (r1)) {
1560 /* now recurse, so that we can mark base as being fed by
1561 all routes that feed r2
1564 trace_terminal (r2, rbase);
1571 Session::resort_routes ()
1573 /* don't do anything here with signals emitted
1574 by Routes during initial setup or while we
1575 are being destroyed.
1578 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1583 RCUWriter<RouteList> writer (routes);
1584 boost::shared_ptr<RouteList> r = writer.get_copy ();
1585 resort_routes_using (r);
1586 /* writer goes out of scope and forces update */
1590 boost::shared_ptr<RouteList> rl = routes.reader ();
1591 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1592 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1594 const Route::FedBy& fb ((*i)->fed_by());
1596 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1597 boost::shared_ptr<Route> sf = f->r.lock();
1599 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1607 /** This is called whenever we need to rebuild the graph of how we will process
1609 * @param r List of routes, in any order.
1613 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1615 /* We are going to build a directed graph of our routes;
1616 this is where the edges of that graph are put.
1621 /* Go through all routes doing two things:
1623 * 1. Collect the edges of the route graph. Each of these edges
1624 * is a pair of routes, one of which directly feeds the other
1625 * either by a JACK connection or by an internal send.
1627 * 2. Begin the process of making routes aware of which other
1628 * routes directly or indirectly feed them. This information
1629 * is used by the solo code.
1632 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1634 /* Clear out the route's list of direct or indirect feeds */
1635 (*i)->clear_fed_by ();
1637 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1639 bool via_sends_only;
1641 /* See if this *j feeds *i according to the current state of the JACK
1642 connections and internal sends.
1644 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1645 /* add the edge to the graph (part #1) */
1646 edges.add (*j, *i, via_sends_only);
1647 /* tell the route (for part #2) */
1648 (*i)->add_fed_by (*j, via_sends_only);
1653 /* Attempt a topological sort of the route graph */
1654 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1656 if (sorted_routes) {
1657 /* We got a satisfactory topological sort, so there is no feedback;
1660 Note: the process graph rechain does not require a
1661 topologically-sorted list, but hey ho.
1663 if (_process_graph) {
1664 _process_graph->rechain (sorted_routes, edges);
1667 _current_route_graph = edges;
1669 /* Complete the building of the routes' lists of what directly
1670 or indirectly feeds them.
1672 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1673 trace_terminal (*i, *i);
1676 *r = *sorted_routes;
1679 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1680 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1681 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1682 (*i)->name(), (*i)->order_key (MixerSort)));
1686 SuccessfulGraphSort (); /* EMIT SIGNAL */
1689 /* The topological sort failed, so we have a problem. Tell everyone
1690 and stick to the old graph; this will continue to be processed, so
1691 until the feedback is fixed, what is played back will not quite
1692 reflect what is actually connected. Note also that we do not
1693 do trace_terminal here, as it would fail due to an endless recursion,
1694 so the solo code will think that everything is still connected
1698 FeedbackDetected (); /* EMIT SIGNAL */
1703 /** Find a route name starting with \a base, maybe followed by the
1704 * lowest \a id. \a id will always be added if \a definitely_add_number
1705 * is true on entry; otherwise it will only be added if required
1706 * to make the name unique.
1708 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1709 * The available route name with the lowest ID will be used, and \a id
1710 * will be set to the ID.
1712 * \return false if a route name could not be found, and \a track_name
1713 * and \a id do not reflect a free route name.
1716 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1718 if (!definitely_add_number && route_by_name (base) == 0) {
1719 /* juse use the base */
1720 snprintf (name, name_len, "%s", base.c_str());
1725 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1727 if (route_by_name (name) == 0) {
1733 } while (id < (UINT_MAX-1));
1738 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1740 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1742 in = ChanCount::ZERO;
1743 out = ChanCount::ZERO;
1745 boost::shared_ptr<RouteList> r = routes.reader ();
1747 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1748 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1749 if (tr && !tr->is_auditioner()) {
1750 in += tr->n_inputs();
1751 out += tr->n_outputs();
1756 /** Caller must not hold process lock
1757 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1758 * @param instrument plugin info for the instrument to insert pre-fader, if any
1760 list<boost::shared_ptr<MidiTrack> >
1761 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1762 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1764 char track_name[32];
1765 uint32_t track_id = 0;
1767 RouteList new_routes;
1768 list<boost::shared_ptr<MidiTrack> > ret;
1770 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1773 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1774 error << "cannot find name for new midi track" << endmsg;
1778 boost::shared_ptr<MidiTrack> track;
1781 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1783 if (track->init ()) {
1787 track->use_new_diskstream();
1789 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1790 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1793 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1794 if (track->input()->ensure_io (input, false, this)) {
1795 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1799 if (track->output()->ensure_io (output, false, this)) {
1800 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1805 track->non_realtime_input_change();
1808 route_group->add (track);
1811 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1813 if (Config->get_remote_model() == UserOrdered) {
1814 track->set_remote_control_id (next_control_id());
1817 new_routes.push_back (track);
1818 ret.push_back (track);
1821 catch (failed_constructor &err) {
1822 error << _("Session: could not create new midi track.") << endmsg;
1826 catch (AudioEngine::PortRegistrationFailure& pfe) {
1828 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;
1836 if (!new_routes.empty()) {
1837 add_routes (new_routes, true, true, true);
1840 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1841 PluginPtr plugin = instrument->load (*this);
1842 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1843 (*r)->add_processor (p, PreFader);
1853 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1855 boost::shared_ptr<Route> midi_track (wmt.lock());
1861 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1863 if (change.after.n_audio() <= change.before.n_audio()) {
1867 /* new audio ports: make sure the audio goes somewhere useful,
1868 unless the user has no-auto-connect selected.
1870 The existing ChanCounts don't matter for this call as they are only
1871 to do with matching input and output indices, and we are only changing
1877 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1881 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1882 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1883 * @param output_start As \a input_start, but for outputs.
1886 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1887 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1889 if (!IO::connecting_legal) {
1893 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1899 /* If both inputs and outputs are auto-connected to physical ports,
1900 use the max of input and output offsets to ensure auto-connected
1901 port numbers always match up (e.g. the first audio input and the
1902 first audio output of the route will have the same physical
1903 port number). Otherwise just use the lowest input or output
1907 DEBUG_TRACE (DEBUG::Graph,
1908 string_compose("Auto-connect: existing in = %1 out = %2\n",
1909 existing_inputs, existing_outputs));
1911 const bool in_out_physical =
1912 (Config->get_input_auto_connect() & AutoConnectPhysical)
1913 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1916 const ChanCount in_offset = in_out_physical
1917 ? ChanCount::max(existing_inputs, existing_outputs)
1920 const ChanCount out_offset = in_out_physical
1921 ? ChanCount::max(existing_inputs, existing_outputs)
1924 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1925 vector<string> physinputs;
1926 vector<string> physoutputs;
1928 _engine.get_physical_outputs (*t, physoutputs);
1929 _engine.get_physical_inputs (*t, physinputs);
1931 if (!physinputs.empty() && connect_inputs) {
1932 uint32_t nphysical_in = physinputs.size();
1934 DEBUG_TRACE (DEBUG::Graph,
1935 string_compose("There are %1 physical inputs of type %2\n",
1938 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1941 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1942 DEBUG_TRACE (DEBUG::Graph,
1943 string_compose("Get index %1 + %2 % %3 = %4\n",
1944 in_offset.get(*t), i, nphysical_in,
1945 (in_offset.get(*t) + i) % nphysical_in));
1946 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1949 DEBUG_TRACE (DEBUG::Graph,
1950 string_compose("Connect route %1 IN to %2\n",
1951 route->name(), port));
1953 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1957 ChanCount one_added (*t, 1);
1958 existing_inputs += one_added;
1962 if (!physoutputs.empty()) {
1963 uint32_t nphysical_out = physoutputs.size();
1964 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
1967 if ((*t) == DataType::MIDI || Config->get_output_auto_connect() & AutoConnectPhysical) {
1968 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1969 } else if ((*t) == DataType::AUDIO && Config->get_output_auto_connect() & AutoConnectMaster) {
1970 /* master bus is audio only */
1971 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1972 port = _master_out->input()->ports().port(*t,
1973 i % _master_out->input()->n_ports().get(*t))->name();
1977 DEBUG_TRACE (DEBUG::Graph,
1978 string_compose("Connect route %1 OUT to %2\n",
1979 route->name(), port));
1981 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
1985 ChanCount one_added (*t, 1);
1986 existing_outputs += one_added;
1992 /** Caller must not hold process lock
1993 * @param name_template string to use for the start of the name, or "" to use "Audio".
1995 list< boost::shared_ptr<AudioTrack> >
1996 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
1997 uint32_t how_many, string name_template)
1999 char track_name[32];
2000 uint32_t track_id = 0;
2002 RouteList new_routes;
2003 list<boost::shared_ptr<AudioTrack> > ret;
2005 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2008 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2009 error << "cannot find name for new audio track" << endmsg;
2013 boost::shared_ptr<AudioTrack> track;
2016 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2018 if (track->init ()) {
2022 track->use_new_diskstream();
2024 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2025 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2028 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2030 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2031 error << string_compose (
2032 _("cannot configure %1 in/%2 out configuration for new audio track"),
2033 input_channels, output_channels)
2038 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2039 error << string_compose (
2040 _("cannot configure %1 in/%2 out configuration for new audio track"),
2041 input_channels, output_channels)
2048 route_group->add (track);
2051 track->non_realtime_input_change();
2053 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2054 if (Config->get_remote_model() == UserOrdered) {
2055 track->set_remote_control_id (next_control_id());
2058 new_routes.push_back (track);
2059 ret.push_back (track);
2062 catch (failed_constructor &err) {
2063 error << _("Session: could not create new audio track.") << endmsg;
2067 catch (AudioEngine::PortRegistrationFailure& pfe) {
2069 error << pfe.what() << endmsg;
2077 if (!new_routes.empty()) {
2078 add_routes (new_routes, true, true, true);
2084 /** Caller must not hold process lock.
2085 * @param name_template string to use for the start of the name, or "" to use "Bus".
2088 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2091 uint32_t bus_id = 0;
2095 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2098 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2099 error << "cannot find name for new audio bus" << endmsg;
2104 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2110 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2111 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2114 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2116 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2117 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2118 input_channels, output_channels)
2124 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2125 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2126 input_channels, output_channels)
2133 route_group->add (bus);
2135 if (Config->get_remote_model() == UserOrdered) {
2136 bus->set_remote_control_id (next_control_id());
2139 bus->add_internal_return ();
2141 ret.push_back (bus);
2147 catch (failed_constructor &err) {
2148 error << _("Session: could not create new audio route.") << endmsg;
2152 catch (AudioEngine::PortRegistrationFailure& pfe) {
2153 error << pfe.what() << endmsg;
2163 add_routes (ret, false, true, true); // autoconnect outputs only
2171 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2174 uint32_t control_id;
2176 uint32_t number = 0;
2177 const uint32_t being_added = how_many;
2179 if (!tree.read (template_path.c_str())) {
2183 XMLNode* node = tree.root();
2185 IO::disable_connecting ();
2187 control_id = next_control_id ();
2191 XMLNode node_copy (*node);
2193 /* Remove IDs of everything so that new ones are used */
2194 node_copy.remove_property_recursively (X_("id"));
2199 if (!name_base.empty()) {
2201 /* if we're adding more than one routes, force
2202 * all the names of the new routes to be
2203 * numbered, via the final parameter.
2206 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2207 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2213 string const route_name = node_copy.property(X_("name"))->value ();
2215 /* generate a new name by adding a number to the end of the template name */
2216 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2217 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2222 /* set this name in the XML description that we are about to use */
2223 Route::set_name_in_state (node_copy, name);
2225 /* trim bitslots from listen sends so that new ones are used */
2226 XMLNodeList children = node_copy.children ();
2227 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2228 if ((*i)->name() == X_("Processor")) {
2229 XMLProperty* role = (*i)->property (X_("role"));
2230 if (role && role->value() == X_("Listen")) {
2231 (*i)->remove_property (X_("bitslot"));
2236 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2239 error << _("Session: cannot create track/bus from template description") << endmsg;
2243 if (boost::dynamic_pointer_cast<Track>(route)) {
2244 /* force input/output change signals so that the new diskstream
2245 picks up the configuration of the route. During session
2246 loading this normally happens in a different way.
2249 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2251 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2252 change.after = route->input()->n_ports();
2253 route->input()->changed (change, this);
2254 change.after = route->output()->n_ports();
2255 route->output()->changed (change, this);
2258 route->set_remote_control_id (control_id);
2261 ret.push_back (route);
2264 catch (failed_constructor &err) {
2265 error << _("Session: could not create new route from template") << endmsg;
2269 catch (AudioEngine::PortRegistrationFailure& pfe) {
2270 error << pfe.what() << endmsg;
2279 add_routes (ret, true, true, true);
2280 IO::enable_connecting ();
2287 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2290 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2291 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2294 error << _("Adding new tracks/busses failed") << endmsg;
2299 update_latency (true);
2300 update_latency (false);
2305 save_state (_current_snapshot_name);
2308 RouteAdded (new_routes); /* EMIT SIGNAL */
2312 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2314 ChanCount existing_inputs;
2315 ChanCount existing_outputs;
2316 uint32_t order = next_control_id();
2318 count_existing_track_channels (existing_inputs, existing_outputs);
2321 RCUWriter<RouteList> writer (routes);
2322 boost::shared_ptr<RouteList> r = writer.get_copy ();
2323 r->insert (r->end(), new_routes.begin(), new_routes.end());
2325 /* if there is no control out and we're not in the middle of loading,
2326 resort the graph here. if there is a control out, we will resort
2327 toward the end of this method. if we are in the middle of loading,
2328 we will resort when done.
2331 if (!_monitor_out && IO::connecting_legal) {
2332 resort_routes_using (r);
2336 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2338 boost::weak_ptr<Route> wpr (*x);
2339 boost::shared_ptr<Route> r (*x);
2341 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2342 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2343 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2344 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2345 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2346 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2348 if (r->is_master()) {
2352 if (r->is_monitor()) {
2356 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2358 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2359 track_playlist_changed (boost::weak_ptr<Track> (tr));
2360 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2362 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2364 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2365 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2370 if (input_auto_connect || output_auto_connect) {
2371 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2374 /* order keys are a GUI responsibility but we need to set up
2375 reasonable defaults because they also affect the remote control
2376 ID in most situations.
2379 if (!r->has_order_key (EditorSort)) {
2380 if (r->is_auditioner()) {
2381 /* use an arbitrarily high value */
2382 r->set_order_key (EditorSort, UINT_MAX);
2383 r->set_order_key (MixerSort, UINT_MAX);
2385 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2386 r->set_order_key (EditorSort, order);
2387 r->set_order_key (MixerSort, order);
2395 if (_monitor_out && IO::connecting_legal) {
2396 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2398 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2399 if ((*x)->is_monitor()) {
2401 } else if ((*x)->is_master()) {
2404 (*x)->enable_monitor_send ();
2411 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2413 boost::shared_ptr<RouteList> r = routes.reader ();
2414 boost::shared_ptr<Send> s;
2416 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2417 if ((s = (*i)->internal_send_for (dest)) != 0) {
2418 s->amp()->gain_control()->set_value (0.0);
2424 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2426 boost::shared_ptr<RouteList> r = routes.reader ();
2427 boost::shared_ptr<Send> s;
2429 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2430 if ((s = (*i)->internal_send_for (dest)) != 0) {
2431 s->amp()->gain_control()->set_value (1.0);
2437 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2439 boost::shared_ptr<RouteList> r = routes.reader ();
2440 boost::shared_ptr<Send> s;
2442 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2443 if ((s = (*i)->internal_send_for (dest)) != 0) {
2444 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2449 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2451 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2453 boost::shared_ptr<RouteList> r = routes.reader ();
2454 boost::shared_ptr<RouteList> t (new RouteList);
2456 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2457 /* no MIDI sends because there are no MIDI busses yet */
2458 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2463 add_internal_sends (dest, p, t);
2467 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2469 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2470 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2475 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2477 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2481 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2483 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2487 if (!dest->internal_return()) {
2488 dest->add_internal_return ();
2491 sender->add_aux_send (dest, before);
2497 Session::remove_route (boost::shared_ptr<Route> route)
2499 if (route == _master_out) {
2503 route->set_solo (false, this);
2506 RCUWriter<RouteList> writer (routes);
2507 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2511 /* deleting the master out seems like a dumb
2512 idea, but its more of a UI policy issue
2516 if (route == _master_out) {
2517 _master_out = boost::shared_ptr<Route> ();
2520 if (route == _monitor_out) {
2521 _monitor_out.reset ();
2524 /* writer goes out of scope, forces route list update */
2527 update_route_solo_state ();
2529 // We need to disconnect the route's inputs and outputs
2531 route->input()->disconnect (0);
2532 route->output()->disconnect (0);
2534 /* if the route had internal sends sending to it, remove them */
2535 if (route->internal_return()) {
2537 boost::shared_ptr<RouteList> r = routes.reader ();
2538 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2539 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2541 (*i)->remove_processor (s);
2546 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2547 if (mt && mt->step_editing()) {
2548 if (_step_editors > 0) {
2553 update_latency_compensation ();
2556 /* Re-sort routes to remove the graph's current references to the one that is
2557 * going away, then flush old references out of the graph.
2561 if (_process_graph) {
2562 _process_graph->clear_other_chain ();
2565 /* get rid of it from the dead wood collection in the route list manager */
2567 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2571 /* try to cause everyone to drop their references */
2573 route->drop_references ();
2575 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2577 /* save the new state of the world */
2579 if (save_state (_current_snapshot_name)) {
2580 save_history (_current_snapshot_name);
2585 Session::route_mute_changed (void* /*src*/)
2591 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2593 boost::shared_ptr<Route> route = wpr.lock();
2595 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2599 if (route->listening_via_monitor ()) {
2601 if (Config->get_exclusive_solo()) {
2602 /* new listen: disable all other listen */
2603 boost::shared_ptr<RouteList> r = routes.reader ();
2604 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2605 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2608 (*i)->set_listen (false, this);
2614 } else if (_listen_cnt > 0) {
2619 update_route_solo_state ();
2622 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2624 boost::shared_ptr<Route> route = wpr.lock ();
2627 /* should not happen */
2628 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2632 bool send_changed = false;
2634 if (route->solo_isolated()) {
2635 if (_solo_isolated_cnt == 0) {
2636 send_changed = true;
2638 _solo_isolated_cnt++;
2639 } else if (_solo_isolated_cnt > 0) {
2640 _solo_isolated_cnt--;
2641 if (_solo_isolated_cnt == 0) {
2642 send_changed = true;
2647 IsolatedChanged (); /* EMIT SIGNAL */
2652 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2654 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2656 if (!self_solo_change) {
2657 // session doesn't care about changes to soloed-by-others
2661 if (solo_update_disabled) {
2663 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2667 boost::shared_ptr<Route> route = wpr.lock ();
2670 boost::shared_ptr<RouteList> r = routes.reader ();
2673 if (route->self_soloed()) {
2679 RouteGroup* rg = route->route_group ();
2680 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2682 if (delta == 1 && Config->get_exclusive_solo()) {
2684 /* new solo: disable all other solos, but not the group if its solo-enabled */
2686 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2687 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2688 (leave_group_alone && ((*i)->route_group() == rg))) {
2691 (*i)->set_solo (false, this);
2695 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2697 solo_update_disabled = true;
2699 RouteList uninvolved;
2701 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2703 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2704 bool via_sends_only;
2705 bool in_signal_flow;
2707 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2708 (leave_group_alone && ((*i)->route_group() == rg))) {
2712 in_signal_flow = false;
2714 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2716 if ((*i)->feeds (route, &via_sends_only)) {
2717 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2718 if (!via_sends_only) {
2719 if (!route->soloed_by_others_upstream()) {
2720 (*i)->mod_solo_by_others_downstream (delta);
2723 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2725 in_signal_flow = true;
2727 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2730 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2732 if (route->feeds (*i, &via_sends_only)) {
2733 /* propagate solo upstream only if routing other than
2734 sends is involved, but do consider the other route
2735 (*i) to be part of the signal flow even if only
2738 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2742 route->soloed_by_others_downstream(),
2743 route->soloed_by_others_upstream()));
2744 if (!via_sends_only) {
2745 if (!route->soloed_by_others_downstream()) {
2746 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2747 (*i)->mod_solo_by_others_upstream (delta);
2749 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2752 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2754 in_signal_flow = true;
2756 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2759 if (!in_signal_flow) {
2760 uninvolved.push_back (*i);
2764 solo_update_disabled = false;
2765 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2767 update_route_solo_state (r);
2769 /* now notify that the mute state of the routes not involved in the signal
2770 pathway of the just-solo-changed route may have altered.
2773 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2774 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2775 (*i)->mute_changed (this);
2778 SoloChanged (); /* EMIT SIGNAL */
2783 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2785 /* now figure out if anything that matters is soloed (or is "listening")*/
2787 bool something_soloed = false;
2788 uint32_t listeners = 0;
2789 uint32_t isolated = 0;
2792 r = routes.reader();
2795 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2796 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2797 something_soloed = true;
2800 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2801 if (Config->get_solo_control_is_listen_control()) {
2804 (*i)->set_listen (false, this);
2808 if ((*i)->solo_isolated()) {
2813 if (something_soloed != _non_soloed_outs_muted) {
2814 _non_soloed_outs_muted = something_soloed;
2815 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2818 _listen_cnt = listeners;
2820 if (isolated != _solo_isolated_cnt) {
2821 _solo_isolated_cnt = isolated;
2822 IsolatedChanged (); /* EMIT SIGNAL */
2825 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2826 something_soloed, listeners, isolated));
2829 boost::shared_ptr<RouteList>
2830 Session::get_routes_with_internal_returns() const
2832 boost::shared_ptr<RouteList> r = routes.reader ();
2833 boost::shared_ptr<RouteList> rl (new RouteList);
2835 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2836 if ((*i)->internal_return ()) {
2844 Session::io_name_is_legal (const std::string& name)
2846 boost::shared_ptr<RouteList> r = routes.reader ();
2848 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2849 if ((*i)->name() == name) {
2853 if ((*i)->has_io_processor_named (name)) {
2862 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2865 vector<string> connections;
2867 /* if we are passed only a single route and we're not told to turn
2868 * others off, then just do the simple thing.
2871 if (flip_others == false && rl->size() == 1) {
2872 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2874 mt->set_input_active (onoff);
2879 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2881 PortSet& ps ((*rt)->input()->ports());
2883 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2884 p->get_connections (connections);
2887 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2888 routes_using_input_from (*s, rl2);
2891 /* scan all relevant routes to see if others are on or off */
2893 bool others_are_already_on = false;
2895 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2897 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2903 if ((*r) != (*rt)) {
2904 if (mt->input_active()) {
2905 others_are_already_on = true;
2908 /* this one needs changing */
2909 mt->set_input_active (onoff);
2915 /* globally reverse other routes */
2917 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2918 if ((*r) != (*rt)) {
2919 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2921 mt->set_input_active (!others_are_already_on);
2930 Session::routes_using_input_from (const string& str, RouteList& rl)
2932 boost::shared_ptr<RouteList> r = routes.reader();
2934 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2935 if ((*i)->input()->connected_to (str)) {
2941 boost::shared_ptr<Route>
2942 Session::route_by_name (string name)
2944 boost::shared_ptr<RouteList> r = routes.reader ();
2946 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2947 if ((*i)->name() == name) {
2952 return boost::shared_ptr<Route> ((Route*) 0);
2955 boost::shared_ptr<Route>
2956 Session::route_by_id (PBD::ID id)
2958 boost::shared_ptr<RouteList> r = routes.reader ();
2960 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2961 if ((*i)->id() == id) {
2966 return boost::shared_ptr<Route> ((Route*) 0);
2969 boost::shared_ptr<Track>
2970 Session::track_by_diskstream_id (PBD::ID id)
2972 boost::shared_ptr<RouteList> r = routes.reader ();
2974 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2975 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
2976 if (t && t->using_diskstream_id (id)) {
2981 return boost::shared_ptr<Track> ();
2984 boost::shared_ptr<Route>
2985 Session::route_by_remote_id (uint32_t id)
2987 boost::shared_ptr<RouteList> r = routes.reader ();
2989 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2990 if ((*i)->remote_control_id() == id) {
2995 return boost::shared_ptr<Route> ((Route*) 0);
2999 Session::playlist_region_added (boost::weak_ptr<Region> w)
3001 boost::shared_ptr<Region> r = w.lock ();
3006 /* These are the operations that are currently in progress... */
3007 list<GQuark> curr = _current_trans_quarks;
3010 /* ...and these are the operations during which we want to update
3011 the session range location markers.
3014 ops.push_back (Operations::capture);
3015 ops.push_back (Operations::paste);
3016 ops.push_back (Operations::duplicate_region);
3017 ops.push_back (Operations::insert_file);
3018 ops.push_back (Operations::insert_region);
3019 ops.push_back (Operations::drag_region_brush);
3020 ops.push_back (Operations::region_drag);
3021 ops.push_back (Operations::selection_grab);
3022 ops.push_back (Operations::region_fill);
3023 ops.push_back (Operations::fill_selection);
3024 ops.push_back (Operations::create_region);
3025 ops.push_back (Operations::region_copy);
3026 ops.push_back (Operations::fixed_time_region_copy);
3029 /* See if any of the current operations match the ones that we want */
3031 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3033 /* If so, update the session range markers */
3035 maybe_update_session_range (r->position (), r->last_frame ());
3039 /** Update the session range markers if a is before the current start or
3040 * b is after the current end.
3043 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3045 if (_state_of_the_state & Loading) {
3049 if (_session_range_location == 0) {
3051 add_session_range_location (a, b);
3055 if (a < _session_range_location->start()) {
3056 _session_range_location->set_start (a);
3059 if (b > _session_range_location->end()) {
3060 _session_range_location->set_end (b);
3066 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3068 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3069 maybe_update_session_range (i->to, i->to + i->length);
3074 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3076 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3077 maybe_update_session_range (i->from, i->to);
3081 /* Region management */
3083 boost::shared_ptr<Region>
3084 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3086 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3087 RegionFactory::RegionMap::const_iterator i;
3088 boost::shared_ptr<Region> region;
3090 Glib::Threads::Mutex::Lock lm (region_lock);
3092 for (i = regions.begin(); i != regions.end(); ++i) {
3096 if (region->whole_file()) {
3098 if (child->source_equivalent (region)) {
3104 return boost::shared_ptr<Region> ();
3108 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3110 set<boost::shared_ptr<Region> > relevant_regions;
3112 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3113 RegionFactory::get_regions_using_source (*s, relevant_regions);
3116 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3117 set<boost::shared_ptr<Region> >::iterator tmp;
3122 playlists->destroy_region (*r);
3123 RegionFactory::map_remove (*r);
3125 (*r)->drop_sources ();
3126 (*r)->drop_references ();
3128 relevant_regions.erase (r);
3133 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3136 Glib::Threads::Mutex::Lock ls (source_lock);
3137 /* remove from the main source list */
3138 sources.erase ((*s)->id());
3141 (*s)->mark_for_remove ();
3142 (*s)->drop_references ();
3151 Session::remove_last_capture ()
3153 list<boost::shared_ptr<Source> > srcs;
3155 boost::shared_ptr<RouteList> rl = routes.reader ();
3156 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3157 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3162 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3165 srcs.insert (srcs.end(), l.begin(), l.end());
3170 destroy_sources (srcs);
3172 save_state (_current_snapshot_name);
3177 /* Source Management */
3180 Session::add_source (boost::shared_ptr<Source> source)
3182 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3183 pair<SourceMap::iterator,bool> result;
3185 entry.first = source->id();
3186 entry.second = source;
3189 Glib::Threads::Mutex::Lock lm (source_lock);
3190 result = sources.insert (entry);
3193 if (result.second) {
3195 /* yay, new source */
3197 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3200 if (!fs->within_session()) {
3201 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3207 boost::shared_ptr<AudioFileSource> afs;
3209 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3210 if (Config->get_auto_analyse_audio()) {
3211 Analyser::queue_source_for_analysis (source, false);
3215 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3220 Session::remove_source (boost::weak_ptr<Source> src)
3222 if (_state_of_the_state & Deletion) {
3226 SourceMap::iterator i;
3227 boost::shared_ptr<Source> source = src.lock();
3234 Glib::Threads::Mutex::Lock lm (source_lock);
3236 if ((i = sources.find (source->id())) != sources.end()) {
3241 if (!(_state_of_the_state & InCleanup)) {
3243 /* save state so we don't end up with a session file
3244 referring to non-existent sources.
3247 save_state (_current_snapshot_name);
3251 boost::shared_ptr<Source>
3252 Session::source_by_id (const PBD::ID& id)
3254 Glib::Threads::Mutex::Lock lm (source_lock);
3255 SourceMap::iterator i;
3256 boost::shared_ptr<Source> source;
3258 if ((i = sources.find (id)) != sources.end()) {
3265 boost::shared_ptr<Source>
3266 Session::source_by_path_and_channel (const string& path, uint16_t chn)
3268 Glib::Threads::Mutex::Lock lm (source_lock);
3270 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3271 boost::shared_ptr<AudioFileSource> afs
3272 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3274 if (afs && afs->path() == path && chn == afs->channel()) {
3278 return boost::shared_ptr<Source>();
3282 Session::count_sources_by_origin (const string& path)
3285 Glib::Threads::Mutex::Lock lm (source_lock);
3287 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3288 boost::shared_ptr<FileSource> fs
3289 = boost::dynamic_pointer_cast<FileSource>(i->second);
3291 if (fs && fs->origin() == path) {
3301 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3304 string old_basename = PBD::basename_nosuffix (oldname);
3305 string new_legalized = legalize_for_path (newname);
3307 /* note: we know (or assume) the old path is already valid */
3311 /* destructive file sources have a name of the form:
3313 /path/to/Tnnnn-NAME(%[LR])?.wav
3315 the task here is to replace NAME with the new name.
3320 string::size_type dash;
3322 dir = Glib::path_get_dirname (path);
3323 path = Glib::path_get_basename (path);
3325 /* '-' is not a legal character for the NAME part of the path */
3327 if ((dash = path.find_last_of ('-')) == string::npos) {
3331 prefix = path.substr (0, dash);
3335 path += new_legalized;
3336 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3337 path = Glib::build_filename (dir, path);
3341 /* non-destructive file sources have a name of the form:
3343 /path/to/NAME-nnnnn(%[LR])?.ext
3345 the task here is to replace NAME with the new name.
3350 string::size_type dash;
3351 string::size_type postfix;
3353 dir = Glib::path_get_dirname (path);
3354 path = Glib::path_get_basename (path);
3356 /* '-' is not a legal character for the NAME part of the path */
3358 if ((dash = path.find_last_of ('-')) == string::npos) {
3362 suffix = path.substr (dash+1);
3364 // Suffix is now everything after the dash. Now we need to eliminate
3365 // the nnnnn part, which is done by either finding a '%' or a '.'
3367 postfix = suffix.find_last_of ("%");
3368 if (postfix == string::npos) {
3369 postfix = suffix.find_last_of ('.');
3372 if (postfix != string::npos) {
3373 suffix = suffix.substr (postfix);
3375 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3379 const uint32_t limit = 10000;
3380 char buf[PATH_MAX+1];
3382 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3384 snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
3386 if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
3387 path = Glib::build_filename (dir, buf);
3395 fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
3404 /** Return the full path (in some session directory) for a new within-session source.
3405 * \a name must be a session-unique name that does not contain slashes
3406 * (e.g. as returned by new_*_source_name)
3409 Session::new_source_path_from_name (DataType type, const string& name)
3411 assert(name.find("/") == string::npos);
3413 SessionDirectory sdir(get_best_session_directory_for_new_source());
3416 if (type == DataType::AUDIO) {
3417 p = sdir.sound_path();
3418 } else if (type == DataType::MIDI) {
3419 p = sdir.midi_path();
3421 error << "Unknown source type, unable to create file path" << endmsg;
3425 return Glib::build_filename (p, name);
3429 Session::peak_path (string base) const
3431 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3434 /** Return a unique name based on \a base for a new internal audio source */
3436 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3439 char buf[PATH_MAX+1];
3440 const uint32_t limit = 10000;
3442 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3445 legalized = legalize_for_path (base);
3447 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3448 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3450 vector<space_and_path>::iterator i;
3451 uint32_t existing = 0;
3453 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3458 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3459 cnt, legalized.c_str(), ext.c_str());
3460 } else if (nchan == 2) {
3462 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3463 cnt, legalized.c_str(), ext.c_str());
3465 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3466 cnt, legalized.c_str(), ext.c_str());
3468 } else if (nchan < 26) {
3469 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3470 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3472 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3473 cnt, legalized.c_str(), ext.c_str());
3479 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3480 } else if (nchan == 2) {
3482 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3484 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3486 } else if (nchan < 26) {
3487 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3489 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3493 SessionDirectory sdir((*i).path);
3495 string spath = sdir.sound_path();
3497 /* note that we search *without* the extension so that
3498 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3499 in the event that this new name is required for
3500 a file format change.
3503 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3509 if (existing == 0) {
3514 error << string_compose(
3515 _("There are already %1 recordings for %2, which I consider too many."),
3516 limit, base) << endmsg;
3518 throw failed_constructor();
3522 return Glib::path_get_basename (buf);
3525 /** Create a new within-session audio source */
3526 boost::shared_ptr<AudioFileSource>
3527 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3529 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3530 const string path = new_source_path_from_name(DataType::AUDIO, name);
3532 return boost::dynamic_pointer_cast<AudioFileSource> (
3533 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3536 /** Return a unique name based on \a base for a new internal MIDI source */
3538 Session::new_midi_source_name (const string& base)
3541 char buf[PATH_MAX+1];
3542 const uint32_t limit = 10000;
3546 legalized = legalize_for_path (base);
3548 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3549 for (cnt = 1; cnt <= limit; ++cnt) {
3551 vector<space_and_path>::iterator i;
3552 uint32_t existing = 0;
3554 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3556 SessionDirectory sdir((*i).path);
3558 std::string p = Glib::build_filename (sdir.midi_path(), legalized);
3560 snprintf (buf, sizeof(buf), "%s-%u.mid", p.c_str(), cnt);
3562 if (Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
3567 if (existing == 0) {
3572 error << string_compose(
3573 _("There are already %1 recordings for %2, which I consider too many."),
3574 limit, base) << endmsg;
3576 throw failed_constructor();
3580 return Glib::path_get_basename(buf);
3584 /** Create a new within-session MIDI source */
3585 boost::shared_ptr<MidiSource>
3586 Session::create_midi_source_for_session (Track* track, string const & n)
3588 /* try to use the existing write source for the track, to keep numbering sane
3592 /*MidiTrack* mt = dynamic_cast<Track*> (track);
3596 list<boost::shared_ptr<Source> > l = track->steal_write_sources ();
3599 assert (boost::dynamic_pointer_cast<MidiSource> (l.front()));
3600 return boost::dynamic_pointer_cast<MidiSource> (l.front());
3604 const string name = new_midi_source_name (n);
3605 const string path = new_source_path_from_name (DataType::MIDI, name);
3607 return boost::dynamic_pointer_cast<SMFSource> (
3608 SourceFactory::createWritable (
3609 DataType::MIDI, *this, path, false, frame_rate()));
3614 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3616 if (playlist->hidden()) {
3620 playlists->add (playlist);
3623 playlist->release();
3630 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3632 if (_state_of_the_state & Deletion) {
3636 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3642 playlists->remove (playlist);
3648 Session::set_audition (boost::shared_ptr<Region> r)
3650 pending_audition_region = r;
3651 add_post_transport_work (PostTransportAudition);
3652 _butler->schedule_transport_work ();
3656 Session::audition_playlist ()
3658 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3659 ev->region.reset ();
3664 Session::non_realtime_set_audition ()
3666 assert (pending_audition_region);
3667 auditioner->audition_region (pending_audition_region);
3668 pending_audition_region.reset ();
3669 AuditionActive (true); /* EMIT SIGNAL */
3673 Session::audition_region (boost::shared_ptr<Region> r)
3675 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3681 Session::cancel_audition ()
3683 if (auditioner->auditioning()) {
3684 auditioner->cancel_audition ();
3685 AuditionActive (false); /* EMIT SIGNAL */
3690 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3692 if (a->is_monitor()) {
3695 if (b->is_monitor()) {
3698 return a->order_key (MixerSort) < b->order_key (MixerSort);
3702 Session::is_auditioning () const
3704 /* can be called before we have an auditioner object */
3706 return auditioner->auditioning();
3713 Session::graph_reordered ()
3715 /* don't do this stuff if we are setting up connections
3716 from a set_state() call or creating new tracks. Ditto for deletion.
3719 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3723 /* every track/bus asked for this to be handled but it was deferred because
3724 we were connecting. do it now.
3727 request_input_change_handling ();
3731 /* force all diskstreams to update their capture offset values to
3732 reflect any changes in latencies within the graph.
3735 boost::shared_ptr<RouteList> rl = routes.reader ();
3736 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3737 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3739 tr->set_capture_offset ();
3744 /** @return Number of frames that there is disk space available to write,
3747 boost::optional<framecnt_t>
3748 Session::available_capture_duration ()
3750 Glib::Threads::Mutex::Lock lm (space_lock);
3752 if (_total_free_4k_blocks_uncertain) {
3753 return boost::optional<framecnt_t> ();
3756 float sample_bytes_on_disk = 4.0; // keep gcc happy
3758 switch (config.get_native_file_data_format()) {
3760 sample_bytes_on_disk = 4.0;
3764 sample_bytes_on_disk = 3.0;
3768 sample_bytes_on_disk = 2.0;
3772 /* impossible, but keep some gcc versions happy */
3773 fatal << string_compose (_("programming error: %1"),
3774 X_("illegal native file data format"))
3779 double scale = 4096.0 / sample_bytes_on_disk;
3781 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3782 return max_framecnt;
3785 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3789 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3792 RCUWriter<BundleList> writer (_bundles);
3793 boost::shared_ptr<BundleList> b = writer.get_copy ();
3794 b->push_back (bundle);
3797 BundleAdded (bundle); /* EMIT SIGNAL */
3803 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3805 bool removed = false;
3808 RCUWriter<BundleList> writer (_bundles);
3809 boost::shared_ptr<BundleList> b = writer.get_copy ();
3810 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3812 if (i != b->end()) {
3819 BundleRemoved (bundle); /* EMIT SIGNAL */
3825 boost::shared_ptr<Bundle>
3826 Session::bundle_by_name (string name) const
3828 boost::shared_ptr<BundleList> b = _bundles.reader ();
3830 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3831 if ((*i)->name() == name) {
3836 return boost::shared_ptr<Bundle> ();
3840 Session::tempo_map_changed (const PropertyChange&)
3844 playlists->update_after_tempo_map_change ();
3846 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3852 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3854 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3855 (*i)->recompute_frames_from_bbt ();
3859 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3860 * the given count with the current block size.
3863 Session::ensure_buffers (ChanCount howmany)
3865 BufferManager::ensure_buffers (howmany);
3869 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3871 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3872 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3877 Session::next_insert_id ()
3879 /* this doesn't really loop forever. just think about it */
3882 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3883 if (!insert_bitset[n]) {
3884 insert_bitset[n] = true;
3890 /* none available, so resize and try again */
3892 insert_bitset.resize (insert_bitset.size() + 16, false);
3897 Session::next_send_id ()
3899 /* this doesn't really loop forever. just think about it */
3902 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3903 if (!send_bitset[n]) {
3904 send_bitset[n] = true;
3910 /* none available, so resize and try again */
3912 send_bitset.resize (send_bitset.size() + 16, false);
3917 Session::next_aux_send_id ()
3919 /* this doesn't really loop forever. just think about it */
3922 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3923 if (!aux_send_bitset[n]) {
3924 aux_send_bitset[n] = true;
3930 /* none available, so resize and try again */
3932 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3937 Session::next_return_id ()
3939 /* this doesn't really loop forever. just think about it */
3942 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3943 if (!return_bitset[n]) {
3944 return_bitset[n] = true;
3950 /* none available, so resize and try again */
3952 return_bitset.resize (return_bitset.size() + 16, false);
3957 Session::mark_send_id (uint32_t id)
3959 if (id >= send_bitset.size()) {
3960 send_bitset.resize (id+16, false);
3962 if (send_bitset[id]) {
3963 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3965 send_bitset[id] = true;
3969 Session::mark_aux_send_id (uint32_t id)
3971 if (id >= aux_send_bitset.size()) {
3972 aux_send_bitset.resize (id+16, false);
3974 if (aux_send_bitset[id]) {
3975 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
3977 aux_send_bitset[id] = true;
3981 Session::mark_return_id (uint32_t id)
3983 if (id >= return_bitset.size()) {
3984 return_bitset.resize (id+16, false);
3986 if (return_bitset[id]) {
3987 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3989 return_bitset[id] = true;
3993 Session::mark_insert_id (uint32_t id)
3995 if (id >= insert_bitset.size()) {
3996 insert_bitset.resize (id+16, false);
3998 if (insert_bitset[id]) {
3999 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4001 insert_bitset[id] = true;
4005 Session::unmark_send_id (uint32_t id)
4007 if (id < send_bitset.size()) {
4008 send_bitset[id] = false;
4013 Session::unmark_aux_send_id (uint32_t id)
4015 if (id < aux_send_bitset.size()) {
4016 aux_send_bitset[id] = false;
4021 Session::unmark_return_id (uint32_t id)
4023 if (id < return_bitset.size()) {
4024 return_bitset[id] = false;
4029 Session::unmark_insert_id (uint32_t id)
4031 if (id < insert_bitset.size()) {
4032 insert_bitset[id] = false;
4037 Session::reset_native_file_format ()
4039 boost::shared_ptr<RouteList> rl = routes.reader ();
4040 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4041 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4043 /* don't save state as we do this, there's no point
4046 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4047 tr->reset_write_sources (false);
4048 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4054 Session::route_name_unique (string n) const
4056 boost::shared_ptr<RouteList> r = routes.reader ();
4058 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4059 if ((*i)->name() == n) {
4068 Session::route_name_internal (string n) const
4070 if (auditioner && auditioner->name() == n) {
4074 if (_click_io && _click_io->name() == n) {
4082 Session::freeze_all (InterThreadInfo& itt)
4084 boost::shared_ptr<RouteList> r = routes.reader ();
4086 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4088 boost::shared_ptr<Track> t;
4090 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4091 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4101 boost::shared_ptr<Region>
4102 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4103 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4104 InterThreadInfo& itt,
4105 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4108 boost::shared_ptr<Region> result;
4109 boost::shared_ptr<Playlist> playlist;
4110 boost::shared_ptr<AudioFileSource> fsource;
4112 char buf[PATH_MAX+1];
4113 ChanCount diskstream_channels (track.n_channels());
4114 framepos_t position;
4115 framecnt_t this_chunk;
4118 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4119 const string sound_dir = sdir.sound_path();
4120 framepos_t len = end - start;
4121 bool need_block_size_reset = false;
4123 ChanCount const max_proc = track.max_processor_streams ();
4126 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4127 end, start) << endmsg;
4131 const framecnt_t chunk_size = (256 * 1024)/4;
4133 // block all process callback handling
4135 block_processing ();
4137 /* call tree *MUST* hold route_lock */
4139 if ((playlist = track.playlist()) == 0) {
4143 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4145 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4147 for (x = 0; x < 99999; ++x) {
4148 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 "%s", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1, ext.c_str());
4149 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4155 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4160 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4161 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4164 catch (failed_constructor& err) {
4165 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4169 srcs.push_back (fsource);
4172 /* tell redirects that care that we are about to use a much larger
4173 * blocksize. this will flush all plugins too, so that they are ready
4174 * to be used for this process.
4177 need_block_size_reset = true;
4178 track.set_block_size (chunk_size);
4183 /* create a set of reasonably-sized buffers */
4184 buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
4185 buffers.set_count (max_proc);
4187 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4188 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4190 afs->prepare_for_peakfile_writes ();
4193 while (to_do && !itt.cancel) {
4195 this_chunk = min (to_do, chunk_size);
4197 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4202 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4203 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4206 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4212 start += this_chunk;
4213 to_do -= this_chunk;
4215 itt.progress = (float) (1.0 - ((double) to_do / len));
4224 xnow = localtime (&now);
4226 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4227 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4230 afs->update_header (position, *xnow, now);
4231 afs->flush_header ();
4235 /* construct a region to represent the bounced material */
4239 plist.add (Properties::start, 0);
4240 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4241 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4243 result = RegionFactory::create (srcs, plist);
4249 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4250 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4253 afs->mark_for_remove ();
4256 (*src)->drop_references ();
4260 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4261 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4264 afs->done_with_peakfile_writes ();
4269 if (need_block_size_reset) {
4270 track.set_block_size (get_block_size());
4273 unblock_processing ();
4279 Session::gain_automation_buffer() const
4281 return ProcessThread::gain_automation_buffer ();
4285 Session::send_gain_automation_buffer() const
4287 return ProcessThread::send_gain_automation_buffer ();
4291 Session::pan_automation_buffer() const
4293 return ProcessThread::pan_automation_buffer ();
4297 Session::get_silent_buffers (ChanCount count)
4299 return ProcessThread::get_silent_buffers (count);
4303 Session::get_scratch_buffers (ChanCount count, bool silence)
4305 return ProcessThread::get_scratch_buffers (count, silence);
4309 Session::get_route_buffers (ChanCount count, bool silence)
4311 return ProcessThread::get_route_buffers (count, silence);
4316 Session::get_mix_buffers (ChanCount count)
4318 return ProcessThread::get_mix_buffers (count);
4322 Session::ntracks () const
4325 boost::shared_ptr<RouteList> r = routes.reader ();
4327 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4328 if (boost::dynamic_pointer_cast<Track> (*i)) {
4337 Session::nbusses () const
4340 boost::shared_ptr<RouteList> r = routes.reader ();
4342 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4343 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4352 Session::add_automation_list(AutomationList *al)
4354 automation_lists[al->id()] = al;
4357 /** @return true if there is at least one record-enabled track, otherwise false */
4359 Session::have_rec_enabled_track () const
4361 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4364 /** Update the state of our rec-enabled tracks flag */
4366 Session::update_have_rec_enabled_track ()
4368 boost::shared_ptr<RouteList> rl = routes.reader ();
4369 RouteList::iterator i = rl->begin();
4370 while (i != rl->end ()) {
4372 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4373 if (tr && tr->record_enabled ()) {
4380 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4382 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4384 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4385 RecordStateChanged (); /* EMIT SIGNAL */
4390 Session::listen_position_changed ()
4392 boost::shared_ptr<RouteList> r = routes.reader ();
4394 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4395 (*i)->listen_position_changed ();
4400 Session::solo_control_mode_changed ()
4402 /* cancel all solo or all listen when solo control mode changes */
4405 set_solo (get_routes(), false);
4406 } else if (listening()) {
4407 set_listen (get_routes(), false);
4411 /** Called when a property of one of our route groups changes */
4413 Session::route_group_property_changed (RouteGroup* rg)
4415 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4418 /** Called when a route is added to one of our route groups */
4420 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4422 RouteAddedToRouteGroup (rg, r);
4425 /** Called when a route is removed from one of our route groups */
4427 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4429 RouteRemovedFromRouteGroup (rg, r);
4432 boost::shared_ptr<RouteList>
4433 Session::get_routes_with_regions_at (framepos_t const p) const
4435 boost::shared_ptr<RouteList> r = routes.reader ();
4436 boost::shared_ptr<RouteList> rl (new RouteList);
4438 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4439 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4444 boost::shared_ptr<Playlist> pl = tr->playlist ();
4449 if (pl->has_region_at (p)) {
4458 Session::goto_end ()
4460 if (_session_range_location) {
4461 request_locate (_session_range_location->end(), false);
4463 request_locate (0, false);
4468 Session::goto_start ()
4470 if (_session_range_location) {
4471 request_locate (_session_range_location->start(), false);
4473 request_locate (0, false);
4478 Session::current_start_frame () const
4480 return _session_range_location ? _session_range_location->start() : 0;
4484 Session::current_end_frame () const
4486 return _session_range_location ? _session_range_location->end() : 0;
4490 Session::add_session_range_location (framepos_t start, framepos_t end)
4492 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4493 _locations->add (_session_range_location);
4497 Session::step_edit_status_change (bool yn)
4503 send = (_step_editors == 0);
4508 send = (_step_editors == 1);
4511 if (_step_editors > 0) {
4517 StepEditStatusChange (val);
4523 Session::start_time_changed (framepos_t old)
4525 /* Update the auto loop range to match the session range
4526 (unless the auto loop range has been changed by the user)
4529 Location* s = _locations->session_range_location ();
4534 Location* l = _locations->auto_loop_location ();
4536 if (l && l->start() == old) {
4537 l->set_start (s->start(), true);
4542 Session::end_time_changed (framepos_t old)
4544 /* Update the auto loop range to match the session range
4545 (unless the auto loop range has been changed by the user)
4548 Location* s = _locations->session_range_location ();
4553 Location* l = _locations->auto_loop_location ();
4555 if (l && l->end() == old) {
4556 l->set_end (s->end(), true);
4560 std::vector<std::string>
4561 Session::source_search_path (DataType type) const
4565 if (session_dirs.size() == 1) {
4567 case DataType::AUDIO:
4568 sp.push_back (_session_dir->sound_path());
4570 case DataType::MIDI:
4571 sp.push_back (_session_dir->midi_path());
4575 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4576 SessionDirectory sdir (i->path);
4578 case DataType::AUDIO:
4579 sp.push_back (sdir.sound_path());
4581 case DataType::MIDI:
4582 sp.push_back (sdir.midi_path());
4588 if (type == DataType::AUDIO) {
4589 const string sound_path_2X = _session_dir->sound_path_2X();
4590 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4591 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
4592 sp.push_back (sound_path_2X);
4597 // now check the explicit (possibly user-specified) search path
4600 case DataType::AUDIO:
4601 sp += Searchpath(config.get_audio_search_path ());
4603 case DataType::MIDI:
4604 sp += Searchpath(config.get_midi_search_path ());
4612 Session::ensure_search_path_includes (const string& path, DataType type)
4621 case DataType::AUDIO:
4622 sp += Searchpath(config.get_audio_search_path ());
4624 case DataType::MIDI:
4625 sp += Searchpath (config.get_midi_search_path ());
4629 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
4630 /* No need to add this new directory if it has the same inode as
4631 an existing one; checking inode rather than name prevents duplicated
4632 directories when we are using symlinks.
4634 On Windows, I think we could just do if (*i == path) here.
4636 if (PBD::equivalent_paths (*i, path)) {
4644 case DataType::AUDIO:
4645 config.set_audio_search_path (sp.to_string());
4647 case DataType::MIDI:
4648 config.set_midi_search_path (sp.to_string());
4653 boost::shared_ptr<Speakers>
4654 Session::get_speakers()
4660 Session::unknown_processors () const
4664 boost::shared_ptr<RouteList> r = routes.reader ();
4665 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4666 list<string> t = (*i)->unknown_processors ();
4667 copy (t.begin(), t.end(), back_inserter (p));
4677 Session::update_latency (bool playback)
4679 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4681 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4685 boost::shared_ptr<RouteList> r = routes.reader ();
4686 framecnt_t max_latency = 0;
4689 /* reverse the list so that we work backwards from the last route to run to the first */
4690 RouteList* rl = routes.reader().get();
4691 r.reset (new RouteList (*rl));
4692 reverse (r->begin(), r->end());
4695 /* compute actual latency values for the given direction and store them all in per-port
4696 structures. this will also publish the same values (to JACK) so that computation of latency
4697 for routes can consistently use public latency values.
4700 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4701 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4704 /* because we latency compensate playback, our published playback latencies should
4705 be the same for all output ports - all material played back by ardour has
4706 the same latency, whether its caused by plugins or by latency compensation. since
4707 these may differ from the values computed above, reset all playback port latencies
4711 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4713 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4714 (*i)->set_public_port_latencies (max_latency, playback);
4719 post_playback_latency ();
4723 post_capture_latency ();
4726 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4730 Session::post_playback_latency ()
4732 set_worst_playback_latency ();
4734 boost::shared_ptr<RouteList> r = routes.reader ();
4736 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4737 if (!(*i)->is_auditioner() && ((*i)->active())) {
4738 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4742 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4743 (*i)->set_latency_compensation (_worst_track_latency);
4748 Session::post_capture_latency ()
4750 set_worst_capture_latency ();
4752 /* reflect any changes in capture latencies into capture offsets
4755 boost::shared_ptr<RouteList> rl = routes.reader();
4756 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4757 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4759 tr->set_capture_offset ();
4765 Session::initialize_latencies ()
4768 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4769 update_latency (false);
4770 update_latency (true);
4773 set_worst_io_latencies ();
4777 Session::set_worst_io_latencies ()
4779 set_worst_playback_latency ();
4780 set_worst_capture_latency ();
4784 Session::set_worst_playback_latency ()
4786 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4790 _worst_output_latency = 0;
4792 if (!_engine.connected()) {
4796 boost::shared_ptr<RouteList> r = routes.reader ();
4798 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4799 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4802 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4806 Session::set_worst_capture_latency ()
4808 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4812 _worst_input_latency = 0;
4814 if (!_engine.connected()) {
4818 boost::shared_ptr<RouteList> r = routes.reader ();
4820 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4821 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4824 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4828 Session::update_latency_compensation (bool force_whole_graph)
4830 bool some_track_latency_changed = false;
4832 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4836 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4838 _worst_track_latency = 0;
4840 boost::shared_ptr<RouteList> r = routes.reader ();
4842 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4843 if (!(*i)->is_auditioner() && ((*i)->active())) {
4845 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4846 some_track_latency_changed = true;
4848 _worst_track_latency = max (tl, _worst_track_latency);
4852 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4853 (some_track_latency_changed ? "yes" : "no")));
4855 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4857 if (some_track_latency_changed || force_whole_graph) {
4858 _engine.update_latencies ();
4862 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4863 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4867 tr->set_capture_offset ();
4872 Session::session_name_is_legal (const string& path)
4874 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4876 for (int i = 0; illegal_chars[i]; ++i) {
4877 if (path.find (illegal_chars[i]) != string::npos) {
4878 return illegal_chars[i];
4886 Session::next_control_id () const
4890 /* the monitor bus remote ID is in a different
4891 * "namespace" than regular routes. its existence doesn't
4892 * affect normal (low) numbered routes.
4899 return nroutes() - subtract;
4903 Session::notify_remote_id_change ()
4905 if (deletion_in_progress()) {
4909 switch (Config->get_remote_model()) {
4912 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4920 Session::sync_order_keys (RouteSortOrderKey sort_key_changed)
4922 if (deletion_in_progress()) {
4926 /* tell everyone that something has happened to the sort keys
4927 and let them sync up with the change(s)
4928 this will give objects that manage the sort order keys the
4929 opportunity to keep them in sync if they wish to.
4932 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("Sync Order Keys, based on %1\n", enum_2_string (sort_key_changed)));
4934 Route::SyncOrderKeys (sort_key_changed); /* EMIT SIGNAL */
4936 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
4940 Session::operation_in_progress (GQuark op) const
4942 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
4945 boost::shared_ptr<Port>
4946 Session::ltc_input_port () const
4948 return _ltc_input->nth (0);
4951 boost::shared_ptr<Port>
4952 Session::ltc_output_port () const
4954 return _ltc_output->nth (0);
4958 Session::reconnect_ltc_input ()
4962 string src = Config->get_ltc_source_port();
4964 _ltc_input->disconnect (this);
4966 if (src != _("None") && !src.empty()) {
4967 _ltc_input->nth (0)->connect (src);
4973 Session::reconnect_ltc_output ()
4978 string src = Config->get_ltc_sink_port();
4980 _ltc_output->disconnect (this);
4982 if (src != _("None") && !src.empty()) {
4983 _ltc_output->nth (0)->connect (src);