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/track.h"
92 #include "ardour/utils.h"
94 #include "midi++/port.h"
95 #include "midi++/mmc.h"
106 using namespace ARDOUR;
109 bool Session::_disable_all_loaded_plugins = false;
111 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
112 PBD::Signal1<void,std::string> Session::Dialog;
113 PBD::Signal0<int> Session::AskAboutPendingState;
114 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
115 PBD::Signal0<void> Session::SendFeedback;
116 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
118 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
119 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
120 PBD::Signal2<void,std::string, std::string> Session::Exported;
121 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
122 PBD::Signal0<void> Session::Quit;
123 PBD::Signal0<void> Session::FeedbackDetected;
124 PBD::Signal0<void> Session::SuccessfulGraphSort;
125 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
127 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
128 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
130 /** @param snapshot_name Snapshot name, without .ardour suffix */
131 Session::Session (AudioEngine &eng,
132 const string& fullpath,
133 const string& snapshot_name,
134 BusProfile* bus_profile,
136 : playlists (new SessionPlaylists)
138 , process_function (&Session::process_with_events)
139 , waiting_for_sync_offset (false)
140 , _base_frame_rate (0)
141 , _current_frame_rate (0)
142 , _nominal_frame_rate (0)
143 , transport_sub_state (0)
144 , _record_status (Disabled)
145 , _transport_frame (0)
146 , _session_range_location (0)
149 , _transport_speed (0)
150 , _default_transport_speed (1.0)
151 , _last_transport_speed (0)
152 , _target_transport_speed (0.0)
153 , auto_play_legal (false)
154 , _last_slave_transport_frame (0)
155 , maximum_output_latency (0)
156 , _requested_return_frame (-1)
157 , current_block_size (0)
158 , _worst_output_latency (0)
159 , _worst_input_latency (0)
160 , _worst_track_latency (0)
161 , _have_captured (false)
164 , _non_soloed_outs_muted (false)
166 , _solo_isolated_cnt (0)
168 , _was_seamless (Config->get_seamless_loop ())
169 , _under_nsm_control (false)
170 , delta_accumulator_cnt (0)
171 , average_slave_delta (1800) // !!! why 1800 ???
173 , have_first_delta_accumulator (false)
174 , _slave_state (Stopped)
175 , post_export_sync (false)
176 , post_export_position (0)
178 , _export_started (false)
179 , _export_rolling (false)
180 , _pre_export_mmc_enabled (false)
181 , _name (snapshot_name)
183 , _send_qf_mtc (false)
184 , _pframes_since_last_mtc (0)
185 , session_midi_feedback (0)
187 , loop_changing (false)
189 , _session_dir (new SessionDirectory (fullpath))
190 , _current_snapshot_name (snapshot_name)
192 , state_was_pending (false)
193 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
194 , _last_roll_location (0)
195 , _last_roll_or_reversal_location (0)
196 , _last_record_location (0)
197 , pending_locate_roll (false)
198 , pending_locate_frame (0)
199 , pending_locate_flush (false)
200 , pending_abort (false)
201 , pending_auto_loop (false)
202 , _butler (new Butler (*this))
203 , _post_transport_work (0)
204 , cumulative_rf_motion (0)
206 , _locations (new Locations (*this))
208 , outbound_mtc_timecode_frame (0)
209 , next_quarter_frame_to_send (-1)
210 , _frames_per_timecode_frame (0)
211 , _frames_per_hour (0)
212 , _timecode_frames_per_hour (0)
213 , last_timecode_valid (false)
214 , last_timecode_when (0)
215 , _send_timecode_update (false)
227 , ltc_timecode_offset (0)
228 , ltc_timecode_negative_offset (false)
229 , midi_control_ui (0)
231 , _all_route_group (new RouteGroup (*this, "all"))
232 , routes (new RouteList)
233 , _adding_routes_in_progress (false)
234 , destructive_index (0)
235 , solo_update_disabled (false)
236 , default_fade_steepness (0)
237 , default_fade_msecs (0)
238 , _total_free_4k_blocks (0)
239 , _total_free_4k_blocks_uncertain (false)
240 , no_questions_about_missing_files (false)
243 , _bundles (new BundleList)
244 , _bundle_xml_node (0)
248 , click_emphasis_data (0)
250 , click_emphasis_length (0)
251 , _clicks_cleared (0)
252 , _play_range (false)
254 , first_file_data_format_reset (true)
255 , first_file_header_format_reset (true)
256 , have_looped (false)
257 , _have_rec_enabled_track (false)
259 , _suspend_timecode_transmission (0)
260 , _speakers (new Speakers)
262 , ignore_route_processor_changes (false)
268 pre_engine_init (fullpath);
271 if (ensure_engine (sr)) {
273 throw failed_constructor ();
276 if (create (mix_template, bus_profile)) {
278 throw failed_constructor ();
281 /* if a mix template was provided, then ::create() will
282 * have copied it into the session and we need to load it
283 * so that we have the state ready for ::set_state()
284 * after the engine is started.
286 * Note that we do NOT try to get the sample rate from
287 * the template at this time, though doing so would
288 * be easy if we decided this was an appropriate part
292 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
293 throw failed_constructor ();
298 if (load_state (_current_snapshot_name)) {
299 throw failed_constructor ();
302 /* try to get sample rate from XML state so that we
303 * can influence the SR if we set up the audio
308 const XMLProperty* prop;
309 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
310 sr = atoi (prop->value());
314 if (ensure_engine (sr)) {
316 throw failed_constructor ();
320 if (post_engine_init ()) {
322 throw failed_constructor ();
325 store_recent_sessions (_name, _path);
327 bool was_dirty = dirty();
329 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
331 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
332 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
335 DirtyChanged (); /* EMIT SIGNAL */
338 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
339 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
343 /* hook us up to the engine since we are now completely constructed */
345 BootMessage (_("Connect to engine"));
347 _engine.set_session (this);
348 _engine.reset_timebase ();
350 BootMessage (_("Session loading complete"));
363 Session::ensure_engine (uint32_t desired_sample_rate)
365 if (_engine.current_backend() == 0) {
366 /* backend is unknown ... */
367 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
368 if (r.get_value_or (-1) != 0) {
371 } else if (_engine.setup_required()) {
372 /* backend is known, but setup is needed */
373 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
374 if (r.get_value_or (-1) != 0) {
377 } else if (!_engine.running()) {
378 if (_engine.start()) {
383 /* at this point the engine should be running
386 if (!_engine.running()) {
390 return immediately_post_engine ();
395 Session::immediately_post_engine ()
397 /* Do various initializations that should take place directly after we
398 * know that the engine is running, but before we either create a
399 * session or set state for an existing one.
402 if (how_many_dsp_threads () > 1) {
403 /* For now, only create the graph if we are using >1 DSP threads, as
404 it is a bit slower than the old code with 1 thread.
406 _process_graph.reset (new Graph (*this));
409 /* every time we reconnect, recompute worst case output latencies */
411 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
413 if (synced_to_engine()) {
414 _engine.transport_stop ();
417 if (config.get_jack_time_master()) {
418 _engine.transport_locate (_transport_frame);
422 BootMessage (_("Set up LTC"));
424 BootMessage (_("Set up Click"));
426 BootMessage (_("Set up standard connections"));
430 catch (failed_constructor& err) {
440 vector<void*> debug_pointers;
442 /* if we got to here, leaving pending capture state around
446 remove_pending_capture_state ();
448 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
450 /* disconnect from any and all signals that we are connected to */
454 _engine.remove_session ();
456 /* deregister all ports - there will be no process or any other
457 * callbacks from the engine any more.
460 Port::PortDrop (); /* EMIT SIGNAL */
464 /* clear history so that no references to objects are held any more */
468 /* clear state tree so that no references to objects are held any more */
472 /* reset dynamic state version back to default */
474 Stateful::loading_state_version = 0;
476 _butler->drop_references ();
480 delete midi_control_ui;
481 delete _all_route_group;
483 if (click_data != default_click) {
484 delete [] click_data;
487 if (click_emphasis_data != default_click_emphasis) {
488 delete [] click_emphasis_data;
493 /* clear out any pending dead wood from RCU managed objects */
498 AudioDiskstream::free_working_buffers();
500 /* tell everyone who is still standing that we're about to die */
503 /* tell everyone to drop references and delete objects as we go */
505 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
506 RegionFactory::delete_all_regions ();
508 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
510 /* reset these three references to special routes before we do the usual route delete thing */
513 _master_out.reset ();
514 _monitor_out.reset ();
517 RCUWriter<RouteList> writer (routes);
518 boost::shared_ptr<RouteList> r = writer.get_copy ();
520 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
521 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
522 (*i)->drop_references ();
526 /* writer goes out of scope and updates master */
531 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
532 Glib::Threads::Mutex::Lock lm (source_lock);
533 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
534 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
535 i->second->drop_references ();
541 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
542 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
547 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
550 delete _mmc; _mmc = 0;
551 delete _midi_ports; _midi_ports = 0;
552 delete _locations; _locations = 0;
554 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
556 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
557 boost_debug_list_ptrs ();
562 Session::setup_ltc ()
566 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
567 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
569 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
570 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
573 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
574 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
576 reconnect_ltc_input ();
579 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
580 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
583 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
584 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
586 reconnect_ltc_output ();
589 /* fix up names of LTC ports because we don't want the normal
590 * IO style of NAME/TYPE-{in,out}N
593 _ltc_input->nth (0)->set_name (X_("LTC-in"));
594 _ltc_output->nth (0)->set_name (X_("LTC-out"));
598 Session::setup_click ()
601 _click_io.reset (new ClickIO (*this, X_("Click")));
602 _click_gain.reset (new Amp (*this));
603 _click_gain->activate ();
605 setup_click_state (state_tree->root());
607 setup_click_state (0);
612 Session::setup_click_state (const XMLNode* node)
614 const XMLNode* child = 0;
616 if (node && (child = find_named_node (*node, "Click")) != 0) {
618 /* existing state for Click */
621 if (Stateful::loading_state_version < 3000) {
622 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
624 const XMLNodeList& children (child->children());
625 XMLNodeList::const_iterator i = children.begin();
626 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
628 if (i != children.end()) {
629 c = _click_gain->set_state (**i, Stateful::loading_state_version);
635 _clicking = Config->get_clicking ();
639 error << _("could not setup Click I/O") << endmsg;
646 /* default state for Click: dual-mono to first 2 physical outputs */
649 _engine.get_physical_outputs (DataType::AUDIO, outs);
651 for (uint32_t physport = 0; physport < 2; ++physport) {
652 if (outs.size() > physport) {
653 if (_click_io->add_port (outs[physport], this)) {
654 // relax, even though its an error
659 if (_click_io->n_ports () > ChanCount::ZERO) {
660 _clicking = Config->get_clicking ();
666 Session::setup_bundles ()
668 vector<string> inputs[DataType::num_types];
669 vector<string> outputs[DataType::num_types];
670 for (uint32_t i = 0; i < DataType::num_types; ++i) {
671 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
672 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
675 /* Create a set of Bundle objects that map
676 to the physical I/O currently available. We create both
677 mono and stereo bundles, so that the common cases of mono
678 and stereo tracks get bundles to put in their mixer strip
679 in / out menus. There may be a nicer way of achieving that;
680 it doesn't really scale that well to higher channel counts
683 /* mono output bundles */
685 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
687 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
689 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
690 c->add_channel (_("mono"), DataType::AUDIO);
691 c->set_port (0, outputs[DataType::AUDIO][np]);
696 /* stereo output bundles */
698 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
699 if (np + 1 < outputs[DataType::AUDIO].size()) {
701 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
702 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
703 c->add_channel (_("L"), DataType::AUDIO);
704 c->set_port (0, outputs[DataType::AUDIO][np]);
705 c->add_channel (_("R"), DataType::AUDIO);
706 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
712 /* mono input bundles */
714 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
716 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
718 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
719 c->add_channel (_("mono"), DataType::AUDIO);
720 c->set_port (0, inputs[DataType::AUDIO][np]);
725 /* stereo input bundles */
727 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
728 if (np + 1 < inputs[DataType::AUDIO].size()) {
730 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
732 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
733 c->add_channel (_("L"), DataType::AUDIO);
734 c->set_port (0, inputs[DataType::AUDIO][np]);
735 c->add_channel (_("R"), DataType::AUDIO);
736 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
742 /* MIDI input bundles */
744 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
745 string n = inputs[DataType::MIDI][np];
746 boost::erase_first (n, X_("alsa_pcm:"));
748 boost::shared_ptr<Bundle> c (new Bundle (n, false));
749 c->add_channel ("", DataType::MIDI);
750 c->set_port (0, inputs[DataType::MIDI][np]);
754 /* MIDI output bundles */
756 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
757 string n = outputs[DataType::MIDI][np];
758 boost::erase_first (n, X_("alsa_pcm:"));
760 boost::shared_ptr<Bundle> c (new Bundle (n, true));
761 c->add_channel ("", DataType::MIDI);
762 c->set_port (0, outputs[DataType::MIDI][np]);
769 Session::auto_connect_master_bus ()
771 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
775 /* if requested auto-connect the outputs to the first N physical ports.
778 uint32_t limit = _master_out->n_outputs().n_total();
779 vector<string> outputs[DataType::num_types];
781 for (uint32_t i = 0; i < DataType::num_types; ++i) {
782 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
785 for (uint32_t n = 0; n < limit; ++n) {
786 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
788 if (outputs[p->type()].size() > n) {
789 connect_to = outputs[p->type()][n];
792 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
793 if (_master_out->output()->connect (p, connect_to, this)) {
794 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
803 Session::remove_monitor_section ()
809 /* force reversion to Solo-In-Place */
810 Config->set_solo_control_is_listen_control (false);
812 /* if we are auditioning, cancel it ... this is a workaround
813 to a problem (auditioning does not execute the process graph,
814 which is needed to remove routes when using >1 core for processing)
819 /* Hold process lock while doing this so that we don't hear bits and
820 * pieces of audio as we work on each route.
823 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
825 /* Connect tracks to monitor section. Note that in an
826 existing session, the internal sends will already exist, but we want the
827 routes to notice that they connect to the control out specifically.
831 boost::shared_ptr<RouteList> r = routes.reader ();
832 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
834 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
836 if ((*x)->is_monitor()) {
838 } else if ((*x)->is_master()) {
841 (*x)->remove_aux_or_listen (_monitor_out);
846 remove_route (_monitor_out);
847 auto_connect_master_bus ();
850 auditioner->connect ();
855 Session::add_monitor_section ()
859 if (_monitor_out || !_master_out) {
863 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
869 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
870 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
873 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
874 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
875 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
879 add_routes (rl, false, false, false);
881 assert (_monitor_out);
883 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
884 are undefined, at best.
887 uint32_t limit = _monitor_out->n_inputs().n_audio();
891 /* connect the inputs to the master bus outputs. this
892 * represents a separate data feed from the internal sends from
893 * each route. as of jan 2011, it allows the monitor section to
894 * conditionally ignore either the internal sends or the normal
895 * input feed, but we should really find a better way to do
899 _master_out->output()->disconnect (this);
901 for (uint32_t n = 0; n < limit; ++n) {
902 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
903 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
906 string connect_to = o->name();
907 if (_monitor_out->input()->connect (p, connect_to, this)) {
908 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
916 /* if monitor section is not connected, connect it to physical outs
919 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
921 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
923 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
926 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
928 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
929 Config->get_monitor_bus_preferred_bundle())
935 /* Monitor bus is audio only */
937 vector<string> outputs[DataType::num_types];
939 for (uint32_t i = 0; i < DataType::num_types; ++i) {
940 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
943 uint32_t mod = outputs[DataType::AUDIO].size();
944 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
948 for (uint32_t n = 0; n < limit; ++n) {
950 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
952 if (outputs[DataType::AUDIO].size() > (n % mod)) {
953 connect_to = outputs[DataType::AUDIO][n % mod];
956 if (!connect_to.empty()) {
957 if (_monitor_out->output()->connect (p, connect_to, this)) {
958 error << string_compose (
959 _("cannot connect control output %1 to %2"),
970 /* Hold process lock while doing this so that we don't hear bits and
971 * pieces of audio as we work on each route.
974 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
976 /* Connect tracks to monitor section. Note that in an
977 existing session, the internal sends will already exist, but we want the
978 routes to notice that they connect to the control out specifically.
982 boost::shared_ptr<RouteList> rls = routes.reader ();
984 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
986 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
988 if ((*x)->is_monitor()) {
990 } else if ((*x)->is_master()) {
993 (*x)->enable_monitor_send ();
998 auditioner->connect ();
1003 Session::hookup_io ()
1005 /* stop graph reordering notifications from
1006 causing resorts, etc.
1009 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1013 /* we delay creating the auditioner till now because
1014 it makes its own connections to ports.
1018 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1020 throw failed_constructor ();
1022 a->use_new_diskstream ();
1026 catch (failed_constructor& err) {
1027 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1031 /* load bundles, which we may have postponed earlier on */
1032 if (_bundle_xml_node) {
1033 load_bundles (*_bundle_xml_node);
1034 delete _bundle_xml_node;
1037 /* Tell all IO objects to connect themselves together */
1039 IO::enable_connecting ();
1041 /* Now tell all "floating" ports to connect to whatever
1042 they should be connected to.
1045 AudioEngine::instance()->reconnect_ports ();
1047 /* Anyone who cares about input state, wake up and do something */
1049 IOConnectionsComplete (); /* EMIT SIGNAL */
1051 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1053 /* now handle the whole enchilada as if it was one
1054 graph reorder event.
1059 /* update the full solo state, which can't be
1060 correctly determined on a per-route basis, but
1061 needs the global overview that only the session
1065 update_route_solo_state ();
1069 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1071 boost::shared_ptr<Track> track = wp.lock ();
1076 boost::shared_ptr<Playlist> playlist;
1078 if ((playlist = track->playlist()) != 0) {
1079 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1080 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1081 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1086 Session::record_enabling_legal () const
1088 /* this used to be in here, but survey says.... we don't need to restrict it */
1089 // if (record_status() == Recording) {
1093 if (Config->get_all_safe()) {
1100 Session::set_track_monitor_input_status (bool yn)
1102 boost::shared_ptr<RouteList> rl = routes.reader ();
1103 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1104 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1105 if (tr && tr->record_enabled ()) {
1106 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1107 tr->request_input_monitoring (yn);
1113 Session::auto_punch_start_changed (Location* location)
1115 replace_event (SessionEvent::PunchIn, location->start());
1117 if (get_record_enabled() && config.get_punch_in()) {
1118 /* capture start has been changed, so save new pending state */
1119 save_state ("", true);
1124 Session::auto_punch_end_changed (Location* location)
1126 framepos_t when_to_stop = location->end();
1127 // when_to_stop += _worst_output_latency + _worst_input_latency;
1128 replace_event (SessionEvent::PunchOut, when_to_stop);
1132 Session::auto_punch_changed (Location* location)
1134 framepos_t when_to_stop = location->end();
1136 replace_event (SessionEvent::PunchIn, location->start());
1137 //when_to_stop += _worst_output_latency + _worst_input_latency;
1138 replace_event (SessionEvent::PunchOut, when_to_stop);
1141 /** @param loc A loop location.
1142 * @param pos Filled in with the start time of the required fade-out (in session frames).
1143 * @param length Filled in with the length of the required fade-out.
1146 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1148 pos = max (loc->start(), loc->end() - 64);
1149 length = loc->end() - pos;
1153 Session::auto_loop_changed (Location* location)
1155 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1158 auto_loop_declick_range (location, dcp, dcl);
1159 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1161 if (transport_rolling() && play_loop) {
1164 // if (_transport_frame > location->end()) {
1166 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1167 // relocate to beginning of loop
1168 clear_events (SessionEvent::LocateRoll);
1170 request_locate (location->start(), true);
1173 else if (Config->get_seamless_loop() && !loop_changing) {
1175 // schedule a locate-roll to refill the diskstreams at the
1176 // previous loop end
1177 loop_changing = true;
1179 if (location->end() > last_loopend) {
1180 clear_events (SessionEvent::LocateRoll);
1181 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1188 last_loopend = location->end();
1192 Session::set_auto_punch_location (Location* location)
1196 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1197 punch_connections.drop_connections();
1198 existing->set_auto_punch (false, this);
1199 remove_event (existing->start(), SessionEvent::PunchIn);
1200 clear_events (SessionEvent::PunchOut);
1201 auto_punch_location_changed (0);
1206 if (location == 0) {
1210 if (location->end() <= location->start()) {
1211 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1215 punch_connections.drop_connections ();
1217 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1218 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1219 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1221 location->set_auto_punch (true, this);
1223 auto_punch_changed (location);
1225 auto_punch_location_changed (location);
1229 Session::set_auto_loop_location (Location* location)
1233 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1234 loop_connections.drop_connections ();
1235 existing->set_auto_loop (false, this);
1236 remove_event (existing->end(), SessionEvent::AutoLoop);
1239 auto_loop_declick_range (existing, dcp, dcl);
1240 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1241 auto_loop_location_changed (0);
1246 if (location == 0) {
1250 if (location->end() <= location->start()) {
1251 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1255 last_loopend = location->end();
1257 loop_connections.drop_connections ();
1259 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1260 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1261 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1263 location->set_auto_loop (true, this);
1265 /* take care of our stuff first */
1267 auto_loop_changed (location);
1269 /* now tell everyone else */
1271 auto_loop_location_changed (location);
1275 Session::locations_added (Location *)
1281 Session::locations_changed ()
1283 _locations->apply (*this, &Session::handle_locations_changed);
1287 Session::handle_locations_changed (Locations::LocationList& locations)
1289 Locations::LocationList::iterator i;
1291 bool set_loop = false;
1292 bool set_punch = false;
1294 for (i = locations.begin(); i != locations.end(); ++i) {
1298 if (location->is_auto_punch()) {
1299 set_auto_punch_location (location);
1302 if (location->is_auto_loop()) {
1303 set_auto_loop_location (location);
1307 if (location->is_session_range()) {
1308 _session_range_location = location;
1313 set_auto_loop_location (0);
1316 set_auto_punch_location (0);
1323 Session::enable_record ()
1325 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1326 /* no recording at anything except normal speed */
1331 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1333 if (rs == Recording) {
1337 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1339 _last_record_location = _transport_frame;
1340 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1342 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1343 set_track_monitor_input_status (true);
1346 RecordStateChanged ();
1353 Session::disable_record (bool rt_context, bool force)
1357 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1359 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1360 g_atomic_int_set (&_record_status, Disabled);
1361 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1363 if (rs == Recording) {
1364 g_atomic_int_set (&_record_status, Enabled);
1368 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1369 set_track_monitor_input_status (false);
1372 RecordStateChanged (); /* emit signal */
1375 remove_pending_capture_state ();
1381 Session::step_back_from_record ()
1383 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1385 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1386 set_track_monitor_input_status (false);
1389 RecordStateChanged (); /* emit signal */
1394 Session::maybe_enable_record ()
1396 if (_step_editors > 0) {
1400 g_atomic_int_set (&_record_status, Enabled);
1402 /* This function is currently called from somewhere other than an RT thread.
1403 This save_state() call therefore doesn't impact anything. Doing it here
1404 means that we save pending state of which sources the next record will use,
1405 which gives us some chance of recovering from a crash during the record.
1408 save_state ("", true);
1410 if (_transport_speed) {
1411 if (!config.get_punch_in()) {
1415 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1416 RecordStateChanged (); /* EMIT SIGNAL */
1423 Session::audible_frame () const
1429 /* the first of these two possible settings for "offset"
1430 mean that the audible frame is stationary until
1431 audio emerges from the latency compensation
1434 the second means that the audible frame is stationary
1435 until audio would emerge from a physical port
1436 in the absence of any plugin latency compensation
1439 offset = worst_playback_latency ();
1441 if (offset > current_block_size) {
1442 offset -= current_block_size;
1444 /* XXX is this correct? if we have no external
1445 physical connections and everything is internal
1446 then surely this is zero? still, how
1447 likely is that anyway?
1449 offset = current_block_size;
1452 if (synced_to_engine()) {
1453 tf = _engine.transport_frame();
1455 tf = _transport_frame;
1460 if (!non_realtime_work_pending()) {
1464 /* Check to see if we have passed the first guaranteed
1465 audible frame past our last start position. if not,
1466 return that last start point because in terms
1467 of audible frames, we have not moved yet.
1469 `Start position' in this context means the time we last
1470 either started, located, or changed transport direction.
1473 if (_transport_speed > 0.0f) {
1475 if (!play_loop || !have_looped) {
1476 if (tf < _last_roll_or_reversal_location + offset) {
1477 return _last_roll_or_reversal_location;
1485 } else if (_transport_speed < 0.0f) {
1487 /* XXX wot? no backward looping? */
1489 if (tf > _last_roll_or_reversal_location - offset) {
1490 return _last_roll_or_reversal_location;
1502 Session::set_frame_rate (framecnt_t frames_per_second)
1504 /** \fn void Session::set_frame_size(framecnt_t)
1505 the AudioEngine object that calls this guarantees
1506 that it will not be called while we are also in
1507 ::process(). Its fine to do things that block
1511 _base_frame_rate = frames_per_second;
1512 _nominal_frame_rate = frames_per_second;
1518 // XXX we need some equivalent to this, somehow
1519 // SndFileSource::setup_standard_crossfades (frames_per_second);
1523 /* XXX need to reset/reinstantiate all LADSPA plugins */
1527 Session::set_block_size (pframes_t nframes)
1529 /* the AudioEngine guarantees
1530 that it will not be called while we are also in
1531 ::process(). It is therefore fine to do things that block
1536 current_block_size = nframes;
1540 boost::shared_ptr<RouteList> r = routes.reader ();
1542 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1543 (*i)->set_block_size (nframes);
1546 boost::shared_ptr<RouteList> rl = routes.reader ();
1547 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1548 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1550 tr->set_block_size (nframes);
1554 set_worst_io_latencies ();
1560 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1562 boost::shared_ptr<Route> r2;
1564 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1565 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1569 /* make a copy of the existing list of routes that feed r1 */
1571 Route::FedBy existing (r1->fed_by());
1573 /* for each route that feeds r1, recurse, marking it as feeding
1577 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1578 if (!(r2 = i->r.lock ())) {
1579 /* (*i) went away, ignore it */
1583 /* r2 is a route that feeds r1 which somehow feeds base. mark
1584 base as being fed by r2
1587 rbase->add_fed_by (r2, i->sends_only);
1591 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1595 if (r1->feeds (r2) && r2->feeds (r1)) {
1599 /* now recurse, so that we can mark base as being fed by
1600 all routes that feed r2
1603 trace_terminal (r2, rbase);
1610 Session::resort_routes ()
1612 /* don't do anything here with signals emitted
1613 by Routes during initial setup or while we
1614 are being destroyed.
1617 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1622 RCUWriter<RouteList> writer (routes);
1623 boost::shared_ptr<RouteList> r = writer.get_copy ();
1624 resort_routes_using (r);
1625 /* writer goes out of scope and forces update */
1629 boost::shared_ptr<RouteList> rl = routes.reader ();
1630 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1631 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1633 const Route::FedBy& fb ((*i)->fed_by());
1635 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1636 boost::shared_ptr<Route> sf = f->r.lock();
1638 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1646 /** This is called whenever we need to rebuild the graph of how we will process
1648 * @param r List of routes, in any order.
1652 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1654 /* We are going to build a directed graph of our routes;
1655 this is where the edges of that graph are put.
1660 /* Go through all routes doing two things:
1662 * 1. Collect the edges of the route graph. Each of these edges
1663 * is a pair of routes, one of which directly feeds the other
1664 * either by a JACK connection or by an internal send.
1666 * 2. Begin the process of making routes aware of which other
1667 * routes directly or indirectly feed them. This information
1668 * is used by the solo code.
1671 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1673 /* Clear out the route's list of direct or indirect feeds */
1674 (*i)->clear_fed_by ();
1676 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1678 bool via_sends_only;
1680 /* See if this *j feeds *i according to the current state of the JACK
1681 connections and internal sends.
1683 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1684 /* add the edge to the graph (part #1) */
1685 edges.add (*j, *i, via_sends_only);
1686 /* tell the route (for part #2) */
1687 (*i)->add_fed_by (*j, via_sends_only);
1692 /* Attempt a topological sort of the route graph */
1693 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1695 if (sorted_routes) {
1696 /* We got a satisfactory topological sort, so there is no feedback;
1699 Note: the process graph rechain does not require a
1700 topologically-sorted list, but hey ho.
1702 if (_process_graph) {
1703 _process_graph->rechain (sorted_routes, edges);
1706 _current_route_graph = edges;
1708 /* Complete the building of the routes' lists of what directly
1709 or indirectly feeds them.
1711 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1712 trace_terminal (*i, *i);
1715 *r = *sorted_routes;
1718 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1719 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1720 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1721 (*i)->name(), (*i)->order_key ()));
1725 SuccessfulGraphSort (); /* EMIT SIGNAL */
1728 /* The topological sort failed, so we have a problem. Tell everyone
1729 and stick to the old graph; this will continue to be processed, so
1730 until the feedback is fixed, what is played back will not quite
1731 reflect what is actually connected. Note also that we do not
1732 do trace_terminal here, as it would fail due to an endless recursion,
1733 so the solo code will think that everything is still connected
1737 FeedbackDetected (); /* EMIT SIGNAL */
1742 /** Find a route name starting with \a base, maybe followed by the
1743 * lowest \a id. \a id will always be added if \a definitely_add_number
1744 * is true on entry; otherwise it will only be added if required
1745 * to make the name unique.
1747 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1748 * The available route name with the lowest ID will be used, and \a id
1749 * will be set to the ID.
1751 * \return false if a route name could not be found, and \a track_name
1752 * and \a id do not reflect a free route name.
1755 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1757 if (!definitely_add_number && route_by_name (base) == 0) {
1758 /* juse use the base */
1759 snprintf (name, name_len, "%s", base.c_str());
1764 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1766 if (route_by_name (name) == 0) {
1772 } while (id < (UINT_MAX-1));
1777 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1779 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1781 in = ChanCount::ZERO;
1782 out = ChanCount::ZERO;
1784 boost::shared_ptr<RouteList> r = routes.reader ();
1786 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1787 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1788 if (tr && !tr->is_auditioner()) {
1789 in += tr->n_inputs();
1790 out += tr->n_outputs();
1795 /** Caller must not hold process lock
1796 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1797 * @param instrument plugin info for the instrument to insert pre-fader, if any
1799 list<boost::shared_ptr<MidiTrack> >
1800 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1801 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1803 char track_name[32];
1804 uint32_t track_id = 0;
1806 RouteList new_routes;
1807 list<boost::shared_ptr<MidiTrack> > ret;
1809 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1812 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1813 error << "cannot find name for new midi track" << endmsg;
1817 boost::shared_ptr<MidiTrack> track;
1820 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1822 if (track->init ()) {
1826 track->use_new_diskstream();
1828 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1829 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1832 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1833 if (track->input()->ensure_io (input, false, this)) {
1834 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1838 if (track->output()->ensure_io (output, false, this)) {
1839 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1844 track->non_realtime_input_change();
1847 route_group->add (track);
1850 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1852 if (Config->get_remote_model() == UserOrdered) {
1853 track->set_remote_control_id (next_control_id());
1856 new_routes.push_back (track);
1857 ret.push_back (track);
1860 catch (failed_constructor &err) {
1861 error << _("Session: could not create new midi track.") << endmsg;
1865 catch (AudioEngine::PortRegistrationFailure& pfe) {
1867 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;
1875 if (!new_routes.empty()) {
1876 add_routes (new_routes, true, true, true);
1879 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1880 PluginPtr plugin = instrument->load (*this);
1881 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1882 (*r)->add_processor (p, PreFader);
1892 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1894 boost::shared_ptr<Route> midi_track (wmt.lock());
1900 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1902 if (change.after.n_audio() <= change.before.n_audio()) {
1906 /* new audio ports: make sure the audio goes somewhere useful,
1907 unless the user has no-auto-connect selected.
1909 The existing ChanCounts don't matter for this call as they are only
1910 to do with matching input and output indices, and we are only changing
1916 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1920 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1921 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1922 * @param output_start As \a input_start, but for outputs.
1925 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1926 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1928 if (!IO::connecting_legal) {
1932 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1938 /* If both inputs and outputs are auto-connected to physical ports,
1939 use the max of input and output offsets to ensure auto-connected
1940 port numbers always match up (e.g. the first audio input and the
1941 first audio output of the route will have the same physical
1942 port number). Otherwise just use the lowest input or output
1946 DEBUG_TRACE (DEBUG::Graph,
1947 string_compose("Auto-connect: existing in = %1 out = %2\n",
1948 existing_inputs, existing_outputs));
1950 const bool in_out_physical =
1951 (Config->get_input_auto_connect() & AutoConnectPhysical)
1952 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1955 const ChanCount in_offset = in_out_physical
1956 ? ChanCount::max(existing_inputs, existing_outputs)
1959 const ChanCount out_offset = in_out_physical
1960 ? ChanCount::max(existing_inputs, existing_outputs)
1963 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1964 vector<string> physinputs;
1965 vector<string> physoutputs;
1967 _engine.get_physical_outputs (*t, physoutputs);
1968 _engine.get_physical_inputs (*t, physinputs);
1970 if (!physinputs.empty() && connect_inputs) {
1971 uint32_t nphysical_in = physinputs.size();
1973 DEBUG_TRACE (DEBUG::Graph,
1974 string_compose("There are %1 physical inputs of type %2\n",
1977 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1980 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1981 DEBUG_TRACE (DEBUG::Graph,
1982 string_compose("Get index %1 + %2 % %3 = %4\n",
1983 in_offset.get(*t), i, nphysical_in,
1984 (in_offset.get(*t) + i) % nphysical_in));
1985 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1988 DEBUG_TRACE (DEBUG::Graph,
1989 string_compose("Connect route %1 IN to %2\n",
1990 route->name(), port));
1992 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1996 ChanCount one_added (*t, 1);
1997 existing_inputs += one_added;
2001 if (!physoutputs.empty()) {
2002 uint32_t nphysical_out = physoutputs.size();
2003 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2006 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2007 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2008 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2009 /* master bus is audio only */
2010 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2011 port = _master_out->input()->ports().port(*t,
2012 i % _master_out->input()->n_ports().get(*t))->name();
2016 DEBUG_TRACE (DEBUG::Graph,
2017 string_compose("Connect route %1 OUT to %2\n",
2018 route->name(), port));
2020 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2024 ChanCount one_added (*t, 1);
2025 existing_outputs += one_added;
2031 /** Caller must not hold process lock
2032 * @param name_template string to use for the start of the name, or "" to use "Audio".
2034 list< boost::shared_ptr<AudioTrack> >
2035 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2036 uint32_t how_many, string name_template)
2038 char track_name[32];
2039 uint32_t track_id = 0;
2041 RouteList new_routes;
2042 list<boost::shared_ptr<AudioTrack> > ret;
2044 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2047 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2048 error << "cannot find name for new audio track" << endmsg;
2052 boost::shared_ptr<AudioTrack> track;
2055 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2057 if (track->init ()) {
2061 track->use_new_diskstream();
2063 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2064 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2067 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2069 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2070 error << string_compose (
2071 _("cannot configure %1 in/%2 out configuration for new audio track"),
2072 input_channels, output_channels)
2077 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2078 error << string_compose (
2079 _("cannot configure %1 in/%2 out configuration for new audio track"),
2080 input_channels, output_channels)
2087 route_group->add (track);
2090 track->non_realtime_input_change();
2092 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2093 if (Config->get_remote_model() == UserOrdered) {
2094 track->set_remote_control_id (next_control_id());
2097 new_routes.push_back (track);
2098 ret.push_back (track);
2101 catch (failed_constructor &err) {
2102 error << _("Session: could not create new audio track.") << endmsg;
2106 catch (AudioEngine::PortRegistrationFailure& pfe) {
2108 error << pfe.what() << endmsg;
2116 if (!new_routes.empty()) {
2117 add_routes (new_routes, true, true, true);
2123 /** Caller must not hold process lock.
2124 * @param name_template string to use for the start of the name, or "" to use "Bus".
2127 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2130 uint32_t bus_id = 0;
2134 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2137 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2138 error << "cannot find name for new audio bus" << endmsg;
2143 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2149 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2150 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2153 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2155 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2156 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2157 input_channels, output_channels)
2163 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2164 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2165 input_channels, output_channels)
2172 route_group->add (bus);
2174 if (Config->get_remote_model() == UserOrdered) {
2175 bus->set_remote_control_id (next_control_id());
2178 bus->add_internal_return ();
2180 ret.push_back (bus);
2186 catch (failed_constructor &err) {
2187 error << _("Session: could not create new audio route.") << endmsg;
2191 catch (AudioEngine::PortRegistrationFailure& pfe) {
2192 error << pfe.what() << endmsg;
2202 add_routes (ret, false, true, true); // autoconnect outputs only
2210 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2213 uint32_t control_id;
2215 uint32_t number = 0;
2216 const uint32_t being_added = how_many;
2218 if (!tree.read (template_path.c_str())) {
2222 XMLNode* node = tree.root();
2224 IO::disable_connecting ();
2226 control_id = next_control_id ();
2230 XMLNode node_copy (*node);
2232 /* Remove IDs of everything so that new ones are used */
2233 node_copy.remove_property_recursively (X_("id"));
2238 if (!name_base.empty()) {
2240 /* if we're adding more than one routes, force
2241 * all the names of the new routes to be
2242 * numbered, via the final parameter.
2245 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2246 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2252 string const route_name = node_copy.property(X_("name"))->value ();
2254 /* generate a new name by adding a number to the end of the template name */
2255 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2256 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2261 /* set this name in the XML description that we are about to use */
2262 Route::set_name_in_state (node_copy, name);
2264 /* trim bitslots from listen sends so that new ones are used */
2265 XMLNodeList children = node_copy.children ();
2266 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2267 if ((*i)->name() == X_("Processor")) {
2268 XMLProperty* role = (*i)->property (X_("role"));
2269 if (role && role->value() == X_("Listen")) {
2270 (*i)->remove_property (X_("bitslot"));
2275 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2278 error << _("Session: cannot create track/bus from template description") << endmsg;
2282 if (boost::dynamic_pointer_cast<Track>(route)) {
2283 /* force input/output change signals so that the new diskstream
2284 picks up the configuration of the route. During session
2285 loading this normally happens in a different way.
2288 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2290 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2291 change.after = route->input()->n_ports();
2292 route->input()->changed (change, this);
2293 change.after = route->output()->n_ports();
2294 route->output()->changed (change, this);
2297 route->set_remote_control_id (control_id);
2300 ret.push_back (route);
2303 catch (failed_constructor &err) {
2304 error << _("Session: could not create new route from template") << endmsg;
2308 catch (AudioEngine::PortRegistrationFailure& pfe) {
2309 error << pfe.what() << endmsg;
2318 add_routes (ret, true, true, true);
2319 IO::enable_connecting ();
2326 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2329 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2330 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2333 error << _("Adding new tracks/busses failed") << endmsg;
2338 update_latency (true);
2339 update_latency (false);
2344 save_state (_current_snapshot_name);
2347 RouteAdded (new_routes); /* EMIT SIGNAL */
2351 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2353 ChanCount existing_inputs;
2354 ChanCount existing_outputs;
2355 uint32_t order = next_control_id();
2357 if (_order_hint != 0) {
2358 order = _order_hint;
2362 count_existing_track_channels (existing_inputs, existing_outputs);
2365 RCUWriter<RouteList> writer (routes);
2366 boost::shared_ptr<RouteList> r = writer.get_copy ();
2367 r->insert (r->end(), new_routes.begin(), new_routes.end());
2369 /* if there is no control out and we're not in the middle of loading,
2370 resort the graph here. if there is a control out, we will resort
2371 toward the end of this method. if we are in the middle of loading,
2372 we will resort when done.
2375 if (!_monitor_out && IO::connecting_legal) {
2376 resort_routes_using (r);
2380 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2382 boost::weak_ptr<Route> wpr (*x);
2383 boost::shared_ptr<Route> r (*x);
2385 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2386 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2387 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2388 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2389 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2390 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2392 if (r->is_master()) {
2396 if (r->is_monitor()) {
2400 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2402 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2403 track_playlist_changed (boost::weak_ptr<Track> (tr));
2404 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2406 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2408 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2409 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2414 if (input_auto_connect || output_auto_connect) {
2415 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2418 /* order keys are a GUI responsibility but we need to set up
2419 reasonable defaults because they also affect the remote control
2420 ID in most situations.
2423 if (!r->has_order_key ()) {
2424 if (r->is_auditioner()) {
2425 /* use an arbitrarily high value */
2426 r->set_order_key (UINT_MAX);
2428 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2429 r->set_order_key (order);
2437 if (_monitor_out && IO::connecting_legal) {
2438 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2440 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2441 if ((*x)->is_monitor()) {
2443 } else if ((*x)->is_master()) {
2446 (*x)->enable_monitor_send ();
2453 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2455 boost::shared_ptr<RouteList> r = routes.reader ();
2456 boost::shared_ptr<Send> s;
2458 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2459 if ((s = (*i)->internal_send_for (dest)) != 0) {
2460 s->amp()->gain_control()->set_value (0.0);
2466 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2468 boost::shared_ptr<RouteList> r = routes.reader ();
2469 boost::shared_ptr<Send> s;
2471 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2472 if ((s = (*i)->internal_send_for (dest)) != 0) {
2473 s->amp()->gain_control()->set_value (1.0);
2479 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2481 boost::shared_ptr<RouteList> r = routes.reader ();
2482 boost::shared_ptr<Send> s;
2484 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2485 if ((s = (*i)->internal_send_for (dest)) != 0) {
2486 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2491 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2493 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2495 boost::shared_ptr<RouteList> r = routes.reader ();
2496 boost::shared_ptr<RouteList> t (new RouteList);
2498 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2499 /* no MIDI sends because there are no MIDI busses yet */
2500 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2505 add_internal_sends (dest, p, t);
2509 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2511 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2512 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2517 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2519 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2523 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2525 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2529 if (!dest->internal_return()) {
2530 dest->add_internal_return ();
2533 sender->add_aux_send (dest, before);
2539 Session::remove_route (boost::shared_ptr<Route> route)
2541 if (route == _master_out) {
2545 route->set_solo (false, this);
2548 RCUWriter<RouteList> writer (routes);
2549 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2553 /* deleting the master out seems like a dumb
2554 idea, but its more of a UI policy issue
2558 if (route == _master_out) {
2559 _master_out = boost::shared_ptr<Route> ();
2562 if (route == _monitor_out) {
2563 _monitor_out.reset ();
2566 /* writer goes out of scope, forces route list update */
2569 update_route_solo_state ();
2571 // We need to disconnect the route's inputs and outputs
2573 route->input()->disconnect (0);
2574 route->output()->disconnect (0);
2576 /* if the route had internal sends sending to it, remove them */
2577 if (route->internal_return()) {
2579 boost::shared_ptr<RouteList> r = routes.reader ();
2580 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2581 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2583 (*i)->remove_processor (s);
2588 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2589 if (mt && mt->step_editing()) {
2590 if (_step_editors > 0) {
2595 update_latency_compensation ();
2598 /* Re-sort routes to remove the graph's current references to the one that is
2599 * going away, then flush old references out of the graph.
2603 if (_process_graph) {
2604 _process_graph->clear_other_chain ();
2607 /* get rid of it from the dead wood collection in the route list manager */
2609 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2613 /* try to cause everyone to drop their references */
2615 route->drop_references ();
2617 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2619 /* save the new state of the world */
2621 if (save_state (_current_snapshot_name)) {
2622 save_history (_current_snapshot_name);
2627 Session::route_mute_changed (void* /*src*/)
2633 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2635 boost::shared_ptr<Route> route = wpr.lock();
2637 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2641 if (route->listening_via_monitor ()) {
2643 if (Config->get_exclusive_solo()) {
2644 /* new listen: disable all other listen */
2645 boost::shared_ptr<RouteList> r = routes.reader ();
2646 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2647 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2650 (*i)->set_listen (false, this);
2656 } else if (_listen_cnt > 0) {
2661 update_route_solo_state ();
2664 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2666 boost::shared_ptr<Route> route = wpr.lock ();
2669 /* should not happen */
2670 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2674 bool send_changed = false;
2676 if (route->solo_isolated()) {
2677 if (_solo_isolated_cnt == 0) {
2678 send_changed = true;
2680 _solo_isolated_cnt++;
2681 } else if (_solo_isolated_cnt > 0) {
2682 _solo_isolated_cnt--;
2683 if (_solo_isolated_cnt == 0) {
2684 send_changed = true;
2689 IsolatedChanged (); /* EMIT SIGNAL */
2694 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2696 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2698 if (!self_solo_change) {
2699 // session doesn't care about changes to soloed-by-others
2703 if (solo_update_disabled) {
2705 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2709 boost::shared_ptr<Route> route = wpr.lock ();
2712 boost::shared_ptr<RouteList> r = routes.reader ();
2715 if (route->self_soloed()) {
2721 RouteGroup* rg = route->route_group ();
2722 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2724 if (delta == 1 && Config->get_exclusive_solo()) {
2726 /* new solo: disable all other solos, but not the group if its solo-enabled */
2728 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2729 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2730 (leave_group_alone && ((*i)->route_group() == rg))) {
2733 (*i)->set_solo (false, this);
2737 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2739 solo_update_disabled = true;
2741 RouteList uninvolved;
2743 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2745 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2746 bool via_sends_only;
2747 bool in_signal_flow;
2749 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2750 (leave_group_alone && ((*i)->route_group() == rg))) {
2754 in_signal_flow = false;
2756 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2758 if ((*i)->feeds (route, &via_sends_only)) {
2759 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2760 if (!via_sends_only) {
2761 if (!route->soloed_by_others_upstream()) {
2762 (*i)->mod_solo_by_others_downstream (delta);
2765 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2767 in_signal_flow = true;
2769 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2772 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2774 if (route->feeds (*i, &via_sends_only)) {
2775 /* propagate solo upstream only if routing other than
2776 sends is involved, but do consider the other route
2777 (*i) to be part of the signal flow even if only
2780 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2784 route->soloed_by_others_downstream(),
2785 route->soloed_by_others_upstream()));
2786 if (!via_sends_only) {
2787 if (!route->soloed_by_others_downstream()) {
2788 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2789 (*i)->mod_solo_by_others_upstream (delta);
2791 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2794 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2796 in_signal_flow = true;
2798 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2801 if (!in_signal_flow) {
2802 uninvolved.push_back (*i);
2806 solo_update_disabled = false;
2807 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2809 update_route_solo_state (r);
2811 /* now notify that the mute state of the routes not involved in the signal
2812 pathway of the just-solo-changed route may have altered.
2815 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2816 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2817 (*i)->mute_changed (this);
2820 SoloChanged (); /* EMIT SIGNAL */
2825 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2827 /* now figure out if anything that matters is soloed (or is "listening")*/
2829 bool something_soloed = false;
2830 uint32_t listeners = 0;
2831 uint32_t isolated = 0;
2834 r = routes.reader();
2837 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2838 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2839 something_soloed = true;
2842 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2843 if (Config->get_solo_control_is_listen_control()) {
2846 (*i)->set_listen (false, this);
2850 if ((*i)->solo_isolated()) {
2855 if (something_soloed != _non_soloed_outs_muted) {
2856 _non_soloed_outs_muted = something_soloed;
2857 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2860 _listen_cnt = listeners;
2862 if (isolated != _solo_isolated_cnt) {
2863 _solo_isolated_cnt = isolated;
2864 IsolatedChanged (); /* EMIT SIGNAL */
2867 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2868 something_soloed, listeners, isolated));
2871 boost::shared_ptr<RouteList>
2872 Session::get_routes_with_internal_returns() const
2874 boost::shared_ptr<RouteList> r = routes.reader ();
2875 boost::shared_ptr<RouteList> rl (new RouteList);
2877 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2878 if ((*i)->internal_return ()) {
2886 Session::io_name_is_legal (const std::string& name)
2888 boost::shared_ptr<RouteList> r = routes.reader ();
2890 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2891 if ((*i)->name() == name) {
2895 if ((*i)->has_io_processor_named (name)) {
2904 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2907 vector<string> connections;
2909 /* if we are passed only a single route and we're not told to turn
2910 * others off, then just do the simple thing.
2913 if (flip_others == false && rl->size() == 1) {
2914 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2916 mt->set_input_active (onoff);
2921 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2923 PortSet& ps ((*rt)->input()->ports());
2925 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2926 p->get_connections (connections);
2929 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2930 routes_using_input_from (*s, rl2);
2933 /* scan all relevant routes to see if others are on or off */
2935 bool others_are_already_on = false;
2937 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2939 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2945 if ((*r) != (*rt)) {
2946 if (mt->input_active()) {
2947 others_are_already_on = true;
2950 /* this one needs changing */
2951 mt->set_input_active (onoff);
2957 /* globally reverse other routes */
2959 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2960 if ((*r) != (*rt)) {
2961 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2963 mt->set_input_active (!others_are_already_on);
2972 Session::routes_using_input_from (const string& str, RouteList& rl)
2974 boost::shared_ptr<RouteList> r = routes.reader();
2976 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2977 if ((*i)->input()->connected_to (str)) {
2983 boost::shared_ptr<Route>
2984 Session::route_by_name (string name)
2986 boost::shared_ptr<RouteList> r = routes.reader ();
2988 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2989 if ((*i)->name() == name) {
2994 return boost::shared_ptr<Route> ((Route*) 0);
2997 boost::shared_ptr<Route>
2998 Session::route_by_id (PBD::ID id)
3000 boost::shared_ptr<RouteList> r = routes.reader ();
3002 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3003 if ((*i)->id() == id) {
3008 return boost::shared_ptr<Route> ((Route*) 0);
3011 boost::shared_ptr<Track>
3012 Session::track_by_diskstream_id (PBD::ID id)
3014 boost::shared_ptr<RouteList> r = routes.reader ();
3016 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3017 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3018 if (t && t->using_diskstream_id (id)) {
3023 return boost::shared_ptr<Track> ();
3026 boost::shared_ptr<Route>
3027 Session::route_by_remote_id (uint32_t id)
3029 boost::shared_ptr<RouteList> r = routes.reader ();
3031 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3032 if ((*i)->remote_control_id() == id) {
3037 return boost::shared_ptr<Route> ((Route*) 0);
3041 Session::playlist_region_added (boost::weak_ptr<Region> w)
3043 boost::shared_ptr<Region> r = w.lock ();
3048 /* These are the operations that are currently in progress... */
3049 list<GQuark> curr = _current_trans_quarks;
3052 /* ...and these are the operations during which we want to update
3053 the session range location markers.
3056 ops.push_back (Operations::capture);
3057 ops.push_back (Operations::paste);
3058 ops.push_back (Operations::duplicate_region);
3059 ops.push_back (Operations::insert_file);
3060 ops.push_back (Operations::insert_region);
3061 ops.push_back (Operations::drag_region_brush);
3062 ops.push_back (Operations::region_drag);
3063 ops.push_back (Operations::selection_grab);
3064 ops.push_back (Operations::region_fill);
3065 ops.push_back (Operations::fill_selection);
3066 ops.push_back (Operations::create_region);
3067 ops.push_back (Operations::region_copy);
3068 ops.push_back (Operations::fixed_time_region_copy);
3071 /* See if any of the current operations match the ones that we want */
3073 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3075 /* If so, update the session range markers */
3077 maybe_update_session_range (r->position (), r->last_frame ());
3081 /** Update the session range markers if a is before the current start or
3082 * b is after the current end.
3085 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3087 if (_state_of_the_state & Loading) {
3091 if (_session_range_location == 0) {
3093 add_session_range_location (a, b);
3097 if (a < _session_range_location->start()) {
3098 _session_range_location->set_start (a);
3101 if (b > _session_range_location->end()) {
3102 _session_range_location->set_end (b);
3108 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3110 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3111 maybe_update_session_range (i->to, i->to + i->length);
3116 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3118 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3119 maybe_update_session_range (i->from, i->to);
3123 /* Region management */
3125 boost::shared_ptr<Region>
3126 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3128 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3129 RegionFactory::RegionMap::const_iterator i;
3130 boost::shared_ptr<Region> region;
3132 Glib::Threads::Mutex::Lock lm (region_lock);
3134 for (i = regions.begin(); i != regions.end(); ++i) {
3138 if (region->whole_file()) {
3140 if (child->source_equivalent (region)) {
3146 return boost::shared_ptr<Region> ();
3150 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3152 set<boost::shared_ptr<Region> > relevant_regions;
3154 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3155 RegionFactory::get_regions_using_source (*s, relevant_regions);
3158 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3159 set<boost::shared_ptr<Region> >::iterator tmp;
3164 playlists->destroy_region (*r);
3165 RegionFactory::map_remove (*r);
3167 (*r)->drop_sources ();
3168 (*r)->drop_references ();
3170 relevant_regions.erase (r);
3175 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3178 Glib::Threads::Mutex::Lock ls (source_lock);
3179 /* remove from the main source list */
3180 sources.erase ((*s)->id());
3183 (*s)->mark_for_remove ();
3184 (*s)->drop_references ();
3193 Session::remove_last_capture ()
3195 list<boost::shared_ptr<Source> > srcs;
3197 boost::shared_ptr<RouteList> rl = routes.reader ();
3198 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3199 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3204 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3207 srcs.insert (srcs.end(), l.begin(), l.end());
3212 destroy_sources (srcs);
3214 save_state (_current_snapshot_name);
3219 /* Source Management */
3222 Session::add_source (boost::shared_ptr<Source> source)
3224 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3225 pair<SourceMap::iterator,bool> result;
3227 entry.first = source->id();
3228 entry.second = source;
3231 Glib::Threads::Mutex::Lock lm (source_lock);
3232 result = sources.insert (entry);
3235 if (result.second) {
3237 /* yay, new source */
3239 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3242 if (!fs->within_session()) {
3243 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3249 boost::shared_ptr<AudioFileSource> afs;
3251 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3252 if (Config->get_auto_analyse_audio()) {
3253 Analyser::queue_source_for_analysis (source, false);
3257 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3262 Session::remove_source (boost::weak_ptr<Source> src)
3264 if (_state_of_the_state & Deletion) {
3268 SourceMap::iterator i;
3269 boost::shared_ptr<Source> source = src.lock();
3276 Glib::Threads::Mutex::Lock lm (source_lock);
3278 if ((i = sources.find (source->id())) != sources.end()) {
3283 if (!(_state_of_the_state & InCleanup)) {
3285 /* save state so we don't end up with a session file
3286 referring to non-existent sources.
3289 save_state (_current_snapshot_name);
3293 boost::shared_ptr<Source>
3294 Session::source_by_id (const PBD::ID& id)
3296 Glib::Threads::Mutex::Lock lm (source_lock);
3297 SourceMap::iterator i;
3298 boost::shared_ptr<Source> source;
3300 if ((i = sources.find (id)) != sources.end()) {
3307 boost::shared_ptr<AudioFileSource>
3308 Session::source_by_path_and_channel (const string& path, uint16_t chn) const
3310 /* Restricted to audio files because only audio sources have channel
3314 Glib::Threads::Mutex::Lock lm (source_lock);
3316 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3317 boost::shared_ptr<AudioFileSource> afs
3318 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3320 if (afs && afs->path() == path && chn == afs->channel()) {
3325 return boost::shared_ptr<AudioFileSource>();
3328 boost::shared_ptr<MidiSource>
3329 Session::source_by_path (const std::string& path) const
3331 /* Restricted to MIDI files because audio sources require a channel
3332 for unique identification, in addition to a path.
3335 Glib::Threads::Mutex::Lock lm (source_lock);
3337 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3338 boost::shared_ptr<MidiSource> ms
3339 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3340 boost::shared_ptr<FileSource> fs
3341 = boost::dynamic_pointer_cast<FileSource>(s->second);
3343 if (ms && fs && fs->path() == path) {
3348 return boost::shared_ptr<MidiSource>();
3352 Session::count_sources_by_origin (const string& path)
3355 Glib::Threads::Mutex::Lock lm (source_lock);
3357 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3358 boost::shared_ptr<FileSource> fs
3359 = boost::dynamic_pointer_cast<FileSource>(i->second);
3361 if (fs && fs->origin() == path) {
3369 /** Return the full path (in some session directory) for a new within-session source.
3370 * \a name must be a session-unique name that does not contain slashes
3371 * (e.g. as returned by new_*_source_name)
3374 Session::new_source_path_from_name (DataType type, const string& name)
3376 assert(name.find("/") == string::npos);
3378 SessionDirectory sdir(get_best_session_directory_for_new_source());
3381 if (type == DataType::AUDIO) {
3382 p = sdir.sound_path();
3383 } else if (type == DataType::MIDI) {
3384 p = sdir.midi_path();
3386 error << "Unknown source type, unable to create file path" << endmsg;
3390 return Glib::build_filename (p, name);
3394 Session::peak_path (string base) const
3396 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3399 /** Return a unique name based on \a base for a new internal audio source */
3401 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3404 char buf[PATH_MAX+1];
3405 const uint32_t limit = 10000;
3407 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3410 legalized = legalize_for_path (base);
3412 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3413 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3415 vector<space_and_path>::iterator i;
3416 uint32_t existing = 0;
3418 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3423 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3424 cnt, legalized.c_str(), ext.c_str());
3425 } else if (nchan == 2) {
3427 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3428 cnt, legalized.c_str(), ext.c_str());
3430 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3431 cnt, legalized.c_str(), ext.c_str());
3433 } else if (nchan < 26) {
3434 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3435 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3437 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3438 cnt, legalized.c_str(), ext.c_str());
3444 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3445 } else if (nchan == 2) {
3447 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3449 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3451 } else if (nchan < 26) {
3452 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3454 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3458 SessionDirectory sdir((*i).path);
3460 string spath = sdir.sound_path();
3462 /* note that we search *without* the extension so that
3463 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3464 in the event that this new name is required for
3465 a file format change.
3468 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3474 if (existing == 0) {
3479 error << string_compose(
3480 _("There are already %1 recordings for %2, which I consider too many."),
3481 limit, base) << endmsg;
3483 throw failed_constructor();
3487 return Glib::path_get_basename (buf);
3490 /** Create a new within-session audio source */
3491 boost::shared_ptr<AudioFileSource>
3492 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3494 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3495 const string path = new_source_path_from_name(DataType::AUDIO, name);
3497 return boost::dynamic_pointer_cast<AudioFileSource> (
3498 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3501 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3503 Session::new_midi_source_name (const string& owner_name)
3506 char buf[PATH_MAX+1];
3507 const uint32_t limit = 10000;
3509 string possible_name;
3512 legalized = legalize_for_path (owner_name);
3514 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3516 for (cnt = 1; cnt <= limit; ++cnt) {
3518 vector<space_and_path>::iterator i;
3519 uint32_t existing = 0;
3521 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3523 SessionDirectory sdir((*i).path);
3525 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3526 possible_name = buf;
3528 std::string possible_path = Glib::build_filename (sdir.midi_path(), possible_name);
3530 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3534 if (source_by_path (possible_path)) {
3539 if (existing == 0) {
3544 error << string_compose(
3545 _("There are already %1 recordings for %2, which I consider too many."),
3546 limit, owner_name) << endmsg;
3548 throw failed_constructor();
3552 return possible_name;
3556 /** Create a new within-session MIDI source */
3557 boost::shared_ptr<MidiSource>
3558 Session::create_midi_source_for_session (string const & basic_name)
3563 name = new_midi_source_name (basic_name);
3566 const string path = new_source_path_from_name (DataType::MIDI, name);
3568 return boost::dynamic_pointer_cast<SMFSource> (
3569 SourceFactory::createWritable (
3570 DataType::MIDI, *this, path, false, frame_rate()));
3573 /** Create a new within-session MIDI source */
3574 boost::shared_ptr<MidiSource>
3575 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3577 /* the caller passes in the track the source will be used in,
3578 so that we can keep the numbering sane.
3580 Rationale: a track with the name "Foo" that has had N
3581 captures carried out so far will ALREADY have a write source
3582 named "Foo-N+1.mid" waiting to be used for the next capture.
3584 If we call new_midi_source_name() we will get "Foo-N+2". But
3585 there is no region corresponding to "Foo-N+1", so when
3586 "Foo-N+2" appears in the track, the gap presents the user
3587 with odd behaviour - why did it skip past Foo-N+1?
3589 We could explain this to the user in some odd way, but
3590 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3593 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3596 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3598 std::string name = track->steal_write_source_name ();
3601 return boost::shared_ptr<MidiSource>();
3604 const string path = new_source_path_from_name (DataType::MIDI, name);
3606 return boost::dynamic_pointer_cast<SMFSource> (
3607 SourceFactory::createWritable (
3608 DataType::MIDI, *this, path, false, frame_rate()));
3613 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3615 if (playlist->hidden()) {
3619 playlists->add (playlist);
3622 playlist->release();
3629 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3631 if (_state_of_the_state & Deletion) {
3635 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3641 playlists->remove (playlist);
3647 Session::set_audition (boost::shared_ptr<Region> r)
3649 pending_audition_region = r;
3650 add_post_transport_work (PostTransportAudition);
3651 _butler->schedule_transport_work ();
3655 Session::audition_playlist ()
3657 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3658 ev->region.reset ();
3663 Session::non_realtime_set_audition ()
3665 assert (pending_audition_region);
3666 auditioner->audition_region (pending_audition_region);
3667 pending_audition_region.reset ();
3668 AuditionActive (true); /* EMIT SIGNAL */
3672 Session::audition_region (boost::shared_ptr<Region> r)
3674 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3680 Session::cancel_audition ()
3682 if (auditioner->auditioning()) {
3683 auditioner->cancel_audition ();
3684 AuditionActive (false); /* EMIT SIGNAL */
3689 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3691 if (a->is_monitor()) {
3694 if (b->is_monitor()) {
3697 return a->order_key () < b->order_key ();
3701 Session::is_auditioning () const
3703 /* can be called before we have an auditioner object */
3705 return auditioner->auditioning();
3712 Session::graph_reordered ()
3714 /* don't do this stuff if we are setting up connections
3715 from a set_state() call or creating new tracks. Ditto for deletion.
3718 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3722 /* every track/bus asked for this to be handled but it was deferred because
3723 we were connecting. do it now.
3726 request_input_change_handling ();
3730 /* force all diskstreams to update their capture offset values to
3731 reflect any changes in latencies within the graph.
3734 boost::shared_ptr<RouteList> rl = routes.reader ();
3735 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3736 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3738 tr->set_capture_offset ();
3743 /** @return Number of frames that there is disk space available to write,
3746 boost::optional<framecnt_t>
3747 Session::available_capture_duration ()
3749 Glib::Threads::Mutex::Lock lm (space_lock);
3751 if (_total_free_4k_blocks_uncertain) {
3752 return boost::optional<framecnt_t> ();
3755 float sample_bytes_on_disk = 4.0; // keep gcc happy
3757 switch (config.get_native_file_data_format()) {
3759 sample_bytes_on_disk = 4.0;
3763 sample_bytes_on_disk = 3.0;
3767 sample_bytes_on_disk = 2.0;
3771 /* impossible, but keep some gcc versions happy */
3772 fatal << string_compose (_("programming error: %1"),
3773 X_("illegal native file data format"))
3778 double scale = 4096.0 / sample_bytes_on_disk;
3780 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3781 return max_framecnt;
3784 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3788 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3791 RCUWriter<BundleList> writer (_bundles);
3792 boost::shared_ptr<BundleList> b = writer.get_copy ();
3793 b->push_back (bundle);
3796 BundleAdded (bundle); /* EMIT SIGNAL */
3802 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3804 bool removed = false;
3807 RCUWriter<BundleList> writer (_bundles);
3808 boost::shared_ptr<BundleList> b = writer.get_copy ();
3809 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3811 if (i != b->end()) {
3818 BundleRemoved (bundle); /* EMIT SIGNAL */
3824 boost::shared_ptr<Bundle>
3825 Session::bundle_by_name (string name) const
3827 boost::shared_ptr<BundleList> b = _bundles.reader ();
3829 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3830 if ((*i)->name() == name) {
3835 return boost::shared_ptr<Bundle> ();
3839 Session::tempo_map_changed (const PropertyChange&)
3843 playlists->update_after_tempo_map_change ();
3845 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3851 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3853 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3854 (*i)->recompute_frames_from_bbt ();
3858 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3859 * the given count with the current block size.
3862 Session::ensure_buffers (ChanCount howmany)
3864 BufferManager::ensure_buffers (howmany);
3868 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3870 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3871 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3876 Session::next_insert_id ()
3878 /* this doesn't really loop forever. just think about it */
3881 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3882 if (!insert_bitset[n]) {
3883 insert_bitset[n] = true;
3889 /* none available, so resize and try again */
3891 insert_bitset.resize (insert_bitset.size() + 16, false);
3896 Session::next_send_id ()
3898 /* this doesn't really loop forever. just think about it */
3901 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3902 if (!send_bitset[n]) {
3903 send_bitset[n] = true;
3909 /* none available, so resize and try again */
3911 send_bitset.resize (send_bitset.size() + 16, false);
3916 Session::next_aux_send_id ()
3918 /* this doesn't really loop forever. just think about it */
3921 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3922 if (!aux_send_bitset[n]) {
3923 aux_send_bitset[n] = true;
3929 /* none available, so resize and try again */
3931 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3936 Session::next_return_id ()
3938 /* this doesn't really loop forever. just think about it */
3941 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3942 if (!return_bitset[n]) {
3943 return_bitset[n] = true;
3949 /* none available, so resize and try again */
3951 return_bitset.resize (return_bitset.size() + 16, false);
3956 Session::mark_send_id (uint32_t id)
3958 if (id >= send_bitset.size()) {
3959 send_bitset.resize (id+16, false);
3961 if (send_bitset[id]) {
3962 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3964 send_bitset[id] = true;
3968 Session::mark_aux_send_id (uint32_t id)
3970 if (id >= aux_send_bitset.size()) {
3971 aux_send_bitset.resize (id+16, false);
3973 if (aux_send_bitset[id]) {
3974 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
3976 aux_send_bitset[id] = true;
3980 Session::mark_return_id (uint32_t id)
3982 if (id >= return_bitset.size()) {
3983 return_bitset.resize (id+16, false);
3985 if (return_bitset[id]) {
3986 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3988 return_bitset[id] = true;
3992 Session::mark_insert_id (uint32_t id)
3994 if (id >= insert_bitset.size()) {
3995 insert_bitset.resize (id+16, false);
3997 if (insert_bitset[id]) {
3998 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4000 insert_bitset[id] = true;
4004 Session::unmark_send_id (uint32_t id)
4006 if (id < send_bitset.size()) {
4007 send_bitset[id] = false;
4012 Session::unmark_aux_send_id (uint32_t id)
4014 if (id < aux_send_bitset.size()) {
4015 aux_send_bitset[id] = false;
4020 Session::unmark_return_id (uint32_t id)
4022 if (id < return_bitset.size()) {
4023 return_bitset[id] = false;
4028 Session::unmark_insert_id (uint32_t id)
4030 if (id < insert_bitset.size()) {
4031 insert_bitset[id] = false;
4036 Session::reset_native_file_format ()
4038 boost::shared_ptr<RouteList> rl = routes.reader ();
4039 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4040 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4042 /* don't save state as we do this, there's no point
4045 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4046 tr->reset_write_sources (false);
4047 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4053 Session::route_name_unique (string n) const
4055 boost::shared_ptr<RouteList> r = routes.reader ();
4057 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4058 if ((*i)->name() == n) {
4067 Session::route_name_internal (string n) const
4069 if (auditioner && auditioner->name() == n) {
4073 if (_click_io && _click_io->name() == n) {
4081 Session::freeze_all (InterThreadInfo& itt)
4083 boost::shared_ptr<RouteList> r = routes.reader ();
4085 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4087 boost::shared_ptr<Track> t;
4089 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4090 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4100 boost::shared_ptr<Region>
4101 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4102 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4103 InterThreadInfo& itt,
4104 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4107 boost::shared_ptr<Region> result;
4108 boost::shared_ptr<Playlist> playlist;
4109 boost::shared_ptr<AudioFileSource> fsource;
4111 char buf[PATH_MAX+1];
4112 ChanCount diskstream_channels (track.n_channels());
4113 framepos_t position;
4114 framecnt_t this_chunk;
4117 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4118 const string sound_dir = sdir.sound_path();
4119 framepos_t len = end - start;
4120 bool need_block_size_reset = false;
4122 ChanCount const max_proc = track.max_processor_streams ();
4125 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4126 end, start) << endmsg;
4130 const framecnt_t chunk_size = (256 * 1024)/4;
4132 // block all process callback handling
4134 block_processing ();
4136 /* call tree *MUST* hold route_lock */
4138 if ((playlist = track.playlist()) == 0) {
4142 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4144 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4146 for (x = 0; x < 99999; ++x) {
4147 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());
4148 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4154 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4159 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4160 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4163 catch (failed_constructor& err) {
4164 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4168 srcs.push_back (fsource);
4171 /* tell redirects that care that we are about to use a much larger
4172 * blocksize. this will flush all plugins too, so that they are ready
4173 * to be used for this process.
4176 need_block_size_reset = true;
4177 track.set_block_size (chunk_size);
4182 /* create a set of reasonably-sized buffers */
4183 buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
4184 buffers.set_count (max_proc);
4186 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4187 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4189 afs->prepare_for_peakfile_writes ();
4192 while (to_do && !itt.cancel) {
4194 this_chunk = min (to_do, chunk_size);
4196 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4201 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4202 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4205 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4211 start += this_chunk;
4212 to_do -= this_chunk;
4214 itt.progress = (float) (1.0 - ((double) to_do / len));
4223 xnow = localtime (&now);
4225 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4226 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4229 afs->update_header (position, *xnow, now);
4230 afs->flush_header ();
4234 /* construct a region to represent the bounced material */
4238 plist.add (Properties::start, 0);
4239 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4240 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4242 result = RegionFactory::create (srcs, plist);
4248 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4249 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4252 afs->mark_for_remove ();
4255 (*src)->drop_references ();
4259 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4260 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4263 afs->done_with_peakfile_writes ();
4268 if (need_block_size_reset) {
4269 track.set_block_size (get_block_size());
4272 unblock_processing ();
4278 Session::gain_automation_buffer() const
4280 return ProcessThread::gain_automation_buffer ();
4284 Session::send_gain_automation_buffer() const
4286 return ProcessThread::send_gain_automation_buffer ();
4290 Session::pan_automation_buffer() const
4292 return ProcessThread::pan_automation_buffer ();
4296 Session::get_silent_buffers (ChanCount count)
4298 return ProcessThread::get_silent_buffers (count);
4302 Session::get_scratch_buffers (ChanCount count, bool silence)
4304 return ProcessThread::get_scratch_buffers (count, silence);
4308 Session::get_route_buffers (ChanCount count, bool silence)
4310 return ProcessThread::get_route_buffers (count, silence);
4315 Session::get_mix_buffers (ChanCount count)
4317 return ProcessThread::get_mix_buffers (count);
4321 Session::ntracks () const
4324 boost::shared_ptr<RouteList> r = routes.reader ();
4326 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4327 if (boost::dynamic_pointer_cast<Track> (*i)) {
4336 Session::nbusses () const
4339 boost::shared_ptr<RouteList> r = routes.reader ();
4341 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4342 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4351 Session::add_automation_list(AutomationList *al)
4353 automation_lists[al->id()] = al;
4356 /** @return true if there is at least one record-enabled track, otherwise false */
4358 Session::have_rec_enabled_track () const
4360 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4363 /** Update the state of our rec-enabled tracks flag */
4365 Session::update_have_rec_enabled_track ()
4367 boost::shared_ptr<RouteList> rl = routes.reader ();
4368 RouteList::iterator i = rl->begin();
4369 while (i != rl->end ()) {
4371 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4372 if (tr && tr->record_enabled ()) {
4379 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4381 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4383 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4384 RecordStateChanged (); /* EMIT SIGNAL */
4389 Session::listen_position_changed ()
4391 boost::shared_ptr<RouteList> r = routes.reader ();
4393 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4394 (*i)->listen_position_changed ();
4399 Session::solo_control_mode_changed ()
4401 /* cancel all solo or all listen when solo control mode changes */
4404 set_solo (get_routes(), false);
4405 } else if (listening()) {
4406 set_listen (get_routes(), false);
4410 /** Called when a property of one of our route groups changes */
4412 Session::route_group_property_changed (RouteGroup* rg)
4414 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4417 /** Called when a route is added to one of our route groups */
4419 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4421 RouteAddedToRouteGroup (rg, r);
4424 /** Called when a route is removed from one of our route groups */
4426 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4428 RouteRemovedFromRouteGroup (rg, r);
4431 boost::shared_ptr<RouteList>
4432 Session::get_routes_with_regions_at (framepos_t const p) const
4434 boost::shared_ptr<RouteList> r = routes.reader ();
4435 boost::shared_ptr<RouteList> rl (new RouteList);
4437 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4438 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4443 boost::shared_ptr<Playlist> pl = tr->playlist ();
4448 if (pl->has_region_at (p)) {
4457 Session::goto_end ()
4459 if (_session_range_location) {
4460 request_locate (_session_range_location->end(), false);
4462 request_locate (0, false);
4467 Session::goto_start ()
4469 if (_session_range_location) {
4470 request_locate (_session_range_location->start(), false);
4472 request_locate (0, false);
4477 Session::current_start_frame () const
4479 return _session_range_location ? _session_range_location->start() : 0;
4483 Session::current_end_frame () const
4485 return _session_range_location ? _session_range_location->end() : 0;
4489 Session::add_session_range_location (framepos_t start, framepos_t end)
4491 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4492 _locations->add (_session_range_location);
4496 Session::step_edit_status_change (bool yn)
4502 send = (_step_editors == 0);
4507 send = (_step_editors == 1);
4510 if (_step_editors > 0) {
4516 StepEditStatusChange (val);
4522 Session::start_time_changed (framepos_t old)
4524 /* Update the auto loop range to match the session range
4525 (unless the auto loop range has been changed by the user)
4528 Location* s = _locations->session_range_location ();
4533 Location* l = _locations->auto_loop_location ();
4535 if (l && l->start() == old) {
4536 l->set_start (s->start(), true);
4541 Session::end_time_changed (framepos_t old)
4543 /* Update the auto loop range to match the session range
4544 (unless the auto loop range has been changed by the user)
4547 Location* s = _locations->session_range_location ();
4552 Location* l = _locations->auto_loop_location ();
4554 if (l && l->end() == old) {
4555 l->set_end (s->end(), true);
4560 Session::source_search_path (DataType type) const
4564 if (session_dirs.size() == 1) {
4566 case DataType::AUDIO:
4567 s.push_back (_session_dir->sound_path());
4569 case DataType::MIDI:
4570 s.push_back (_session_dir->midi_path());
4574 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4575 SessionDirectory sdir (i->path);
4577 case DataType::AUDIO:
4578 s.push_back (sdir.sound_path());
4580 case DataType::MIDI:
4581 s.push_back (sdir.midi_path());
4587 if (type == DataType::AUDIO) {
4588 const string sound_path_2X = _session_dir->sound_path_2X();
4589 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4590 if (find (s.begin(), s.end(), sound_path_2X) == s.end()) {
4591 s.push_back (sound_path_2X);
4596 /* now check the explicit (possibly user-specified) search path
4599 vector<string> dirs;
4602 case DataType::AUDIO:
4603 split (config.get_audio_search_path (), dirs, ':');
4605 case DataType::MIDI:
4606 split (config.get_midi_search_path (), dirs, ':');
4610 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4611 if (find (s.begin(), s.end(), *i) == s.end()) {
4618 for (vector<string>::iterator si = s.begin(); si != s.end(); ++si) {
4619 if (!search_path.empty()) {
4629 Session::ensure_search_path_includes (const string& path, DataType type)
4632 vector<string> dirs;
4639 case DataType::AUDIO:
4640 search_path = config.get_audio_search_path ();
4642 case DataType::MIDI:
4643 search_path = config.get_midi_search_path ();
4647 split (search_path, dirs, ':');
4649 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4650 /* No need to add this new directory if it has the same inode as
4651 an existing one; checking inode rather than name prevents duplicated
4652 directories when we are using symlinks.
4654 On Windows, I think we could just do if (*i == path) here.
4656 if (PBD::equivalent_paths (*i, path)) {
4661 if (!search_path.empty()) {
4665 search_path += path;
4668 case DataType::AUDIO:
4669 config.set_audio_search_path (search_path);
4671 case DataType::MIDI:
4672 config.set_midi_search_path (search_path);
4677 boost::shared_ptr<Speakers>
4678 Session::get_speakers()
4684 Session::unknown_processors () const
4688 boost::shared_ptr<RouteList> r = routes.reader ();
4689 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4690 list<string> t = (*i)->unknown_processors ();
4691 copy (t.begin(), t.end(), back_inserter (p));
4701 Session::update_latency (bool playback)
4703 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4705 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4709 boost::shared_ptr<RouteList> r = routes.reader ();
4710 framecnt_t max_latency = 0;
4713 /* reverse the list so that we work backwards from the last route to run to the first */
4714 RouteList* rl = routes.reader().get();
4715 r.reset (new RouteList (*rl));
4716 reverse (r->begin(), r->end());
4719 /* compute actual latency values for the given direction and store them all in per-port
4720 structures. this will also publish the same values (to JACK) so that computation of latency
4721 for routes can consistently use public latency values.
4724 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4725 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4728 /* because we latency compensate playback, our published playback latencies should
4729 be the same for all output ports - all material played back by ardour has
4730 the same latency, whether its caused by plugins or by latency compensation. since
4731 these may differ from the values computed above, reset all playback port latencies
4735 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4737 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4738 (*i)->set_public_port_latencies (max_latency, playback);
4743 post_playback_latency ();
4747 post_capture_latency ();
4750 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4754 Session::post_playback_latency ()
4756 set_worst_playback_latency ();
4758 boost::shared_ptr<RouteList> r = routes.reader ();
4760 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4761 if (!(*i)->is_auditioner() && ((*i)->active())) {
4762 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4766 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4767 (*i)->set_latency_compensation (_worst_track_latency);
4772 Session::post_capture_latency ()
4774 set_worst_capture_latency ();
4776 /* reflect any changes in capture latencies into capture offsets
4779 boost::shared_ptr<RouteList> rl = routes.reader();
4780 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4781 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4783 tr->set_capture_offset ();
4789 Session::initialize_latencies ()
4792 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4793 update_latency (false);
4794 update_latency (true);
4797 set_worst_io_latencies ();
4801 Session::set_worst_io_latencies ()
4803 set_worst_playback_latency ();
4804 set_worst_capture_latency ();
4808 Session::set_worst_playback_latency ()
4810 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4814 _worst_output_latency = 0;
4816 if (!_engine.connected()) {
4820 boost::shared_ptr<RouteList> r = routes.reader ();
4822 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4823 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4826 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4830 Session::set_worst_capture_latency ()
4832 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4836 _worst_input_latency = 0;
4838 if (!_engine.connected()) {
4842 boost::shared_ptr<RouteList> r = routes.reader ();
4844 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4845 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4848 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4852 Session::update_latency_compensation (bool force_whole_graph)
4854 bool some_track_latency_changed = false;
4856 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4860 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4862 _worst_track_latency = 0;
4864 boost::shared_ptr<RouteList> r = routes.reader ();
4866 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4867 if (!(*i)->is_auditioner() && ((*i)->active())) {
4869 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4870 some_track_latency_changed = true;
4872 _worst_track_latency = max (tl, _worst_track_latency);
4876 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4877 (some_track_latency_changed ? "yes" : "no")));
4879 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4881 if (some_track_latency_changed || force_whole_graph) {
4882 _engine.update_latencies ();
4886 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4887 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4891 tr->set_capture_offset ();
4896 Session::session_name_is_legal (const string& path)
4898 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4900 for (int i = 0; illegal_chars[i]; ++i) {
4901 if (path.find (illegal_chars[i]) != string::npos) {
4902 return illegal_chars[i];
4910 Session::next_control_id () const
4914 /* the monitor bus remote ID is in a different
4915 * "namespace" than regular routes. its existence doesn't
4916 * affect normal (low) numbered routes.
4923 return nroutes() - subtract;
4927 Session::notify_remote_id_change ()
4929 if (deletion_in_progress()) {
4933 switch (Config->get_remote_model()) {
4935 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4943 Session::sync_order_keys ()
4945 if (deletion_in_progress()) {
4949 /* tell everyone that something has happened to the sort keys
4950 and let them sync up with the change(s)
4951 this will give objects that manage the sort order keys the
4952 opportunity to keep them in sync if they wish to.
4955 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
4957 Route::SyncOrderKeys (); /* EMIT SIGNAL */
4959 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
4963 Session::operation_in_progress (GQuark op) const
4965 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
4968 boost::shared_ptr<Port>
4969 Session::ltc_input_port () const
4971 return _ltc_input->nth (0);
4974 boost::shared_ptr<Port>
4975 Session::ltc_output_port () const
4977 return _ltc_output->nth (0);
4981 Session::reconnect_ltc_input ()
4985 string src = Config->get_ltc_source_port();
4987 _ltc_input->disconnect (this);
4989 if (src != _("None") && !src.empty()) {
4990 _ltc_input->nth (0)->connect (src);
4996 Session::reconnect_ltc_output ()
5001 string src = Config->get_ltc_sink_port();
5003 _ltc_output->disconnect (this);
5005 if (src != _("None") && !src.empty()) {
5006 _ltc_output->nth (0)->connect (src);