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/strsplit.h"
48 #include "pbd/unwind.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/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 (ensure_engine (sr)) {
269 throw failed_constructor ();
272 if (create (mix_template, bus_profile)) {
274 throw failed_constructor ();
279 if (load_state (_current_snapshot_name)) {
280 throw failed_constructor ();
283 /* try to get sample rate from XML state so that we
284 * can influence the SR if we set up the audio
289 const XMLProperty* prop;
290 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
291 sr = atoi (prop->value());
295 if (ensure_engine (sr)) {
297 throw failed_constructor ();
301 if (post_engine_init ()) {
303 throw failed_constructor ();
306 store_recent_sessions (_name, _path);
308 bool was_dirty = dirty();
310 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
312 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
313 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
316 DirtyChanged (); /* EMIT SIGNAL */
319 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
320 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
324 /* hook us up to the engine since we are now completely constructed */
326 BootMessage (_("Connect to engine"));
328 _engine.set_session (this);
329 _engine.reset_timebase ();
331 BootMessage (_("Session loading complete"));
344 Session::ensure_engine (uint32_t desired_sample_rate)
346 if (_engine.current_backend() == 0) {
347 /* backend is unknown ... */
348 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
349 if (r.get_value_or (-1) != 0) {
352 } else if (_engine.setup_required()) {
353 /* backend is known, but setup is needed */
354 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
355 if (r.get_value_or (-1) != 0) {
358 } else if (!_engine.running()) {
359 if (_engine.start()) {
364 /* at this point the engine should be running
367 if (!_engine.running()) {
371 /* the graph is just about as basic to everything else as the engine
372 so we create it here. this results in it coming into being at just
373 the right time for both new and existing sessions.
375 XXX some cleanup in the new/existing path is still waiting to be
379 if (how_many_dsp_threads () > 1) {
380 /* For now, only create the graph if we are using >1 DSP threads, as
381 it is a bit slower than the old code with 1 thread.
383 _process_graph.reset (new Graph (*this));
392 vector<void*> debug_pointers;
394 /* if we got to here, leaving pending capture state around
398 remove_pending_capture_state ();
400 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
402 /* disconnect from any and all signals that we are connected to */
406 _engine.remove_session ();
408 /* deregister all ports - there will be no process or any other
409 * callbacks from the engine any more.
412 Port::PortDrop (); /* EMIT SIGNAL */
416 /* clear history so that no references to objects are held any more */
420 /* clear state tree so that no references to objects are held any more */
424 /* reset dynamic state version back to default */
426 Stateful::loading_state_version = 0;
428 _butler->drop_references ();
432 delete midi_control_ui;
433 delete _all_route_group;
435 if (click_data != default_click) {
436 delete [] click_data;
439 if (click_emphasis_data != default_click_emphasis) {
440 delete [] click_emphasis_data;
445 /* clear out any pending dead wood from RCU managed objects */
450 AudioDiskstream::free_working_buffers();
452 /* tell everyone who is still standing that we're about to die */
455 /* tell everyone to drop references and delete objects as we go */
457 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
458 RegionFactory::delete_all_regions ();
460 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
462 /* reset these three references to special routes before we do the usual route delete thing */
465 _master_out.reset ();
466 _monitor_out.reset ();
469 RCUWriter<RouteList> writer (routes);
470 boost::shared_ptr<RouteList> r = writer.get_copy ();
472 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
473 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
474 (*i)->drop_references ();
478 /* writer goes out of scope and updates master */
482 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
483 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
484 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
485 i->second->drop_references ();
490 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
491 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
496 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
503 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
505 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
506 boost_debug_list_ptrs ();
511 Session::setup_ltc ()
515 _ltc_input.reset (new IO (*this, _("LTC In"), IO::Input));
516 _ltc_output.reset (new IO (*this, _("LTC Out"), IO::Output));
518 if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-In")) != 0) {
519 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
522 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
523 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
525 reconnect_ltc_input ();
528 if (state_tree && (child = find_named_node (*state_tree->root(), "LTC-Out")) != 0) {
529 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
532 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
533 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
535 reconnect_ltc_output ();
538 /* fix up names of LTC ports because we don't want the normal
539 * IO style of NAME/TYPE-{in,out}N
542 _ltc_input->nth (0)->set_name (_("LTC-in"));
543 _ltc_output->nth (0)->set_name (_("LTC-out"));
547 Session::setup_click ()
552 _click_io.reset (new ClickIO (*this, "click"));
553 _click_gain.reset (new Amp (*this));
554 _click_gain->activate ();
556 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
558 /* existing state for Click */
561 if (Stateful::loading_state_version < 3000) {
562 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
564 const XMLNodeList& children (child->children());
565 XMLNodeList::const_iterator i = children.begin();
566 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
568 if (i != children.end()) {
569 c = _click_gain->set_state (**i, Stateful::loading_state_version);
575 _clicking = Config->get_clicking ();
579 error << _("could not setup Click I/O") << endmsg;
586 /* default state for Click: dual-mono to first 2 physical outputs */
589 _engine.get_physical_outputs (DataType::AUDIO, outs);
591 for (uint32_t physport = 0; physport < 2; ++physport) {
592 if (outs.size() > physport) {
593 if (_click_io->add_port (outs[physport], this)) {
594 // relax, even though its an error
599 if (_click_io->n_ports () > ChanCount::ZERO) {
600 _clicking = Config->get_clicking ();
606 Session::setup_bundles ()
608 vector<string> inputs[DataType::num_types];
609 vector<string> outputs[DataType::num_types];
610 for (uint32_t i = 0; i < DataType::num_types; ++i) {
611 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
612 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
615 /* Create a set of Bundle objects that map
616 to the physical I/O currently available. We create both
617 mono and stereo bundles, so that the common cases of mono
618 and stereo tracks get bundles to put in their mixer strip
619 in / out menus. There may be a nicer way of achieving that;
620 it doesn't really scale that well to higher channel counts
623 /* mono output bundles */
625 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
627 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
629 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
630 c->add_channel (_("mono"), DataType::AUDIO);
631 c->set_port (0, outputs[DataType::AUDIO][np]);
636 /* stereo output bundles */
638 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
639 if (np + 1 < outputs[DataType::AUDIO].size()) {
641 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
642 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
643 c->add_channel (_("L"), DataType::AUDIO);
644 c->set_port (0, outputs[DataType::AUDIO][np]);
645 c->add_channel (_("R"), DataType::AUDIO);
646 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
652 /* mono input bundles */
654 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
656 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
658 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
659 c->add_channel (_("mono"), DataType::AUDIO);
660 c->set_port (0, inputs[DataType::AUDIO][np]);
665 /* stereo input bundles */
667 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
668 if (np + 1 < inputs[DataType::AUDIO].size()) {
670 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
672 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
673 c->add_channel (_("L"), DataType::AUDIO);
674 c->set_port (0, inputs[DataType::AUDIO][np]);
675 c->add_channel (_("R"), DataType::AUDIO);
676 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
682 /* MIDI input bundles */
684 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
685 string n = inputs[DataType::MIDI][np];
686 boost::erase_first (n, X_("alsa_pcm:"));
688 boost::shared_ptr<Bundle> c (new Bundle (n, false));
689 c->add_channel ("", DataType::MIDI);
690 c->set_port (0, inputs[DataType::MIDI][np]);
694 /* MIDI output bundles */
696 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
697 string n = outputs[DataType::MIDI][np];
698 boost::erase_first (n, X_("alsa_pcm:"));
700 boost::shared_ptr<Bundle> c (new Bundle (n, true));
701 c->add_channel ("", DataType::MIDI);
702 c->set_port (0, outputs[DataType::MIDI][np]);
709 Session::when_engine_running ()
711 /* every time we reconnect, recompute worst case output latencies */
713 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
715 if (synced_to_jack()) {
716 _engine.transport_stop ();
719 if (config.get_jack_time_master()) {
720 _engine.transport_locate (_transport_frame);
725 BootMessage (_("Set up LTC"));
727 BootMessage (_("Set up Click"));
729 BootMessage (_("Set up standard connections"));
733 catch (failed_constructor& err) {
737 BootMessage (_("Setup signal flow and plugins"));
739 /* Reset all panners */
741 Delivery::reset_panners ();
743 /* this will cause the CPM to instantiate any protocols that are in use
744 * (or mandatory), which will pass it this Session, and then call
745 * set_state() on each instantiated protocol to match stored state.
748 ControlProtocolManager::instance().set_session (this);
750 /* This must be done after the ControlProtocolManager set_session above,
751 as it will set states for ports which the ControlProtocolManager creates.
754 // XXX set state of MIDI::Port's
755 // MidiPortManager::instance()->set_port_states (Config->midi_port_states ());
757 /* And this must be done after the MIDI::Manager::set_port_states as
758 * it will try to make connections whose details are loaded by set_port_states.
763 /* Let control protocols know that we are now all connected, so they
764 * could start talking to surfaces if they want to.
767 ControlProtocolManager::instance().midi_connectivity_established ();
769 if (_is_new && !no_auto_connect()) {
770 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock());
771 auto_connect_master_bus ();
774 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
776 /* update latencies */
778 initialize_latencies ();
784 Session::auto_connect_master_bus ()
786 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
790 /* if requested auto-connect the outputs to the first N physical ports.
793 uint32_t limit = _master_out->n_outputs().n_total();
794 vector<string> outputs[DataType::num_types];
796 for (uint32_t i = 0; i < DataType::num_types; ++i) {
797 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
800 for (uint32_t n = 0; n < limit; ++n) {
801 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
803 if (outputs[p->type()].size() > n) {
804 connect_to = outputs[p->type()][n];
807 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
808 if (_master_out->output()->connect (p, connect_to, this)) {
809 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
818 Session::remove_monitor_section ()
824 /* force reversion to Solo-In-Place */
825 Config->set_solo_control_is_listen_control (false);
828 /* Hold process lock while doing this so that we don't hear bits and
829 * pieces of audio as we work on each route.
832 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
834 /* Connect tracks to monitor section. Note that in an
835 existing session, the internal sends will already exist, but we want the
836 routes to notice that they connect to the control out specifically.
840 boost::shared_ptr<RouteList> r = routes.reader ();
841 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
843 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
845 if ((*x)->is_monitor()) {
847 } else if ((*x)->is_master()) {
850 (*x)->remove_aux_or_listen (_monitor_out);
855 remove_route (_monitor_out);
856 auto_connect_master_bus ();
860 Session::add_monitor_section ()
864 if (_monitor_out || !_master_out) {
868 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
874 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
875 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
878 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
879 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
880 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
884 add_routes (rl, false, false, false);
886 assert (_monitor_out);
888 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
889 are undefined, at best.
892 uint32_t limit = _monitor_out->n_inputs().n_audio();
896 /* connect the inputs to the master bus outputs. this
897 * represents a separate data feed from the internal sends from
898 * each route. as of jan 2011, it allows the monitor section to
899 * conditionally ignore either the internal sends or the normal
900 * input feed, but we should really find a better way to do
904 _master_out->output()->disconnect (this);
906 for (uint32_t n = 0; n < limit; ++n) {
907 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
908 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
911 string connect_to = o->name();
912 if (_monitor_out->input()->connect (p, connect_to, this)) {
913 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
921 /* if monitor section is not connected, connect it to physical outs
924 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
926 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
928 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
931 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
933 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
934 Config->get_monitor_bus_preferred_bundle())
940 /* Monitor bus is audio only */
942 uint32_t mod = n_physical_outputs.get (DataType::AUDIO);
943 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
944 vector<string> outputs[DataType::num_types];
946 for (uint32_t i = 0; i < DataType::num_types; ++i) {
947 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
953 for (uint32_t n = 0; n < limit; ++n) {
955 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
957 if (outputs[DataType::AUDIO].size() > (n % mod)) {
958 connect_to = outputs[DataType::AUDIO][n % mod];
961 if (!connect_to.empty()) {
962 if (_monitor_out->output()->connect (p, connect_to, this)) {
963 error << string_compose (
964 _("cannot connect control output %1 to %2"),
975 /* Hold process lock while doing this so that we don't hear bits and
976 * pieces of audio as we work on each route.
979 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
981 /* Connect tracks to monitor section. Note that in an
982 existing session, the internal sends will already exist, but we want the
983 routes to notice that they connect to the control out specifically.
987 boost::shared_ptr<RouteList> rls = routes.reader ();
989 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
991 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
993 if ((*x)->is_monitor()) {
995 } else if ((*x)->is_master()) {
998 (*x)->enable_monitor_send ();
1004 Session::hookup_io ()
1006 /* stop graph reordering notifications from
1007 causing resorts, etc.
1010 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1014 /* we delay creating the auditioner till now because
1015 it makes its own connections to ports.
1019 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1021 throw failed_constructor ();
1023 a->use_new_diskstream ();
1027 catch (failed_constructor& err) {
1028 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1032 /* load bundles, which we may have postponed earlier on */
1033 if (_bundle_xml_node) {
1034 load_bundles (*_bundle_xml_node);
1035 delete _bundle_xml_node;
1038 /* Tell all IO objects to connect themselves together */
1040 IO::enable_connecting ();
1042 /* Now tell all "floating" ports to connect to whatever
1043 they should be connected to.
1046 AudioEngine::instance()->reconnect_ports ();
1048 /* Anyone who cares about input state, wake up and do something */
1050 IOConnectionsComplete (); /* EMIT SIGNAL */
1052 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1054 /* now handle the whole enchilada as if it was one
1055 graph reorder event.
1060 /* update the full solo state, which can't be
1061 correctly determined on a per-route basis, but
1062 needs the global overview that only the session
1066 update_route_solo_state ();
1070 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1072 boost::shared_ptr<Track> track = wp.lock ();
1077 boost::shared_ptr<Playlist> playlist;
1079 if ((playlist = track->playlist()) != 0) {
1080 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1081 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1082 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1087 Session::record_enabling_legal () const
1089 /* this used to be in here, but survey says.... we don't need to restrict it */
1090 // if (record_status() == Recording) {
1094 if (Config->get_all_safe()) {
1101 Session::set_track_monitor_input_status (bool yn)
1103 boost::shared_ptr<RouteList> rl = routes.reader ();
1104 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1105 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1106 if (tr && tr->record_enabled ()) {
1107 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1108 tr->request_input_monitoring (yn);
1114 Session::auto_punch_start_changed (Location* location)
1116 replace_event (SessionEvent::PunchIn, location->start());
1118 if (get_record_enabled() && config.get_punch_in()) {
1119 /* capture start has been changed, so save new pending state */
1120 save_state ("", true);
1125 Session::auto_punch_end_changed (Location* location)
1127 framepos_t when_to_stop = location->end();
1128 // when_to_stop += _worst_output_latency + _worst_input_latency;
1129 replace_event (SessionEvent::PunchOut, when_to_stop);
1133 Session::auto_punch_changed (Location* location)
1135 framepos_t when_to_stop = location->end();
1137 replace_event (SessionEvent::PunchIn, location->start());
1138 //when_to_stop += _worst_output_latency + _worst_input_latency;
1139 replace_event (SessionEvent::PunchOut, when_to_stop);
1142 /** @param loc A loop location.
1143 * @param pos Filled in with the start time of the required fade-out (in session frames).
1144 * @param length Filled in with the length of the required fade-out.
1147 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1149 pos = max (loc->start(), loc->end() - 64);
1150 length = loc->end() - pos;
1154 Session::auto_loop_changed (Location* location)
1156 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1159 auto_loop_declick_range (location, dcp, dcl);
1160 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1162 if (transport_rolling() && play_loop) {
1165 // if (_transport_frame > location->end()) {
1167 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1168 // relocate to beginning of loop
1169 clear_events (SessionEvent::LocateRoll);
1171 request_locate (location->start(), true);
1174 else if (Config->get_seamless_loop() && !loop_changing) {
1176 // schedule a locate-roll to refill the diskstreams at the
1177 // previous loop end
1178 loop_changing = true;
1180 if (location->end() > last_loopend) {
1181 clear_events (SessionEvent::LocateRoll);
1182 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1189 last_loopend = location->end();
1193 Session::set_auto_punch_location (Location* location)
1197 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1198 punch_connections.drop_connections();
1199 existing->set_auto_punch (false, this);
1200 remove_event (existing->start(), SessionEvent::PunchIn);
1201 clear_events (SessionEvent::PunchOut);
1202 auto_punch_location_changed (0);
1207 if (location == 0) {
1211 if (location->end() <= location->start()) {
1212 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1216 punch_connections.drop_connections ();
1218 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1219 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1220 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1222 location->set_auto_punch (true, this);
1224 auto_punch_changed (location);
1226 auto_punch_location_changed (location);
1230 Session::set_auto_loop_location (Location* location)
1234 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1235 loop_connections.drop_connections ();
1236 existing->set_auto_loop (false, this);
1237 remove_event (existing->end(), SessionEvent::AutoLoop);
1240 auto_loop_declick_range (existing, dcp, dcl);
1241 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1242 auto_loop_location_changed (0);
1247 if (location == 0) {
1251 if (location->end() <= location->start()) {
1252 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1256 last_loopend = location->end();
1258 loop_connections.drop_connections ();
1260 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1261 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1262 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1264 location->set_auto_loop (true, this);
1266 /* take care of our stuff first */
1268 auto_loop_changed (location);
1270 /* now tell everyone else */
1272 auto_loop_location_changed (location);
1276 Session::locations_added (Location *)
1282 Session::locations_changed ()
1284 _locations->apply (*this, &Session::handle_locations_changed);
1288 Session::handle_locations_changed (Locations::LocationList& locations)
1290 Locations::LocationList::iterator i;
1292 bool set_loop = false;
1293 bool set_punch = false;
1295 for (i = locations.begin(); i != locations.end(); ++i) {
1299 if (location->is_auto_punch()) {
1300 set_auto_punch_location (location);
1303 if (location->is_auto_loop()) {
1304 set_auto_loop_location (location);
1308 if (location->is_session_range()) {
1309 _session_range_location = location;
1314 set_auto_loop_location (0);
1317 set_auto_punch_location (0);
1324 Session::enable_record ()
1326 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1327 /* no recording at anything except normal speed */
1332 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1334 if (rs == Recording) {
1338 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1340 _last_record_location = _transport_frame;
1341 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1343 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1344 set_track_monitor_input_status (true);
1347 RecordStateChanged ();
1354 Session::disable_record (bool rt_context, bool force)
1358 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1360 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1361 g_atomic_int_set (&_record_status, Disabled);
1362 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1364 if (rs == Recording) {
1365 g_atomic_int_set (&_record_status, Enabled);
1369 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1370 set_track_monitor_input_status (false);
1373 RecordStateChanged (); /* emit signal */
1376 remove_pending_capture_state ();
1382 Session::step_back_from_record ()
1384 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1386 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1387 set_track_monitor_input_status (false);
1390 RecordStateChanged (); /* emit signal */
1395 Session::maybe_enable_record ()
1397 if (_step_editors > 0) {
1401 g_atomic_int_set (&_record_status, Enabled);
1403 /* This function is currently called from somewhere other than an RT thread.
1404 This save_state() call therefore doesn't impact anything. Doing it here
1405 means that we save pending state of which sources the next record will use,
1406 which gives us some chance of recovering from a crash during the record.
1409 save_state ("", true);
1411 if (_transport_speed) {
1412 if (!config.get_punch_in()) {
1416 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1417 RecordStateChanged (); /* EMIT SIGNAL */
1424 Session::audible_frame () const
1430 /* the first of these two possible settings for "offset"
1431 mean that the audible frame is stationary until
1432 audio emerges from the latency compensation
1435 the second means that the audible frame is stationary
1436 until audio would emerge from a physical port
1437 in the absence of any plugin latency compensation
1440 offset = worst_playback_latency ();
1442 if (offset > current_block_size) {
1443 offset -= current_block_size;
1445 /* XXX is this correct? if we have no external
1446 physical connections and everything is internal
1447 then surely this is zero? still, how
1448 likely is that anyway?
1450 offset = current_block_size;
1453 if (synced_to_jack()) {
1454 tf = _engine.transport_frame();
1456 tf = _transport_frame;
1461 if (!non_realtime_work_pending()) {
1465 /* Check to see if we have passed the first guaranteed
1466 audible frame past our last start position. if not,
1467 return that last start point because in terms
1468 of audible frames, we have not moved yet.
1470 `Start position' in this context means the time we last
1471 either started, located, or changed transport direction.
1474 if (_transport_speed > 0.0f) {
1476 if (!play_loop || !have_looped) {
1477 if (tf < _last_roll_or_reversal_location + offset) {
1478 return _last_roll_or_reversal_location;
1486 } else if (_transport_speed < 0.0f) {
1488 /* XXX wot? no backward looping? */
1490 if (tf > _last_roll_or_reversal_location - offset) {
1491 return _last_roll_or_reversal_location;
1503 Session::set_frame_rate (framecnt_t frames_per_second)
1505 /** \fn void Session::set_frame_size(framecnt_t)
1506 the AudioEngine object that calls this guarantees
1507 that it will not be called while we are also in
1508 ::process(). Its fine to do things that block
1512 _base_frame_rate = frames_per_second;
1513 _nominal_frame_rate = frames_per_second;
1519 // XXX we need some equivalent to this, somehow
1520 // SndFileSource::setup_standard_crossfades (frames_per_second);
1524 /* XXX need to reset/reinstantiate all LADSPA plugins */
1528 Session::set_block_size (pframes_t nframes)
1530 /* the AudioEngine guarantees
1531 that it will not be called while we are also in
1532 ::process(). It is therefore fine to do things that block
1537 current_block_size = nframes;
1541 boost::shared_ptr<RouteList> r = routes.reader ();
1543 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1544 (*i)->set_block_size (nframes);
1547 boost::shared_ptr<RouteList> rl = routes.reader ();
1548 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1549 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1551 tr->set_block_size (nframes);
1555 set_worst_io_latencies ();
1561 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1563 boost::shared_ptr<Route> r2;
1565 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1566 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1570 /* make a copy of the existing list of routes that feed r1 */
1572 Route::FedBy existing (r1->fed_by());
1574 /* for each route that feeds r1, recurse, marking it as feeding
1578 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1579 if (!(r2 = i->r.lock ())) {
1580 /* (*i) went away, ignore it */
1584 /* r2 is a route that feeds r1 which somehow feeds base. mark
1585 base as being fed by r2
1588 rbase->add_fed_by (r2, i->sends_only);
1592 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1596 if (r1->feeds (r2) && r2->feeds (r1)) {
1600 /* now recurse, so that we can mark base as being fed by
1601 all routes that feed r2
1604 trace_terminal (r2, rbase);
1611 Session::resort_routes ()
1613 /* don't do anything here with signals emitted
1614 by Routes during initial setup or while we
1615 are being destroyed.
1618 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1623 RCUWriter<RouteList> writer (routes);
1624 boost::shared_ptr<RouteList> r = writer.get_copy ();
1625 resort_routes_using (r);
1626 /* writer goes out of scope and forces update */
1630 boost::shared_ptr<RouteList> rl = routes.reader ();
1631 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1632 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1634 const Route::FedBy& fb ((*i)->fed_by());
1636 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1637 boost::shared_ptr<Route> sf = f->r.lock();
1639 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1647 /** This is called whenever we need to rebuild the graph of how we will process
1649 * @param r List of routes, in any order.
1653 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1655 /* We are going to build a directed graph of our routes;
1656 this is where the edges of that graph are put.
1661 /* Go through all routes doing two things:
1663 * 1. Collect the edges of the route graph. Each of these edges
1664 * is a pair of routes, one of which directly feeds the other
1665 * either by a JACK connection or by an internal send.
1667 * 2. Begin the process of making routes aware of which other
1668 * routes directly or indirectly feed them. This information
1669 * is used by the solo code.
1672 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1674 /* Clear out the route's list of direct or indirect feeds */
1675 (*i)->clear_fed_by ();
1677 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1679 bool via_sends_only;
1681 /* See if this *j feeds *i according to the current state of the JACK
1682 connections and internal sends.
1684 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1685 /* add the edge to the graph (part #1) */
1686 edges.add (*j, *i, via_sends_only);
1687 /* tell the route (for part #2) */
1688 (*i)->add_fed_by (*j, via_sends_only);
1693 /* Attempt a topological sort of the route graph */
1694 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1696 if (sorted_routes) {
1697 /* We got a satisfactory topological sort, so there is no feedback;
1700 Note: the process graph rechain does not require a
1701 topologically-sorted list, but hey ho.
1703 if (_process_graph) {
1704 _process_graph->rechain (sorted_routes, edges);
1707 _current_route_graph = edges;
1709 /* Complete the building of the routes' lists of what directly
1710 or indirectly feeds them.
1712 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1713 trace_terminal (*i, *i);
1716 *r = *sorted_routes;
1719 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1721 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1722 (*i)->name(), (*i)->order_key (MixerSort)));
1726 SuccessfulGraphSort (); /* EMIT SIGNAL */
1729 /* The topological sort failed, so we have a problem. Tell everyone
1730 and stick to the old graph; this will continue to be processed, so
1731 until the feedback is fixed, what is played back will not quite
1732 reflect what is actually connected. Note also that we do not
1733 do trace_terminal here, as it would fail due to an endless recursion,
1734 so the solo code will think that everything is still connected
1738 FeedbackDetected (); /* EMIT SIGNAL */
1743 /** Find a route name starting with \a base, maybe followed by the
1744 * lowest \a id. \a id will always be added if \a definitely_add_number
1745 * is true on entry; otherwise it will only be added if required
1746 * to make the name unique.
1748 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1749 * The available route name with the lowest ID will be used, and \a id
1750 * will be set to the ID.
1752 * \return false if a route name could not be found, and \a track_name
1753 * and \a id do not reflect a free route name.
1756 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1758 if (!definitely_add_number && route_by_name (base) == 0) {
1759 /* juse use the base */
1760 snprintf (name, name_len, "%s", base.c_str());
1765 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1767 if (route_by_name (name) == 0) {
1773 } while (id < (UINT_MAX-1));
1778 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1780 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1782 in = ChanCount::ZERO;
1783 out = ChanCount::ZERO;
1785 boost::shared_ptr<RouteList> r = routes.reader ();
1787 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1788 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1789 if (tr && !tr->is_auditioner()) {
1790 in += tr->n_inputs();
1791 out += tr->n_outputs();
1796 /** Caller must not hold process lock
1797 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1798 * @param instrument plugin info for the instrument to insert pre-fader, if any
1800 list<boost::shared_ptr<MidiTrack> >
1801 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1802 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1804 char track_name[32];
1805 uint32_t track_id = 0;
1807 RouteList new_routes;
1808 list<boost::shared_ptr<MidiTrack> > ret;
1810 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1813 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1814 error << "cannot find name for new midi track" << endmsg;
1818 boost::shared_ptr<MidiTrack> track;
1821 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1823 if (track->init ()) {
1827 track->use_new_diskstream();
1829 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1830 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1833 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1834 if (track->input()->ensure_io (input, false, this)) {
1835 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1839 if (track->output()->ensure_io (output, false, this)) {
1840 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1845 track->non_realtime_input_change();
1848 route_group->add (track);
1851 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1853 if (Config->get_remote_model() == UserOrdered) {
1854 track->set_remote_control_id (next_control_id());
1857 new_routes.push_back (track);
1858 ret.push_back (track);
1861 catch (failed_constructor &err) {
1862 error << _("Session: could not create new midi track.") << endmsg;
1866 catch (AudioEngine::PortRegistrationFailure& pfe) {
1868 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;
1876 if (!new_routes.empty()) {
1877 add_routes (new_routes, true, true, true);
1880 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1881 PluginPtr plugin = instrument->load (*this);
1882 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1883 (*r)->add_processor (p, PreFader);
1893 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1895 boost::shared_ptr<Route> midi_track (wmt.lock());
1901 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1903 if (change.after.n_audio() <= change.before.n_audio()) {
1907 /* new audio ports: make sure the audio goes somewhere useful,
1908 unless the user has no-auto-connect selected.
1910 The existing ChanCounts don't matter for this call as they are only
1911 to do with matching input and output indices, and we are only changing
1917 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1921 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1922 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1923 * @param output_start As \a input_start, but for outputs.
1926 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1927 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1929 if (!IO::connecting_legal) {
1933 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1939 /* If both inputs and outputs are auto-connected to physical ports,
1940 use the max of input and output offsets to ensure auto-connected
1941 port numbers always match up (e.g. the first audio input and the
1942 first audio output of the route will have the same physical
1943 port number). Otherwise just use the lowest input or output
1947 DEBUG_TRACE (DEBUG::Graph,
1948 string_compose("Auto-connect: existing in = %1 out = %2\n",
1949 existing_inputs, existing_outputs));
1951 const bool in_out_physical =
1952 (Config->get_input_auto_connect() & AutoConnectPhysical)
1953 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1956 const ChanCount in_offset = in_out_physical
1957 ? ChanCount::max(existing_inputs, existing_outputs)
1960 const ChanCount out_offset = in_out_physical
1961 ? ChanCount::max(existing_inputs, existing_outputs)
1964 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1965 vector<string> physinputs;
1966 vector<string> physoutputs;
1968 _engine.get_physical_outputs (*t, physoutputs);
1969 _engine.get_physical_inputs (*t, physinputs);
1971 if (!physinputs.empty() && connect_inputs) {
1972 uint32_t nphysical_in = physinputs.size();
1974 DEBUG_TRACE (DEBUG::Graph,
1975 string_compose("There are %1 physical inputs of type %2\n",
1978 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1981 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1982 DEBUG_TRACE (DEBUG::Graph,
1983 string_compose("Get index %1 + %2 % %3 = %4\n",
1984 in_offset.get(*t), i, nphysical_in,
1985 (in_offset.get(*t) + i) % nphysical_in));
1986 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1989 DEBUG_TRACE (DEBUG::Graph,
1990 string_compose("Connect route %1 IN to %2\n",
1991 route->name(), port));
1993 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1997 ChanCount one_added (*t, 1);
1998 existing_inputs += one_added;
2002 if (!physoutputs.empty()) {
2003 uint32_t nphysical_out = physoutputs.size();
2004 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2007 if ((*t) == DataType::MIDI || Config->get_output_auto_connect() & AutoConnectPhysical) {
2008 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2009 } else if ((*t) == DataType::AUDIO && Config->get_output_auto_connect() & AutoConnectMaster) {
2010 /* master bus is audio only */
2011 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2012 port = _master_out->input()->ports().port(*t,
2013 i % _master_out->input()->n_ports().get(*t))->name();
2017 DEBUG_TRACE (DEBUG::Graph,
2018 string_compose("Connect route %1 OUT to %2\n",
2019 route->name(), port));
2021 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2025 ChanCount one_added (*t, 1);
2026 existing_outputs += one_added;
2032 /** Caller must not hold process lock
2033 * @param name_template string to use for the start of the name, or "" to use "Audio".
2035 list< boost::shared_ptr<AudioTrack> >
2036 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2037 uint32_t how_many, string name_template)
2039 char track_name[32];
2040 uint32_t track_id = 0;
2042 RouteList new_routes;
2043 list<boost::shared_ptr<AudioTrack> > ret;
2045 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2048 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2049 error << "cannot find name for new audio track" << endmsg;
2053 boost::shared_ptr<AudioTrack> track;
2056 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2058 if (track->init ()) {
2062 track->use_new_diskstream();
2064 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2065 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2068 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2070 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2071 error << string_compose (
2072 _("cannot configure %1 in/%2 out configuration for new audio track"),
2073 input_channels, output_channels)
2078 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2079 error << string_compose (
2080 _("cannot configure %1 in/%2 out configuration for new audio track"),
2081 input_channels, output_channels)
2088 route_group->add (track);
2091 track->non_realtime_input_change();
2093 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2094 if (Config->get_remote_model() == UserOrdered) {
2095 track->set_remote_control_id (next_control_id());
2098 new_routes.push_back (track);
2099 ret.push_back (track);
2102 catch (failed_constructor &err) {
2103 error << _("Session: could not create new audio track.") << endmsg;
2107 catch (AudioEngine::PortRegistrationFailure& pfe) {
2109 error << pfe.what() << endmsg;
2117 if (!new_routes.empty()) {
2118 add_routes (new_routes, true, true, true);
2124 /** Caller must not hold process lock.
2125 * @param name_template string to use for the start of the name, or "" to use "Bus".
2128 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2131 uint32_t bus_id = 0;
2135 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2138 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2139 error << "cannot find name for new audio bus" << endmsg;
2144 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2150 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2151 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2154 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2156 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2157 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2158 input_channels, output_channels)
2164 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2165 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2166 input_channels, output_channels)
2173 route_group->add (bus);
2175 if (Config->get_remote_model() == UserOrdered) {
2176 bus->set_remote_control_id (next_control_id());
2179 bus->add_internal_return ();
2181 ret.push_back (bus);
2187 catch (failed_constructor &err) {
2188 error << _("Session: could not create new audio route.") << endmsg;
2192 catch (AudioEngine::PortRegistrationFailure& pfe) {
2193 error << pfe.what() << endmsg;
2203 add_routes (ret, false, true, true); // autoconnect outputs only
2211 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2214 uint32_t control_id;
2216 uint32_t number = 0;
2217 const uint32_t being_added = how_many;
2219 if (!tree.read (template_path.c_str())) {
2223 XMLNode* node = tree.root();
2225 IO::disable_connecting ();
2227 control_id = next_control_id ();
2231 XMLNode node_copy (*node);
2233 /* Remove IDs of everything so that new ones are used */
2234 node_copy.remove_property_recursively (X_("id"));
2239 if (!name_base.empty()) {
2241 /* if we're adding more than one routes, force
2242 * all the names of the new routes to be
2243 * numbered, via the final parameter.
2246 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2247 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2253 string const route_name = node_copy.property(X_("name"))->value ();
2255 /* generate a new name by adding a number to the end of the template name */
2256 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2257 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2262 /* set this name in the XML description that we are about to use */
2263 Route::set_name_in_state (node_copy, name);
2265 /* trim bitslots from listen sends so that new ones are used */
2266 XMLNodeList children = node_copy.children ();
2267 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2268 if ((*i)->name() == X_("Processor")) {
2269 XMLProperty* role = (*i)->property (X_("role"));
2270 if (role && role->value() == X_("Listen")) {
2271 (*i)->remove_property (X_("bitslot"));
2276 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2279 error << _("Session: cannot create track/bus from template description") << endmsg;
2283 if (boost::dynamic_pointer_cast<Track>(route)) {
2284 /* force input/output change signals so that the new diskstream
2285 picks up the configuration of the route. During session
2286 loading this normally happens in a different way.
2289 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2291 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2292 change.after = route->input()->n_ports();
2293 route->input()->changed (change, this);
2294 change.after = route->output()->n_ports();
2295 route->output()->changed (change, this);
2298 route->set_remote_control_id (control_id);
2301 ret.push_back (route);
2304 catch (failed_constructor &err) {
2305 error << _("Session: could not create new route from template") << endmsg;
2309 catch (AudioEngine::PortRegistrationFailure& pfe) {
2310 error << pfe.what() << endmsg;
2319 add_routes (ret, true, true, true);
2320 IO::enable_connecting ();
2327 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2330 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2331 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2334 error << _("Adding new tracks/busses failed") << endmsg;
2339 update_latency (true);
2340 update_latency (false);
2345 save_state (_current_snapshot_name);
2348 RouteAdded (new_routes); /* EMIT SIGNAL */
2352 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2354 ChanCount existing_inputs;
2355 ChanCount existing_outputs;
2356 uint32_t order = next_control_id();
2358 count_existing_track_channels (existing_inputs, existing_outputs);
2361 RCUWriter<RouteList> writer (routes);
2362 boost::shared_ptr<RouteList> r = writer.get_copy ();
2363 r->insert (r->end(), new_routes.begin(), new_routes.end());
2365 /* if there is no control out and we're not in the middle of loading,
2366 resort the graph here. if there is a control out, we will resort
2367 toward the end of this method. if we are in the middle of loading,
2368 we will resort when done.
2371 if (!_monitor_out && IO::connecting_legal) {
2372 resort_routes_using (r);
2376 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2378 boost::weak_ptr<Route> wpr (*x);
2379 boost::shared_ptr<Route> r (*x);
2381 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2382 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2383 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2384 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2385 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2386 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2388 if (r->is_master()) {
2392 if (r->is_monitor()) {
2396 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2398 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2399 track_playlist_changed (boost::weak_ptr<Track> (tr));
2400 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2402 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2404 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2405 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2410 if (input_auto_connect || output_auto_connect) {
2411 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2414 /* order keys are a GUI responsibility but we need to set up
2415 reasonable defaults because they also affect the remote control
2416 ID in most situations.
2419 if (!r->has_order_key (EditorSort)) {
2420 if (r->is_auditioner()) {
2421 /* use an arbitrarily high value */
2422 r->set_order_key (EditorSort, UINT_MAX);
2423 r->set_order_key (MixerSort, UINT_MAX);
2425 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2426 r->set_order_key (EditorSort, order);
2427 r->set_order_key (MixerSort, order);
2435 if (_monitor_out && IO::connecting_legal) {
2436 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2438 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2439 if ((*x)->is_monitor()) {
2441 } else if ((*x)->is_master()) {
2444 (*x)->enable_monitor_send ();
2451 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2453 boost::shared_ptr<RouteList> r = routes.reader ();
2454 boost::shared_ptr<Send> s;
2456 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2457 if ((s = (*i)->internal_send_for (dest)) != 0) {
2458 s->amp()->gain_control()->set_value (0.0);
2464 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2466 boost::shared_ptr<RouteList> r = routes.reader ();
2467 boost::shared_ptr<Send> s;
2469 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2470 if ((s = (*i)->internal_send_for (dest)) != 0) {
2471 s->amp()->gain_control()->set_value (1.0);
2477 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2479 boost::shared_ptr<RouteList> r = routes.reader ();
2480 boost::shared_ptr<Send> s;
2482 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2483 if ((s = (*i)->internal_send_for (dest)) != 0) {
2484 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2489 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2491 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2493 boost::shared_ptr<RouteList> r = routes.reader ();
2494 boost::shared_ptr<RouteList> t (new RouteList);
2496 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2497 /* no MIDI sends because there are no MIDI busses yet */
2498 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2503 add_internal_sends (dest, p, t);
2507 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2509 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2510 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2515 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2517 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2521 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2523 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2527 if (!dest->internal_return()) {
2528 dest->add_internal_return ();
2531 sender->add_aux_send (dest, before);
2537 Session::remove_route (boost::shared_ptr<Route> route)
2539 if (route == _master_out) {
2543 route->set_solo (false, this);
2546 RCUWriter<RouteList> writer (routes);
2547 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2551 /* deleting the master out seems like a dumb
2552 idea, but its more of a UI policy issue
2556 if (route == _master_out) {
2557 _master_out = boost::shared_ptr<Route> ();
2560 if (route == _monitor_out) {
2561 _monitor_out.reset ();
2564 /* writer goes out of scope, forces route list update */
2567 update_route_solo_state ();
2569 // We need to disconnect the route's inputs and outputs
2571 route->input()->disconnect (0);
2572 route->output()->disconnect (0);
2574 /* if the route had internal sends sending to it, remove them */
2575 if (route->internal_return()) {
2577 boost::shared_ptr<RouteList> r = routes.reader ();
2578 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2579 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2581 (*i)->remove_processor (s);
2586 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2587 if (mt && mt->step_editing()) {
2588 if (_step_editors > 0) {
2593 update_latency_compensation ();
2596 /* Re-sort routes to remove the graph's current references to the one that is
2597 * going away, then flush old references out of the graph.
2601 if (_process_graph) {
2602 _process_graph->clear_other_chain ();
2605 /* get rid of it from the dead wood collection in the route list manager */
2607 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2611 /* try to cause everyone to drop their references */
2613 route->drop_references ();
2615 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2617 /* save the new state of the world */
2619 if (save_state (_current_snapshot_name)) {
2620 save_history (_current_snapshot_name);
2625 Session::route_mute_changed (void* /*src*/)
2631 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2633 boost::shared_ptr<Route> route = wpr.lock();
2635 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2639 if (route->listening_via_monitor ()) {
2641 if (Config->get_exclusive_solo()) {
2642 /* new listen: disable all other listen */
2643 boost::shared_ptr<RouteList> r = routes.reader ();
2644 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2645 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2648 (*i)->set_listen (false, this);
2654 } else if (_listen_cnt > 0) {
2659 update_route_solo_state ();
2662 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2664 boost::shared_ptr<Route> route = wpr.lock ();
2667 /* should not happen */
2668 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2672 bool send_changed = false;
2674 if (route->solo_isolated()) {
2675 if (_solo_isolated_cnt == 0) {
2676 send_changed = true;
2678 _solo_isolated_cnt++;
2679 } else if (_solo_isolated_cnt > 0) {
2680 _solo_isolated_cnt--;
2681 if (_solo_isolated_cnt == 0) {
2682 send_changed = true;
2687 IsolatedChanged (); /* EMIT SIGNAL */
2692 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2694 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2696 if (!self_solo_change) {
2697 // session doesn't care about changes to soloed-by-others
2701 if (solo_update_disabled) {
2703 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2707 boost::shared_ptr<Route> route = wpr.lock ();
2710 boost::shared_ptr<RouteList> r = routes.reader ();
2713 if (route->self_soloed()) {
2719 RouteGroup* rg = route->route_group ();
2720 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2722 if (delta == 1 && Config->get_exclusive_solo()) {
2724 /* new solo: disable all other solos, but not the group if its solo-enabled */
2726 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2727 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2728 (leave_group_alone && ((*i)->route_group() == rg))) {
2731 (*i)->set_solo (false, this);
2735 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2737 solo_update_disabled = true;
2739 RouteList uninvolved;
2741 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2743 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2744 bool via_sends_only;
2745 bool in_signal_flow;
2747 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2748 (leave_group_alone && ((*i)->route_group() == rg))) {
2752 in_signal_flow = false;
2754 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2756 if ((*i)->feeds (route, &via_sends_only)) {
2757 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2758 if (!via_sends_only) {
2759 if (!route->soloed_by_others_upstream()) {
2760 (*i)->mod_solo_by_others_downstream (delta);
2763 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2765 in_signal_flow = true;
2767 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2770 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2772 if (route->feeds (*i, &via_sends_only)) {
2773 /* propagate solo upstream only if routing other than
2774 sends is involved, but do consider the other route
2775 (*i) to be part of the signal flow even if only
2778 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2782 route->soloed_by_others_downstream(),
2783 route->soloed_by_others_upstream()));
2784 if (!via_sends_only) {
2785 if (!route->soloed_by_others_downstream()) {
2786 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2787 (*i)->mod_solo_by_others_upstream (delta);
2789 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2792 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2794 in_signal_flow = true;
2796 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2799 if (!in_signal_flow) {
2800 uninvolved.push_back (*i);
2804 solo_update_disabled = false;
2805 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2807 update_route_solo_state (r);
2809 /* now notify that the mute state of the routes not involved in the signal
2810 pathway of the just-solo-changed route may have altered.
2813 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2814 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2815 (*i)->mute_changed (this);
2818 SoloChanged (); /* EMIT SIGNAL */
2823 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2825 /* now figure out if anything that matters is soloed (or is "listening")*/
2827 bool something_soloed = false;
2828 uint32_t listeners = 0;
2829 uint32_t isolated = 0;
2832 r = routes.reader();
2835 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2836 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2837 something_soloed = true;
2840 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2841 if (Config->get_solo_control_is_listen_control()) {
2844 (*i)->set_listen (false, this);
2848 if ((*i)->solo_isolated()) {
2853 if (something_soloed != _non_soloed_outs_muted) {
2854 _non_soloed_outs_muted = something_soloed;
2855 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2858 _listen_cnt = listeners;
2860 if (isolated != _solo_isolated_cnt) {
2861 _solo_isolated_cnt = isolated;
2862 IsolatedChanged (); /* EMIT SIGNAL */
2865 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2866 something_soloed, listeners, isolated));
2869 boost::shared_ptr<RouteList>
2870 Session::get_routes_with_internal_returns() const
2872 boost::shared_ptr<RouteList> r = routes.reader ();
2873 boost::shared_ptr<RouteList> rl (new RouteList);
2875 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2876 if ((*i)->internal_return ()) {
2884 Session::io_name_is_legal (const std::string& name)
2886 boost::shared_ptr<RouteList> r = routes.reader ();
2888 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2889 if ((*i)->name() == name) {
2893 if ((*i)->has_io_processor_named (name)) {
2902 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2905 vector<string> connections;
2907 /* if we are passed only a single route and we're not told to turn
2908 * others off, then just do the simple thing.
2911 if (flip_others == false && rl->size() == 1) {
2912 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2914 mt->set_input_active (onoff);
2919 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2921 PortSet& ps ((*rt)->input()->ports());
2923 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2924 p->get_connections (connections);
2927 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2928 routes_using_input_from (*s, rl2);
2931 /* scan all relevant routes to see if others are on or off */
2933 bool others_are_already_on = false;
2935 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2937 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2943 if ((*r) != (*rt)) {
2944 if (mt->input_active()) {
2945 others_are_already_on = true;
2948 /* this one needs changing */
2949 mt->set_input_active (onoff);
2955 /* globally reverse other routes */
2957 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2958 if ((*r) != (*rt)) {
2959 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2961 mt->set_input_active (!others_are_already_on);
2970 Session::routes_using_input_from (const string& str, RouteList& rl)
2972 boost::shared_ptr<RouteList> r = routes.reader();
2974 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2975 if ((*i)->input()->connected_to (str)) {
2981 boost::shared_ptr<Route>
2982 Session::route_by_name (string name)
2984 boost::shared_ptr<RouteList> r = routes.reader ();
2986 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2987 if ((*i)->name() == name) {
2992 return boost::shared_ptr<Route> ((Route*) 0);
2995 boost::shared_ptr<Route>
2996 Session::route_by_id (PBD::ID id)
2998 boost::shared_ptr<RouteList> r = routes.reader ();
3000 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3001 if ((*i)->id() == id) {
3006 return boost::shared_ptr<Route> ((Route*) 0);
3009 boost::shared_ptr<Track>
3010 Session::track_by_diskstream_id (PBD::ID id)
3012 boost::shared_ptr<RouteList> r = routes.reader ();
3014 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3015 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3016 if (t && t->using_diskstream_id (id)) {
3021 return boost::shared_ptr<Track> ();
3024 boost::shared_ptr<Route>
3025 Session::route_by_remote_id (uint32_t id)
3027 boost::shared_ptr<RouteList> r = routes.reader ();
3029 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3030 if ((*i)->remote_control_id() == id) {
3035 return boost::shared_ptr<Route> ((Route*) 0);
3039 Session::playlist_region_added (boost::weak_ptr<Region> w)
3041 boost::shared_ptr<Region> r = w.lock ();
3046 /* These are the operations that are currently in progress... */
3047 list<GQuark> curr = _current_trans_quarks;
3050 /* ...and these are the operations during which we want to update
3051 the session range location markers.
3054 ops.push_back (Operations::capture);
3055 ops.push_back (Operations::paste);
3056 ops.push_back (Operations::duplicate_region);
3057 ops.push_back (Operations::insert_file);
3058 ops.push_back (Operations::insert_region);
3059 ops.push_back (Operations::drag_region_brush);
3060 ops.push_back (Operations::region_drag);
3061 ops.push_back (Operations::selection_grab);
3062 ops.push_back (Operations::region_fill);
3063 ops.push_back (Operations::fill_selection);
3064 ops.push_back (Operations::create_region);
3065 ops.push_back (Operations::region_copy);
3066 ops.push_back (Operations::fixed_time_region_copy);
3069 /* See if any of the current operations match the ones that we want */
3071 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3073 /* If so, update the session range markers */
3075 maybe_update_session_range (r->position (), r->last_frame ());
3079 /** Update the session range markers if a is before the current start or
3080 * b is after the current end.
3083 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3085 if (_state_of_the_state & Loading) {
3089 if (_session_range_location == 0) {
3091 add_session_range_location (a, b);
3095 if (a < _session_range_location->start()) {
3096 _session_range_location->set_start (a);
3099 if (b > _session_range_location->end()) {
3100 _session_range_location->set_end (b);
3106 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3108 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3109 maybe_update_session_range (i->to, i->to + i->length);
3114 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3116 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3117 maybe_update_session_range (i->from, i->to);
3121 /* Region management */
3123 boost::shared_ptr<Region>
3124 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3126 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3127 RegionFactory::RegionMap::const_iterator i;
3128 boost::shared_ptr<Region> region;
3130 Glib::Threads::Mutex::Lock lm (region_lock);
3132 for (i = regions.begin(); i != regions.end(); ++i) {
3136 if (region->whole_file()) {
3138 if (child->source_equivalent (region)) {
3144 return boost::shared_ptr<Region> ();
3148 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3150 set<boost::shared_ptr<Region> > relevant_regions;
3152 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3153 RegionFactory::get_regions_using_source (*s, relevant_regions);
3156 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3157 set<boost::shared_ptr<Region> >::iterator tmp;
3162 playlists->destroy_region (*r);
3163 RegionFactory::map_remove (*r);
3165 (*r)->drop_sources ();
3166 (*r)->drop_references ();
3168 relevant_regions.erase (r);
3173 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3176 Glib::Threads::Mutex::Lock ls (source_lock);
3177 /* remove from the main source list */
3178 sources.erase ((*s)->id());
3181 (*s)->mark_for_remove ();
3182 (*s)->drop_references ();
3191 Session::remove_last_capture ()
3193 list<boost::shared_ptr<Source> > srcs;
3195 boost::shared_ptr<RouteList> rl = routes.reader ();
3196 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3197 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3202 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3205 srcs.insert (srcs.end(), l.begin(), l.end());
3210 destroy_sources (srcs);
3212 save_state (_current_snapshot_name);
3217 /* Source Management */
3220 Session::add_source (boost::shared_ptr<Source> source)
3222 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3223 pair<SourceMap::iterator,bool> result;
3225 entry.first = source->id();
3226 entry.second = source;
3229 Glib::Threads::Mutex::Lock lm (source_lock);
3230 result = sources.insert (entry);
3233 if (result.second) {
3235 /* yay, new source */
3237 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3240 if (!fs->within_session()) {
3241 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3247 boost::shared_ptr<AudioFileSource> afs;
3249 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3250 if (Config->get_auto_analyse_audio()) {
3251 Analyser::queue_source_for_analysis (source, false);
3255 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3260 Session::remove_source (boost::weak_ptr<Source> src)
3262 if (_state_of_the_state & Deletion) {
3266 SourceMap::iterator i;
3267 boost::shared_ptr<Source> source = src.lock();
3274 Glib::Threads::Mutex::Lock lm (source_lock);
3276 if ((i = sources.find (source->id())) != sources.end()) {
3281 if (!(_state_of_the_state & InCleanup)) {
3283 /* save state so we don't end up with a session file
3284 referring to non-existent sources.
3287 save_state (_current_snapshot_name);
3291 boost::shared_ptr<Source>
3292 Session::source_by_id (const PBD::ID& id)
3294 Glib::Threads::Mutex::Lock lm (source_lock);
3295 SourceMap::iterator i;
3296 boost::shared_ptr<Source> source;
3298 if ((i = sources.find (id)) != sources.end()) {
3305 boost::shared_ptr<Source>
3306 Session::source_by_path_and_channel (const string& path, uint16_t chn)
3308 Glib::Threads::Mutex::Lock lm (source_lock);
3310 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3311 boost::shared_ptr<AudioFileSource> afs
3312 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3314 if (afs && afs->path() == path && chn == afs->channel()) {
3318 return boost::shared_ptr<Source>();
3322 Session::count_sources_by_origin (const string& path)
3325 Glib::Threads::Mutex::Lock lm (source_lock);
3327 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3328 boost::shared_ptr<FileSource> fs
3329 = boost::dynamic_pointer_cast<FileSource>(i->second);
3331 if (fs && fs->origin() == path) {
3341 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3344 string old_basename = PBD::basename_nosuffix (oldname);
3345 string new_legalized = legalize_for_path (newname);
3347 /* note: we know (or assume) the old path is already valid */
3351 /* destructive file sources have a name of the form:
3353 /path/to/Tnnnn-NAME(%[LR])?.wav
3355 the task here is to replace NAME with the new name.
3360 string::size_type dash;
3362 dir = Glib::path_get_dirname (path);
3363 path = Glib::path_get_basename (path);
3365 /* '-' is not a legal character for the NAME part of the path */
3367 if ((dash = path.find_last_of ('-')) == string::npos) {
3371 prefix = path.substr (0, dash);
3375 path += new_legalized;
3376 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3377 path = Glib::build_filename (dir, path);
3381 /* non-destructive file sources have a name of the form:
3383 /path/to/NAME-nnnnn(%[LR])?.ext
3385 the task here is to replace NAME with the new name.
3390 string::size_type dash;
3391 string::size_type postfix;
3393 dir = Glib::path_get_dirname (path);
3394 path = Glib::path_get_basename (path);
3396 /* '-' is not a legal character for the NAME part of the path */
3398 if ((dash = path.find_last_of ('-')) == string::npos) {
3402 suffix = path.substr (dash+1);
3404 // Suffix is now everything after the dash. Now we need to eliminate
3405 // the nnnnn part, which is done by either finding a '%' or a '.'
3407 postfix = suffix.find_last_of ("%");
3408 if (postfix == string::npos) {
3409 postfix = suffix.find_last_of ('.');
3412 if (postfix != string::npos) {
3413 suffix = suffix.substr (postfix);
3415 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3419 const uint32_t limit = 10000;
3420 char buf[PATH_MAX+1];
3422 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3424 snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
3426 if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
3427 path = Glib::build_filename (dir, buf);
3435 fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
3444 /** Return the full path (in some session directory) for a new within-session source.
3445 * \a name must be a session-unique name that does not contain slashes
3446 * (e.g. as returned by new_*_source_name)
3449 Session::new_source_path_from_name (DataType type, const string& name)
3451 assert(name.find("/") == string::npos);
3453 SessionDirectory sdir(get_best_session_directory_for_new_source());
3456 if (type == DataType::AUDIO) {
3457 p = sdir.sound_path();
3458 } else if (type == DataType::MIDI) {
3459 p = sdir.midi_path();
3461 error << "Unknown source type, unable to create file path" << endmsg;
3465 return Glib::build_filename (p, name);
3469 Session::peak_path (string base) const
3471 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3474 /** Return a unique name based on \a base for a new internal audio source */
3476 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3479 char buf[PATH_MAX+1];
3480 const uint32_t limit = 10000;
3482 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3485 legalized = legalize_for_path (base);
3487 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3488 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3490 vector<space_and_path>::iterator i;
3491 uint32_t existing = 0;
3493 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3498 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3499 cnt, legalized.c_str(), ext.c_str());
3500 } else if (nchan == 2) {
3502 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3503 cnt, legalized.c_str(), ext.c_str());
3505 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3506 cnt, legalized.c_str(), ext.c_str());
3508 } else if (nchan < 26) {
3509 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3510 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3512 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3513 cnt, legalized.c_str(), ext.c_str());
3519 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3520 } else if (nchan == 2) {
3522 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3524 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3526 } else if (nchan < 26) {
3527 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3529 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3533 SessionDirectory sdir((*i).path);
3535 string spath = sdir.sound_path();
3537 /* note that we search *without* the extension so that
3538 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3539 in the event that this new name is required for
3540 a file format change.
3543 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3549 if (existing == 0) {
3554 error << string_compose(
3555 _("There are already %1 recordings for %2, which I consider too many."),
3556 limit, base) << endmsg;
3558 throw failed_constructor();
3562 return Glib::path_get_basename (buf);
3565 /** Create a new within-session audio source */
3566 boost::shared_ptr<AudioFileSource>
3567 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3569 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3570 const string path = new_source_path_from_name(DataType::AUDIO, name);
3572 return boost::dynamic_pointer_cast<AudioFileSource> (
3573 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3576 /** Return a unique name based on \a base for a new internal MIDI source */
3578 Session::new_midi_source_name (const string& base)
3581 char buf[PATH_MAX+1];
3582 const uint32_t limit = 10000;
3586 legalized = legalize_for_path (base);
3588 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3589 for (cnt = 1; cnt <= limit; ++cnt) {
3591 vector<space_and_path>::iterator i;
3592 uint32_t existing = 0;
3594 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3596 SessionDirectory sdir((*i).path);
3598 std::string p = Glib::build_filename (sdir.midi_path(), legalized);
3600 snprintf (buf, sizeof(buf), "%s-%u.mid", p.c_str(), cnt);
3602 if (Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
3607 if (existing == 0) {
3612 error << string_compose(
3613 _("There are already %1 recordings for %2, which I consider too many."),
3614 limit, base) << endmsg;
3616 throw failed_constructor();
3620 return Glib::path_get_basename(buf);
3624 /** Create a new within-session MIDI source */
3625 boost::shared_ptr<MidiSource>
3626 Session::create_midi_source_for_session (Track* track, string const & n)
3628 /* try to use the existing write source for the track, to keep numbering sane
3632 /*MidiTrack* mt = dynamic_cast<Track*> (track);
3636 list<boost::shared_ptr<Source> > l = track->steal_write_sources ();
3639 assert (boost::dynamic_pointer_cast<MidiSource> (l.front()));
3640 return boost::dynamic_pointer_cast<MidiSource> (l.front());
3644 const string name = new_midi_source_name (n);
3645 const string path = new_source_path_from_name (DataType::MIDI, name);
3647 return boost::dynamic_pointer_cast<SMFSource> (
3648 SourceFactory::createWritable (
3649 DataType::MIDI, *this, path, false, frame_rate()));
3654 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3656 if (playlist->hidden()) {
3660 playlists->add (playlist);
3663 playlist->release();
3670 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3672 if (_state_of_the_state & Deletion) {
3676 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3682 playlists->remove (playlist);
3688 Session::set_audition (boost::shared_ptr<Region> r)
3690 pending_audition_region = r;
3691 add_post_transport_work (PostTransportAudition);
3692 _butler->schedule_transport_work ();
3696 Session::audition_playlist ()
3698 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3699 ev->region.reset ();
3704 Session::non_realtime_set_audition ()
3706 assert (pending_audition_region);
3707 auditioner->audition_region (pending_audition_region);
3708 pending_audition_region.reset ();
3709 AuditionActive (true); /* EMIT SIGNAL */
3713 Session::audition_region (boost::shared_ptr<Region> r)
3715 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3721 Session::cancel_audition ()
3723 if (auditioner->auditioning()) {
3724 auditioner->cancel_audition ();
3725 AuditionActive (false); /* EMIT SIGNAL */
3730 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3732 if (a->is_monitor()) {
3735 if (b->is_monitor()) {
3738 return a->order_key (MixerSort) < b->order_key (MixerSort);
3742 Session::is_auditioning () const
3744 /* can be called before we have an auditioner object */
3746 return auditioner->auditioning();
3753 Session::graph_reordered ()
3755 /* don't do this stuff if we are setting up connections
3756 from a set_state() call or creating new tracks. Ditto for deletion.
3759 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3763 /* every track/bus asked for this to be handled but it was deferred because
3764 we were connecting. do it now.
3767 request_input_change_handling ();
3771 /* force all diskstreams to update their capture offset values to
3772 reflect any changes in latencies within the graph.
3775 boost::shared_ptr<RouteList> rl = routes.reader ();
3776 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3777 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3779 tr->set_capture_offset ();
3784 /** @return Number of frames that there is disk space available to write,
3787 boost::optional<framecnt_t>
3788 Session::available_capture_duration ()
3790 Glib::Threads::Mutex::Lock lm (space_lock);
3792 if (_total_free_4k_blocks_uncertain) {
3793 return boost::optional<framecnt_t> ();
3796 float sample_bytes_on_disk = 4.0; // keep gcc happy
3798 switch (config.get_native_file_data_format()) {
3800 sample_bytes_on_disk = 4.0;
3804 sample_bytes_on_disk = 3.0;
3808 sample_bytes_on_disk = 2.0;
3812 /* impossible, but keep some gcc versions happy */
3813 fatal << string_compose (_("programming error: %1"),
3814 X_("illegal native file data format"))
3819 double scale = 4096.0 / sample_bytes_on_disk;
3821 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3822 return max_framecnt;
3825 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3829 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3832 RCUWriter<BundleList> writer (_bundles);
3833 boost::shared_ptr<BundleList> b = writer.get_copy ();
3834 b->push_back (bundle);
3837 BundleAdded (bundle); /* EMIT SIGNAL */
3843 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3845 bool removed = false;
3848 RCUWriter<BundleList> writer (_bundles);
3849 boost::shared_ptr<BundleList> b = writer.get_copy ();
3850 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3852 if (i != b->end()) {
3859 BundleRemoved (bundle); /* EMIT SIGNAL */
3865 boost::shared_ptr<Bundle>
3866 Session::bundle_by_name (string name) const
3868 boost::shared_ptr<BundleList> b = _bundles.reader ();
3870 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3871 if ((*i)->name() == name) {
3876 return boost::shared_ptr<Bundle> ();
3880 Session::tempo_map_changed (const PropertyChange&)
3884 playlists->update_after_tempo_map_change ();
3886 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3892 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3894 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3895 (*i)->recompute_frames_from_bbt ();
3899 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3900 * the given count with the current block size.
3903 Session::ensure_buffers (ChanCount howmany)
3905 BufferManager::ensure_buffers (howmany);
3909 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3911 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3912 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3917 Session::next_insert_id ()
3919 /* this doesn't really loop forever. just think about it */
3922 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3923 if (!insert_bitset[n]) {
3924 insert_bitset[n] = true;
3930 /* none available, so resize and try again */
3932 insert_bitset.resize (insert_bitset.size() + 16, false);
3937 Session::next_send_id ()
3939 /* this doesn't really loop forever. just think about it */
3942 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3943 if (!send_bitset[n]) {
3944 send_bitset[n] = true;
3950 /* none available, so resize and try again */
3952 send_bitset.resize (send_bitset.size() + 16, false);
3957 Session::next_aux_send_id ()
3959 /* this doesn't really loop forever. just think about it */
3962 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3963 if (!aux_send_bitset[n]) {
3964 aux_send_bitset[n] = true;
3970 /* none available, so resize and try again */
3972 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3977 Session::next_return_id ()
3979 /* this doesn't really loop forever. just think about it */
3982 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3983 if (!return_bitset[n]) {
3984 return_bitset[n] = true;
3990 /* none available, so resize and try again */
3992 return_bitset.resize (return_bitset.size() + 16, false);
3997 Session::mark_send_id (uint32_t id)
3999 if (id >= send_bitset.size()) {
4000 send_bitset.resize (id+16, false);
4002 if (send_bitset[id]) {
4003 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4005 send_bitset[id] = true;
4009 Session::mark_aux_send_id (uint32_t id)
4011 if (id >= aux_send_bitset.size()) {
4012 aux_send_bitset.resize (id+16, false);
4014 if (aux_send_bitset[id]) {
4015 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4017 aux_send_bitset[id] = true;
4021 Session::mark_return_id (uint32_t id)
4023 if (id >= return_bitset.size()) {
4024 return_bitset.resize (id+16, false);
4026 if (return_bitset[id]) {
4027 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4029 return_bitset[id] = true;
4033 Session::mark_insert_id (uint32_t id)
4035 if (id >= insert_bitset.size()) {
4036 insert_bitset.resize (id+16, false);
4038 if (insert_bitset[id]) {
4039 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4041 insert_bitset[id] = true;
4045 Session::unmark_send_id (uint32_t id)
4047 if (id < send_bitset.size()) {
4048 send_bitset[id] = false;
4053 Session::unmark_aux_send_id (uint32_t id)
4055 if (id < aux_send_bitset.size()) {
4056 aux_send_bitset[id] = false;
4061 Session::unmark_return_id (uint32_t id)
4063 if (id < return_bitset.size()) {
4064 return_bitset[id] = false;
4069 Session::unmark_insert_id (uint32_t id)
4071 if (id < insert_bitset.size()) {
4072 insert_bitset[id] = false;
4077 Session::reset_native_file_format ()
4079 boost::shared_ptr<RouteList> rl = routes.reader ();
4080 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4081 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4083 /* don't save state as we do this, there's no point
4086 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4087 tr->reset_write_sources (false);
4088 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4094 Session::route_name_unique (string n) const
4096 boost::shared_ptr<RouteList> r = routes.reader ();
4098 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4099 if ((*i)->name() == n) {
4108 Session::route_name_internal (string n) const
4110 if (auditioner && auditioner->name() == n) {
4114 if (_click_io && _click_io->name() == n) {
4122 Session::freeze_all (InterThreadInfo& itt)
4124 boost::shared_ptr<RouteList> r = routes.reader ();
4126 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4128 boost::shared_ptr<Track> t;
4130 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4131 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4141 boost::shared_ptr<Region>
4142 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4143 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4144 InterThreadInfo& itt,
4145 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4148 boost::shared_ptr<Region> result;
4149 boost::shared_ptr<Playlist> playlist;
4150 boost::shared_ptr<AudioFileSource> fsource;
4152 char buf[PATH_MAX+1];
4153 ChanCount diskstream_channels (track.n_channels());
4154 framepos_t position;
4155 framecnt_t this_chunk;
4158 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4159 const string sound_dir = sdir.sound_path();
4160 framepos_t len = end - start;
4161 bool need_block_size_reset = false;
4163 ChanCount const max_proc = track.max_processor_streams ();
4166 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4167 end, start) << endmsg;
4171 const framecnt_t chunk_size = (256 * 1024)/4;
4173 // block all process callback handling
4175 block_processing ();
4177 /* call tree *MUST* hold route_lock */
4179 if ((playlist = track.playlist()) == 0) {
4183 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4185 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4187 for (x = 0; x < 99999; ++x) {
4188 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());
4189 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4195 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4200 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4201 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4204 catch (failed_constructor& err) {
4205 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4209 srcs.push_back (fsource);
4212 /* tell redirects that care that we are about to use a much larger
4213 * blocksize. this will flush all plugins too, so that they are ready
4214 * to be used for this process.
4217 need_block_size_reset = true;
4218 track.set_block_size (chunk_size);
4223 /* create a set of reasonably-sized buffers */
4224 buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
4225 buffers.set_count (max_proc);
4227 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4228 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4230 afs->prepare_for_peakfile_writes ();
4233 while (to_do && !itt.cancel) {
4235 this_chunk = min (to_do, chunk_size);
4237 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4242 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4243 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4246 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4252 start += this_chunk;
4253 to_do -= this_chunk;
4255 itt.progress = (float) (1.0 - ((double) to_do / len));
4264 xnow = localtime (&now);
4266 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4267 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4270 afs->update_header (position, *xnow, now);
4271 afs->flush_header ();
4275 /* construct a region to represent the bounced material */
4279 plist.add (Properties::start, 0);
4280 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4281 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4283 result = RegionFactory::create (srcs, plist);
4289 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4290 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4293 afs->mark_for_remove ();
4296 (*src)->drop_references ();
4300 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4301 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4304 afs->done_with_peakfile_writes ();
4309 if (need_block_size_reset) {
4310 track.set_block_size (get_block_size());
4313 unblock_processing ();
4319 Session::gain_automation_buffer() const
4321 return ProcessThread::gain_automation_buffer ();
4325 Session::send_gain_automation_buffer() const
4327 return ProcessThread::send_gain_automation_buffer ();
4331 Session::pan_automation_buffer() const
4333 return ProcessThread::pan_automation_buffer ();
4337 Session::get_silent_buffers (ChanCount count)
4339 return ProcessThread::get_silent_buffers (count);
4343 Session::get_scratch_buffers (ChanCount count, bool silence)
4345 return ProcessThread::get_scratch_buffers (count, silence);
4349 Session::get_route_buffers (ChanCount count, bool silence)
4351 return ProcessThread::get_route_buffers (count, silence);
4356 Session::get_mix_buffers (ChanCount count)
4358 return ProcessThread::get_mix_buffers (count);
4362 Session::ntracks () const
4365 boost::shared_ptr<RouteList> r = routes.reader ();
4367 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4368 if (boost::dynamic_pointer_cast<Track> (*i)) {
4377 Session::nbusses () const
4380 boost::shared_ptr<RouteList> r = routes.reader ();
4382 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4383 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4392 Session::add_automation_list(AutomationList *al)
4394 automation_lists[al->id()] = al;
4397 /** @return true if there is at least one record-enabled track, otherwise false */
4399 Session::have_rec_enabled_track () const
4401 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4404 /** Update the state of our rec-enabled tracks flag */
4406 Session::update_have_rec_enabled_track ()
4408 boost::shared_ptr<RouteList> rl = routes.reader ();
4409 RouteList::iterator i = rl->begin();
4410 while (i != rl->end ()) {
4412 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4413 if (tr && tr->record_enabled ()) {
4420 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4422 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4424 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4425 RecordStateChanged (); /* EMIT SIGNAL */
4430 Session::listen_position_changed ()
4432 boost::shared_ptr<RouteList> r = routes.reader ();
4434 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4435 (*i)->listen_position_changed ();
4440 Session::solo_control_mode_changed ()
4442 /* cancel all solo or all listen when solo control mode changes */
4445 set_solo (get_routes(), false);
4446 } else if (listening()) {
4447 set_listen (get_routes(), false);
4451 /** Called when a property of one of our route groups changes */
4453 Session::route_group_property_changed (RouteGroup* rg)
4455 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4458 /** Called when a route is added to one of our route groups */
4460 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4462 RouteAddedToRouteGroup (rg, r);
4465 /** Called when a route is removed from one of our route groups */
4467 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4469 RouteRemovedFromRouteGroup (rg, r);
4472 boost::shared_ptr<RouteList>
4473 Session::get_routes_with_regions_at (framepos_t const p) const
4475 boost::shared_ptr<RouteList> r = routes.reader ();
4476 boost::shared_ptr<RouteList> rl (new RouteList);
4478 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4479 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4484 boost::shared_ptr<Playlist> pl = tr->playlist ();
4489 if (pl->has_region_at (p)) {
4498 Session::goto_end ()
4500 if (_session_range_location) {
4501 request_locate (_session_range_location->end(), false);
4503 request_locate (0, false);
4508 Session::goto_start ()
4510 if (_session_range_location) {
4511 request_locate (_session_range_location->start(), false);
4513 request_locate (0, false);
4518 Session::current_start_frame () const
4520 return _session_range_location ? _session_range_location->start() : 0;
4524 Session::current_end_frame () const
4526 return _session_range_location ? _session_range_location->end() : 0;
4530 Session::add_session_range_location (framepos_t start, framepos_t end)
4532 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4533 _locations->add (_session_range_location);
4537 Session::step_edit_status_change (bool yn)
4543 send = (_step_editors == 0);
4548 send = (_step_editors == 1);
4551 if (_step_editors > 0) {
4557 StepEditStatusChange (val);
4563 Session::start_time_changed (framepos_t old)
4565 /* Update the auto loop range to match the session range
4566 (unless the auto loop range has been changed by the user)
4569 Location* s = _locations->session_range_location ();
4574 Location* l = _locations->auto_loop_location ();
4576 if (l && l->start() == old) {
4577 l->set_start (s->start(), true);
4582 Session::end_time_changed (framepos_t old)
4584 /* Update the auto loop range to match the session range
4585 (unless the auto loop range has been changed by the user)
4588 Location* s = _locations->session_range_location ();
4593 Location* l = _locations->auto_loop_location ();
4595 if (l && l->end() == old) {
4596 l->set_end (s->end(), true);
4601 Session::source_search_path (DataType type) const
4605 if (session_dirs.size() == 1) {
4607 case DataType::AUDIO:
4608 s.push_back (_session_dir->sound_path());
4610 case DataType::MIDI:
4611 s.push_back (_session_dir->midi_path());
4615 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4616 SessionDirectory sdir (i->path);
4618 case DataType::AUDIO:
4619 s.push_back (sdir.sound_path());
4621 case DataType::MIDI:
4622 s.push_back (sdir.midi_path());
4628 if (type == DataType::AUDIO) {
4629 const string sound_path_2X = _session_dir->sound_path_2X();
4630 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4631 if (find (s.begin(), s.end(), sound_path_2X) == s.end()) {
4632 s.push_back (sound_path_2X);
4637 /* now check the explicit (possibly user-specified) search path
4640 vector<string> dirs;
4643 case DataType::AUDIO:
4644 split (config.get_audio_search_path (), dirs, ':');
4646 case DataType::MIDI:
4647 split (config.get_midi_search_path (), dirs, ':');
4651 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4652 if (find (s.begin(), s.end(), *i) == s.end()) {
4659 for (vector<string>::iterator si = s.begin(); si != s.end(); ++si) {
4660 if (!search_path.empty()) {
4670 Session::ensure_search_path_includes (const string& path, DataType type)
4673 vector<string> dirs;
4680 case DataType::AUDIO:
4681 search_path = config.get_audio_search_path ();
4683 case DataType::MIDI:
4684 search_path = config.get_midi_search_path ();
4688 split (search_path, dirs, ':');
4690 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4691 /* No need to add this new directory if it has the same inode as
4692 an existing one; checking inode rather than name prevents duplicated
4693 directories when we are using symlinks.
4695 On Windows, I think we could just do if (*i == path) here.
4697 if (PBD::equivalent_paths (*i, path)) {
4702 if (!search_path.empty()) {
4706 search_path += path;
4709 case DataType::AUDIO:
4710 config.set_audio_search_path (search_path);
4712 case DataType::MIDI:
4713 config.set_midi_search_path (search_path);
4718 boost::shared_ptr<Speakers>
4719 Session::get_speakers()
4725 Session::unknown_processors () const
4729 boost::shared_ptr<RouteList> r = routes.reader ();
4730 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4731 list<string> t = (*i)->unknown_processors ();
4732 copy (t.begin(), t.end(), back_inserter (p));
4742 Session::update_latency (bool playback)
4744 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4746 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4750 boost::shared_ptr<RouteList> r = routes.reader ();
4751 framecnt_t max_latency = 0;
4754 /* reverse the list so that we work backwards from the last route to run to the first */
4755 RouteList* rl = routes.reader().get();
4756 r.reset (new RouteList (*rl));
4757 reverse (r->begin(), r->end());
4760 /* compute actual latency values for the given direction and store them all in per-port
4761 structures. this will also publish the same values (to JACK) so that computation of latency
4762 for routes can consistently use public latency values.
4765 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4766 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4769 /* because we latency compensate playback, our published playback latencies should
4770 be the same for all output ports - all material played back by ardour has
4771 the same latency, whether its caused by plugins or by latency compensation. since
4772 these may differ from the values computed above, reset all playback port latencies
4776 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4778 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4779 (*i)->set_public_port_latencies (max_latency, playback);
4784 post_playback_latency ();
4788 post_capture_latency ();
4791 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4795 Session::post_playback_latency ()
4797 set_worst_playback_latency ();
4799 boost::shared_ptr<RouteList> r = routes.reader ();
4801 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4802 if (!(*i)->is_auditioner() && ((*i)->active())) {
4803 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4807 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4808 (*i)->set_latency_compensation (_worst_track_latency);
4813 Session::post_capture_latency ()
4815 set_worst_capture_latency ();
4817 /* reflect any changes in capture latencies into capture offsets
4820 boost::shared_ptr<RouteList> rl = routes.reader();
4821 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4822 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4824 tr->set_capture_offset ();
4830 Session::initialize_latencies ()
4833 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4834 update_latency (false);
4835 update_latency (true);
4838 set_worst_io_latencies ();
4842 Session::set_worst_io_latencies ()
4844 set_worst_playback_latency ();
4845 set_worst_capture_latency ();
4849 Session::set_worst_playback_latency ()
4851 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4855 _worst_output_latency = 0;
4857 if (!_engine.connected()) {
4861 boost::shared_ptr<RouteList> r = routes.reader ();
4863 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4864 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4867 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4871 Session::set_worst_capture_latency ()
4873 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4877 _worst_input_latency = 0;
4879 if (!_engine.connected()) {
4883 boost::shared_ptr<RouteList> r = routes.reader ();
4885 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4886 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4889 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4893 Session::update_latency_compensation (bool force_whole_graph)
4895 bool some_track_latency_changed = false;
4897 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4901 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4903 _worst_track_latency = 0;
4905 boost::shared_ptr<RouteList> r = routes.reader ();
4907 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4908 if (!(*i)->is_auditioner() && ((*i)->active())) {
4910 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4911 some_track_latency_changed = true;
4913 _worst_track_latency = max (tl, _worst_track_latency);
4917 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4918 (some_track_latency_changed ? "yes" : "no")));
4920 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4922 if (some_track_latency_changed || force_whole_graph) {
4923 _engine.update_latencies ();
4927 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4928 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4932 tr->set_capture_offset ();
4937 Session::session_name_is_legal (const string& path)
4939 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4941 for (int i = 0; illegal_chars[i]; ++i) {
4942 if (path.find (illegal_chars[i]) != string::npos) {
4943 return illegal_chars[i];
4951 Session::next_control_id () const
4955 /* the monitor bus remote ID is in a different
4956 * "namespace" than regular routes. its existence doesn't
4957 * affect normal (low) numbered routes.
4964 return nroutes() - subtract;
4968 Session::notify_remote_id_change ()
4970 if (deletion_in_progress()) {
4974 switch (Config->get_remote_model()) {
4977 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4985 Session::sync_order_keys (RouteSortOrderKey sort_key_changed)
4987 if (deletion_in_progress()) {
4991 /* tell everyone that something has happened to the sort keys
4992 and let them sync up with the change(s)
4993 this will give objects that manage the sort order keys the
4994 opportunity to keep them in sync if they wish to.
4997 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("Sync Order Keys, based on %1\n", enum_2_string (sort_key_changed)));
4999 Route::SyncOrderKeys (sort_key_changed); /* EMIT SIGNAL */
5001 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5005 Session::operation_in_progress (GQuark op) const
5007 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5010 boost::shared_ptr<Port>
5011 Session::ltc_input_port () const
5013 return _ltc_input->nth (0);
5016 boost::shared_ptr<Port>
5017 Session::ltc_output_port () const
5019 return _ltc_output->nth (0);
5023 Session::reconnect_ltc_input ()
5027 string src = Config->get_ltc_source_port();
5029 _ltc_input->disconnect (this);
5031 if (src != _("None") && !src.empty()) {
5032 _ltc_input->nth (0)->connect (src);
5038 Session::reconnect_ltc_output ()
5043 string src = Config->get_ltc_sink_port();
5045 _ltc_output->disconnect (this);
5047 if (src != _("None") && !src.empty()) {
5048 _ltc_output->nth (0)->connect (src);