2 Copyright (C) 1999-2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <cstdio> /* sprintf(3) ... grrr */
33 #include <glibmm/threads.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
37 #include <boost/algorithm/string/erase.hpp>
39 #include "pbd/error.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/unwind.h"
48 #include "pbd/search_path.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/scene_changer.h"
72 #include "ardour/midi_track.h"
73 #include "ardour/midi_ui.h"
74 #include "ardour/operations.h"
75 #include "ardour/playlist.h"
76 #include "ardour/plugin.h"
77 #include "ardour/plugin_insert.h"
78 #include "ardour/process_thread.h"
79 #include "ardour/rc_configuration.h"
80 #include "ardour/recent_sessions.h"
81 #include "ardour/region.h"
82 #include "ardour/region_factory.h"
83 #include "ardour/route_graph.h"
84 #include "ardour/route_group.h"
85 #include "ardour/send.h"
86 #include "ardour/session.h"
87 #include "ardour/session_directory.h"
88 #include "ardour/session_playlists.h"
89 #include "ardour/smf_source.h"
90 #include "ardour/source_factory.h"
91 #include "ardour/speakers.h"
92 #include "ardour/track.h"
93 #include "ardour/utils.h"
95 #include "midi++/port.h"
96 #include "midi++/mmc.h"
107 using namespace ARDOUR;
110 bool Session::_disable_all_loaded_plugins = false;
112 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
113 PBD::Signal1<void,std::string> Session::Dialog;
114 PBD::Signal0<int> Session::AskAboutPendingState;
115 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
116 PBD::Signal0<void> Session::SendFeedback;
117 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
119 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
120 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
121 PBD::Signal2<void,std::string, std::string> Session::Exported;
122 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
123 PBD::Signal0<void> Session::Quit;
124 PBD::Signal0<void> Session::FeedbackDetected;
125 PBD::Signal0<void> Session::SuccessfulGraphSort;
126 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
128 const framecnt_t Session::bounce_chunk_size = 65536;
129 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
130 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
132 /** @param snapshot_name Snapshot name, without .ardour suffix */
133 Session::Session (AudioEngine &eng,
134 const string& fullpath,
135 const string& snapshot_name,
136 BusProfile* bus_profile,
138 : playlists (new SessionPlaylists)
140 , process_function (&Session::process_with_events)
141 , _bounce_processing_active (false)
142 , waiting_for_sync_offset (false)
143 , _base_frame_rate (0)
144 , _current_frame_rate (0)
145 , _nominal_frame_rate (0)
146 , transport_sub_state (0)
147 , _record_status (Disabled)
148 , _transport_frame (0)
149 , _session_range_location (0)
152 , _transport_speed (0)
153 , _default_transport_speed (1.0)
154 , _last_transport_speed (0)
155 , _target_transport_speed (0.0)
156 , auto_play_legal (false)
157 , _last_slave_transport_frame (0)
158 , maximum_output_latency (0)
159 , _requested_return_frame (-1)
160 , current_block_size (0)
161 , _worst_output_latency (0)
162 , _worst_input_latency (0)
163 , _worst_track_latency (0)
164 , _have_captured (false)
167 , _non_soloed_outs_muted (false)
169 , _solo_isolated_cnt (0)
171 , _was_seamless (Config->get_seamless_loop ())
172 , _under_nsm_control (false)
173 , delta_accumulator_cnt (0)
174 , average_slave_delta (1800) // !!! why 1800 ???
176 , have_first_delta_accumulator (false)
177 , _slave_state (Stopped)
178 , post_export_sync (false)
179 , post_export_position (0)
181 , _export_started (false)
182 , _export_rolling (false)
183 , _pre_export_mmc_enabled (false)
184 , _name (snapshot_name)
186 , _send_qf_mtc (false)
187 , _pframes_since_last_mtc (0)
188 , session_midi_feedback (0)
190 , loop_changing (false)
192 , _session_dir (new SessionDirectory (fullpath))
193 , _current_snapshot_name (snapshot_name)
195 , state_was_pending (false)
196 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
197 , _last_roll_location (0)
198 , _last_roll_or_reversal_location (0)
199 , _last_record_location (0)
200 , pending_locate_roll (false)
201 , pending_locate_frame (0)
202 , pending_locate_flush (false)
203 , pending_abort (false)
204 , pending_auto_loop (false)
205 , _butler (new Butler (*this))
206 , _post_transport_work (0)
207 , cumulative_rf_motion (0)
209 , _locations (new Locations (*this))
211 , outbound_mtc_timecode_frame (0)
212 , next_quarter_frame_to_send (-1)
213 , _frames_per_timecode_frame (0)
214 , _frames_per_hour (0)
215 , _timecode_frames_per_hour (0)
216 , last_timecode_valid (false)
217 , last_timecode_when (0)
218 , _send_timecode_update (false)
230 , ltc_timecode_offset (0)
231 , ltc_timecode_negative_offset (false)
232 , midi_control_ui (0)
234 , _all_route_group (new RouteGroup (*this, "all"))
235 , routes (new RouteList)
236 , _adding_routes_in_progress (false)
237 , destructive_index (0)
238 , solo_update_disabled (false)
239 , default_fade_steepness (0)
240 , default_fade_msecs (0)
241 , _total_free_4k_blocks (0)
242 , _total_free_4k_blocks_uncertain (false)
243 , no_questions_about_missing_files (false)
246 , _bundles (new BundleList)
247 , _bundle_xml_node (0)
251 , click_emphasis_data (0)
253 , click_emphasis_length (0)
254 , _clicks_cleared (0)
255 , _play_range (false)
257 , first_file_data_format_reset (true)
258 , first_file_header_format_reset (true)
259 , have_looped (false)
260 , _have_rec_enabled_track (false)
262 , _suspend_timecode_transmission (0)
263 , _speakers (new Speakers)
265 , ignore_route_processor_changes (false)
272 pre_engine_init (fullpath);
275 if (ensure_engine (sr)) {
277 throw failed_constructor ();
280 if (create (mix_template, bus_profile)) {
282 throw failed_constructor ();
285 /* if a mix template was provided, then ::create() will
286 * have copied it into the session and we need to load it
287 * so that we have the state ready for ::set_state()
288 * after the engine is started.
290 * Note that we do NOT try to get the sample rate from
291 * the template at this time, though doing so would
292 * be easy if we decided this was an appropriate part
296 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
297 throw failed_constructor ();
302 if (load_state (_current_snapshot_name)) {
303 throw failed_constructor ();
306 /* try to get sample rate from XML state so that we
307 * can influence the SR if we set up the audio
312 const XMLProperty* prop;
313 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
314 sr = atoi (prop->value());
318 if (ensure_engine (sr)) {
320 throw failed_constructor ();
324 if (post_engine_init ()) {
326 throw failed_constructor ();
329 store_recent_sessions (_name, _path);
331 bool was_dirty = dirty();
333 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
335 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
336 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
339 DirtyChanged (); /* EMIT SIGNAL */
342 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
343 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
347 /* hook us up to the engine since we are now completely constructed */
349 BootMessage (_("Connect to engine"));
351 _engine.set_session (this);
352 _engine.reset_timebase ();
354 BootMessage (_("Session loading complete"));
367 Session::ensure_engine (uint32_t desired_sample_rate)
369 if (_engine.current_backend() == 0) {
370 /* backend is unknown ... */
371 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
372 if (r.get_value_or (-1) != 0) {
375 } else if (_engine.setup_required()) {
376 /* backend is known, but setup is needed */
377 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
378 if (r.get_value_or (-1) != 0) {
381 } else if (!_engine.running()) {
382 if (_engine.start()) {
387 /* at this point the engine should be running
390 if (!_engine.running()) {
394 return immediately_post_engine ();
399 Session::immediately_post_engine ()
401 /* Do various initializations that should take place directly after we
402 * know that the engine is running, but before we either create a
403 * session or set state for an existing one.
406 if (how_many_dsp_threads () > 1) {
407 /* For now, only create the graph if we are using >1 DSP threads, as
408 it is a bit slower than the old code with 1 thread.
410 _process_graph.reset (new Graph (*this));
413 /* every time we reconnect, recompute worst case output latencies */
415 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
417 if (synced_to_engine()) {
418 _engine.transport_stop ();
421 if (config.get_jack_time_master()) {
422 _engine.transport_locate (_transport_frame);
426 BootMessage (_("Set up LTC"));
428 BootMessage (_("Set up Click"));
430 BootMessage (_("Set up standard connections"));
434 catch (failed_constructor& err) {
444 vector<void*> debug_pointers;
446 /* if we got to here, leaving pending capture state around
450 remove_pending_capture_state ();
452 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
454 /* disconnect from any and all signals that we are connected to */
458 _engine.remove_session ();
460 /* deregister all ports - there will be no process or any other
461 * callbacks from the engine any more.
464 Port::PortDrop (); /* EMIT SIGNAL */
468 /* clear history so that no references to objects are held any more */
472 /* clear state tree so that no references to objects are held any more */
476 /* reset dynamic state version back to default */
478 Stateful::loading_state_version = 0;
480 _butler->drop_references ();
484 delete midi_control_ui;
485 delete _all_route_group;
487 if (click_data != default_click) {
488 delete [] click_data;
491 if (click_emphasis_data != default_click_emphasis) {
492 delete [] click_emphasis_data;
497 /* clear out any pending dead wood from RCU managed objects */
502 AudioDiskstream::free_working_buffers();
504 /* tell everyone who is still standing that we're about to die */
507 /* tell everyone to drop references and delete objects as we go */
509 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
510 RegionFactory::delete_all_regions ();
512 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
514 /* reset these three references to special routes before we do the usual route delete thing */
517 _master_out.reset ();
518 _monitor_out.reset ();
521 RCUWriter<RouteList> writer (routes);
522 boost::shared_ptr<RouteList> r = writer.get_copy ();
524 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
525 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
526 (*i)->drop_references ();
530 /* writer goes out of scope and updates master */
535 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
536 Glib::Threads::Mutex::Lock lm (source_lock);
537 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
538 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
539 i->second->drop_references ();
545 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
546 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
551 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
554 delete _scene_changer; _scene_changer = 0;
556 delete _mmc; _mmc = 0;
557 delete _midi_ports; _midi_ports = 0;
558 delete _locations; _locations = 0;
560 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
562 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
563 boost_debug_list_ptrs ();
568 Session::setup_ltc ()
572 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
573 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
575 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
576 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
579 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
580 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
582 reconnect_ltc_input ();
585 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
586 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
589 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
590 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
592 reconnect_ltc_output ();
595 /* fix up names of LTC ports because we don't want the normal
596 * IO style of NAME/TYPE-{in,out}N
599 _ltc_input->nth (0)->set_name (X_("LTC-in"));
600 _ltc_output->nth (0)->set_name (X_("LTC-out"));
604 Session::setup_click ()
607 _click_io.reset (new ClickIO (*this, X_("Click")));
608 _click_gain.reset (new Amp (*this));
609 _click_gain->activate ();
611 setup_click_state (state_tree->root());
613 setup_click_state (0);
618 Session::setup_click_state (const XMLNode* node)
620 const XMLNode* child = 0;
622 if (node && (child = find_named_node (*node, "Click")) != 0) {
624 /* existing state for Click */
627 if (Stateful::loading_state_version < 3000) {
628 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
630 const XMLNodeList& children (child->children());
631 XMLNodeList::const_iterator i = children.begin();
632 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
634 if (i != children.end()) {
635 c = _click_gain->set_state (**i, Stateful::loading_state_version);
641 _clicking = Config->get_clicking ();
645 error << _("could not setup Click I/O") << endmsg;
652 /* default state for Click: dual-mono to first 2 physical outputs */
655 _engine.get_physical_outputs (DataType::AUDIO, outs);
657 for (uint32_t physport = 0; physport < 2; ++physport) {
658 if (outs.size() > physport) {
659 if (_click_io->add_port (outs[physport], this)) {
660 // relax, even though its an error
665 if (_click_io->n_ports () > ChanCount::ZERO) {
666 _clicking = Config->get_clicking ();
672 Session::setup_bundles ()
674 vector<string> inputs[DataType::num_types];
675 vector<string> outputs[DataType::num_types];
676 for (uint32_t i = 0; i < DataType::num_types; ++i) {
677 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
678 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
681 /* Create a set of Bundle objects that map
682 to the physical I/O currently available. We create both
683 mono and stereo bundles, so that the common cases of mono
684 and stereo tracks get bundles to put in their mixer strip
685 in / out menus. There may be a nicer way of achieving that;
686 it doesn't really scale that well to higher channel counts
689 /* mono output bundles */
691 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
693 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
695 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
696 c->add_channel (_("mono"), DataType::AUDIO);
697 c->set_port (0, outputs[DataType::AUDIO][np]);
702 /* stereo output bundles */
704 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
705 if (np + 1 < outputs[DataType::AUDIO].size()) {
707 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
708 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
709 c->add_channel (_("L"), DataType::AUDIO);
710 c->set_port (0, outputs[DataType::AUDIO][np]);
711 c->add_channel (_("R"), DataType::AUDIO);
712 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
718 /* mono input bundles */
720 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
722 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
724 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
725 c->add_channel (_("mono"), DataType::AUDIO);
726 c->set_port (0, inputs[DataType::AUDIO][np]);
731 /* stereo input bundles */
733 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
734 if (np + 1 < inputs[DataType::AUDIO].size()) {
736 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
738 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
739 c->add_channel (_("L"), DataType::AUDIO);
740 c->set_port (0, inputs[DataType::AUDIO][np]);
741 c->add_channel (_("R"), DataType::AUDIO);
742 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
748 /* MIDI input bundles */
750 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
751 string n = inputs[DataType::MIDI][np];
752 boost::erase_first (n, X_("alsa_pcm:"));
754 boost::shared_ptr<Bundle> c (new Bundle (n, false));
755 c->add_channel ("", DataType::MIDI);
756 c->set_port (0, inputs[DataType::MIDI][np]);
760 /* MIDI output bundles */
762 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
763 string n = outputs[DataType::MIDI][np];
764 boost::erase_first (n, X_("alsa_pcm:"));
766 boost::shared_ptr<Bundle> c (new Bundle (n, true));
767 c->add_channel ("", DataType::MIDI);
768 c->set_port (0, outputs[DataType::MIDI][np]);
775 Session::auto_connect_master_bus ()
777 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
781 /* if requested auto-connect the outputs to the first N physical ports.
784 uint32_t limit = _master_out->n_outputs().n_total();
785 vector<string> outputs[DataType::num_types];
787 for (uint32_t i = 0; i < DataType::num_types; ++i) {
788 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
791 for (uint32_t n = 0; n < limit; ++n) {
792 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
794 if (outputs[p->type()].size() > n) {
795 connect_to = outputs[p->type()][n];
798 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
799 if (_master_out->output()->connect (p, connect_to, this)) {
800 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
809 Session::remove_monitor_section ()
815 /* force reversion to Solo-In-Place */
816 Config->set_solo_control_is_listen_control (false);
818 /* if we are auditioning, cancel it ... this is a workaround
819 to a problem (auditioning does not execute the process graph,
820 which is needed to remove routes when using >1 core for processing)
825 /* Hold process lock while doing this so that we don't hear bits and
826 * pieces of audio as we work on each route.
829 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
831 /* Connect tracks to monitor section. Note that in an
832 existing session, the internal sends will already exist, but we want the
833 routes to notice that they connect to the control out specifically.
837 boost::shared_ptr<RouteList> r = routes.reader ();
838 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
840 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
842 if ((*x)->is_monitor()) {
844 } else if ((*x)->is_master()) {
847 (*x)->remove_aux_or_listen (_monitor_out);
852 remove_route (_monitor_out);
853 auto_connect_master_bus ();
856 auditioner->connect ();
861 Session::add_monitor_section ()
865 if (_monitor_out || !_master_out) {
869 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
875 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
876 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
879 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
880 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
881 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
885 add_routes (rl, false, false, false);
887 assert (_monitor_out);
889 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
890 are undefined, at best.
893 uint32_t limit = _monitor_out->n_inputs().n_audio();
897 /* connect the inputs to the master bus outputs. this
898 * represents a separate data feed from the internal sends from
899 * each route. as of jan 2011, it allows the monitor section to
900 * conditionally ignore either the internal sends or the normal
901 * input feed, but we should really find a better way to do
905 _master_out->output()->disconnect (this);
907 for (uint32_t n = 0; n < limit; ++n) {
908 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
909 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
912 string connect_to = o->name();
913 if (_monitor_out->input()->connect (p, connect_to, this)) {
914 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
922 /* if monitor section is not connected, connect it to physical outs
925 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
927 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
929 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
932 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
934 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
935 Config->get_monitor_bus_preferred_bundle())
941 /* Monitor bus is audio only */
943 vector<string> outputs[DataType::num_types];
945 for (uint32_t i = 0; i < DataType::num_types; ++i) {
946 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
949 uint32_t mod = outputs[DataType::AUDIO].size();
950 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
954 for (uint32_t n = 0; n < limit; ++n) {
956 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
958 if (outputs[DataType::AUDIO].size() > (n % mod)) {
959 connect_to = outputs[DataType::AUDIO][n % mod];
962 if (!connect_to.empty()) {
963 if (_monitor_out->output()->connect (p, connect_to, this)) {
964 error << string_compose (
965 _("cannot connect control output %1 to %2"),
976 /* Hold process lock while doing this so that we don't hear bits and
977 * pieces of audio as we work on each route.
980 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
982 /* Connect tracks to monitor section. Note that in an
983 existing session, the internal sends will already exist, but we want the
984 routes to notice that they connect to the control out specifically.
988 boost::shared_ptr<RouteList> rls = routes.reader ();
990 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
992 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
994 if ((*x)->is_monitor()) {
996 } else if ((*x)->is_master()) {
999 (*x)->enable_monitor_send ();
1004 auditioner->connect ();
1009 Session::hookup_io ()
1011 /* stop graph reordering notifications from
1012 causing resorts, etc.
1015 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1019 /* we delay creating the auditioner till now because
1020 it makes its own connections to ports.
1024 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1026 throw failed_constructor ();
1028 a->use_new_diskstream ();
1032 catch (failed_constructor& err) {
1033 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1037 /* load bundles, which we may have postponed earlier on */
1038 if (_bundle_xml_node) {
1039 load_bundles (*_bundle_xml_node);
1040 delete _bundle_xml_node;
1043 /* Tell all IO objects to connect themselves together */
1045 IO::enable_connecting ();
1047 /* Now tell all "floating" ports to connect to whatever
1048 they should be connected to.
1051 AudioEngine::instance()->reconnect_ports ();
1053 /* Anyone who cares about input state, wake up and do something */
1055 IOConnectionsComplete (); /* EMIT SIGNAL */
1057 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1059 /* now handle the whole enchilada as if it was one
1060 graph reorder event.
1065 /* update the full solo state, which can't be
1066 correctly determined on a per-route basis, but
1067 needs the global overview that only the session
1071 update_route_solo_state ();
1075 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1077 boost::shared_ptr<Track> track = wp.lock ();
1082 boost::shared_ptr<Playlist> playlist;
1084 if ((playlist = track->playlist()) != 0) {
1085 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1086 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1087 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1092 Session::record_enabling_legal () const
1094 /* this used to be in here, but survey says.... we don't need to restrict it */
1095 // if (record_status() == Recording) {
1099 if (Config->get_all_safe()) {
1106 Session::set_track_monitor_input_status (bool yn)
1108 boost::shared_ptr<RouteList> rl = routes.reader ();
1109 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1110 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1111 if (tr && tr->record_enabled ()) {
1112 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1113 tr->request_input_monitoring (yn);
1119 Session::auto_punch_start_changed (Location* location)
1121 replace_event (SessionEvent::PunchIn, location->start());
1123 if (get_record_enabled() && config.get_punch_in()) {
1124 /* capture start has been changed, so save new pending state */
1125 save_state ("", true);
1130 Session::auto_punch_end_changed (Location* location)
1132 framepos_t when_to_stop = location->end();
1133 // when_to_stop += _worst_output_latency + _worst_input_latency;
1134 replace_event (SessionEvent::PunchOut, when_to_stop);
1138 Session::auto_punch_changed (Location* location)
1140 framepos_t when_to_stop = location->end();
1142 replace_event (SessionEvent::PunchIn, location->start());
1143 //when_to_stop += _worst_output_latency + _worst_input_latency;
1144 replace_event (SessionEvent::PunchOut, when_to_stop);
1147 /** @param loc A loop location.
1148 * @param pos Filled in with the start time of the required fade-out (in session frames).
1149 * @param length Filled in with the length of the required fade-out.
1152 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1154 pos = max (loc->start(), loc->end() - 64);
1155 length = loc->end() - pos;
1159 Session::auto_loop_changed (Location* location)
1161 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1164 auto_loop_declick_range (location, dcp, dcl);
1165 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1167 if (transport_rolling() && play_loop) {
1170 // if (_transport_frame > location->end()) {
1172 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1173 // relocate to beginning of loop
1174 clear_events (SessionEvent::LocateRoll);
1176 request_locate (location->start(), true);
1179 else if (Config->get_seamless_loop() && !loop_changing) {
1181 // schedule a locate-roll to refill the diskstreams at the
1182 // previous loop end
1183 loop_changing = true;
1185 if (location->end() > last_loopend) {
1186 clear_events (SessionEvent::LocateRoll);
1187 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1194 last_loopend = location->end();
1198 Session::set_auto_punch_location (Location* location)
1202 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1203 punch_connections.drop_connections();
1204 existing->set_auto_punch (false, this);
1205 remove_event (existing->start(), SessionEvent::PunchIn);
1206 clear_events (SessionEvent::PunchOut);
1207 auto_punch_location_changed (0);
1212 if (location == 0) {
1216 if (location->end() <= location->start()) {
1217 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1221 punch_connections.drop_connections ();
1223 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1224 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1225 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1227 location->set_auto_punch (true, this);
1229 auto_punch_changed (location);
1231 auto_punch_location_changed (location);
1235 Session::set_auto_loop_location (Location* location)
1239 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1240 loop_connections.drop_connections ();
1241 existing->set_auto_loop (false, this);
1242 remove_event (existing->end(), SessionEvent::AutoLoop);
1245 auto_loop_declick_range (existing, dcp, dcl);
1246 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1247 auto_loop_location_changed (0);
1252 if (location == 0) {
1256 if (location->end() <= location->start()) {
1257 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1261 last_loopend = location->end();
1263 loop_connections.drop_connections ();
1265 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1266 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1267 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1269 location->set_auto_loop (true, this);
1271 /* take care of our stuff first */
1273 auto_loop_changed (location);
1275 /* now tell everyone else */
1277 auto_loop_location_changed (location);
1281 Session::locations_added (Location *)
1287 Session::locations_changed ()
1289 _locations->apply (*this, &Session::handle_locations_changed);
1293 Session::handle_locations_changed (Locations::LocationList& locations)
1295 Locations::LocationList::iterator i;
1297 bool set_loop = false;
1298 bool set_punch = false;
1300 for (i = locations.begin(); i != locations.end(); ++i) {
1304 if (location->is_auto_punch()) {
1305 set_auto_punch_location (location);
1308 if (location->is_auto_loop()) {
1309 set_auto_loop_location (location);
1313 if (location->is_session_range()) {
1314 _session_range_location = location;
1319 set_auto_loop_location (0);
1322 set_auto_punch_location (0);
1329 Session::enable_record ()
1331 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1332 /* no recording at anything except normal speed */
1337 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1339 if (rs == Recording) {
1343 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1345 _last_record_location = _transport_frame;
1346 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1348 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1349 set_track_monitor_input_status (true);
1352 RecordStateChanged ();
1359 Session::disable_record (bool rt_context, bool force)
1363 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1365 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1366 g_atomic_int_set (&_record_status, Disabled);
1367 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1369 if (rs == Recording) {
1370 g_atomic_int_set (&_record_status, Enabled);
1374 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1375 set_track_monitor_input_status (false);
1378 RecordStateChanged (); /* emit signal */
1381 remove_pending_capture_state ();
1387 Session::step_back_from_record ()
1389 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1391 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1392 set_track_monitor_input_status (false);
1395 RecordStateChanged (); /* emit signal */
1400 Session::maybe_enable_record ()
1402 if (_step_editors > 0) {
1406 g_atomic_int_set (&_record_status, Enabled);
1408 /* This function is currently called from somewhere other than an RT thread.
1409 This save_state() call therefore doesn't impact anything. Doing it here
1410 means that we save pending state of which sources the next record will use,
1411 which gives us some chance of recovering from a crash during the record.
1414 save_state ("", true);
1416 if (_transport_speed) {
1417 if (!config.get_punch_in()) {
1421 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1422 RecordStateChanged (); /* EMIT SIGNAL */
1429 Session::audible_frame () const
1435 /* the first of these two possible settings for "offset"
1436 mean that the audible frame is stationary until
1437 audio emerges from the latency compensation
1440 the second means that the audible frame is stationary
1441 until audio would emerge from a physical port
1442 in the absence of any plugin latency compensation
1445 offset = worst_playback_latency ();
1447 if (offset > current_block_size) {
1448 offset -= current_block_size;
1450 /* XXX is this correct? if we have no external
1451 physical connections and everything is internal
1452 then surely this is zero? still, how
1453 likely is that anyway?
1455 offset = current_block_size;
1458 if (synced_to_engine()) {
1459 tf = _engine.transport_frame();
1461 tf = _transport_frame;
1466 if (!non_realtime_work_pending()) {
1470 /* Check to see if we have passed the first guaranteed
1471 audible frame past our last start position. if not,
1472 return that last start point because in terms
1473 of audible frames, we have not moved yet.
1475 `Start position' in this context means the time we last
1476 either started, located, or changed transport direction.
1479 if (_transport_speed > 0.0f) {
1481 if (!play_loop || !have_looped) {
1482 if (tf < _last_roll_or_reversal_location + offset) {
1483 return _last_roll_or_reversal_location;
1491 } else if (_transport_speed < 0.0f) {
1493 /* XXX wot? no backward looping? */
1495 if (tf > _last_roll_or_reversal_location - offset) {
1496 return _last_roll_or_reversal_location;
1508 Session::set_frame_rate (framecnt_t frames_per_second)
1510 /** \fn void Session::set_frame_size(framecnt_t)
1511 the AudioEngine object that calls this guarantees
1512 that it will not be called while we are also in
1513 ::process(). Its fine to do things that block
1517 _base_frame_rate = frames_per_second;
1518 _nominal_frame_rate = frames_per_second;
1524 // XXX we need some equivalent to this, somehow
1525 // SndFileSource::setup_standard_crossfades (frames_per_second);
1529 /* XXX need to reset/reinstantiate all LADSPA plugins */
1533 Session::set_block_size (pframes_t nframes)
1535 /* the AudioEngine guarantees
1536 that it will not be called while we are also in
1537 ::process(). It is therefore fine to do things that block
1542 current_block_size = nframes;
1546 boost::shared_ptr<RouteList> r = routes.reader ();
1548 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1549 (*i)->set_block_size (nframes);
1552 boost::shared_ptr<RouteList> rl = routes.reader ();
1553 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1554 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1556 tr->set_block_size (nframes);
1560 set_worst_io_latencies ();
1566 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1568 boost::shared_ptr<Route> r2;
1570 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1571 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1575 /* make a copy of the existing list of routes that feed r1 */
1577 Route::FedBy existing (r1->fed_by());
1579 /* for each route that feeds r1, recurse, marking it as feeding
1583 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1584 if (!(r2 = i->r.lock ())) {
1585 /* (*i) went away, ignore it */
1589 /* r2 is a route that feeds r1 which somehow feeds base. mark
1590 base as being fed by r2
1593 rbase->add_fed_by (r2, i->sends_only);
1597 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1601 if (r1->feeds (r2) && r2->feeds (r1)) {
1605 /* now recurse, so that we can mark base as being fed by
1606 all routes that feed r2
1609 trace_terminal (r2, rbase);
1616 Session::resort_routes ()
1618 /* don't do anything here with signals emitted
1619 by Routes during initial setup or while we
1620 are being destroyed.
1623 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1628 RCUWriter<RouteList> writer (routes);
1629 boost::shared_ptr<RouteList> r = writer.get_copy ();
1630 resort_routes_using (r);
1631 /* writer goes out of scope and forces update */
1635 boost::shared_ptr<RouteList> rl = routes.reader ();
1636 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1637 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1639 const Route::FedBy& fb ((*i)->fed_by());
1641 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1642 boost::shared_ptr<Route> sf = f->r.lock();
1644 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1652 /** This is called whenever we need to rebuild the graph of how we will process
1654 * @param r List of routes, in any order.
1658 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1660 /* We are going to build a directed graph of our routes;
1661 this is where the edges of that graph are put.
1666 /* Go through all routes doing two things:
1668 * 1. Collect the edges of the route graph. Each of these edges
1669 * is a pair of routes, one of which directly feeds the other
1670 * either by a JACK connection or by an internal send.
1672 * 2. Begin the process of making routes aware of which other
1673 * routes directly or indirectly feed them. This information
1674 * is used by the solo code.
1677 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1679 /* Clear out the route's list of direct or indirect feeds */
1680 (*i)->clear_fed_by ();
1682 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1684 bool via_sends_only;
1686 /* See if this *j feeds *i according to the current state of the JACK
1687 connections and internal sends.
1689 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1690 /* add the edge to the graph (part #1) */
1691 edges.add (*j, *i, via_sends_only);
1692 /* tell the route (for part #2) */
1693 (*i)->add_fed_by (*j, via_sends_only);
1698 /* Attempt a topological sort of the route graph */
1699 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1701 if (sorted_routes) {
1702 /* We got a satisfactory topological sort, so there is no feedback;
1705 Note: the process graph rechain does not require a
1706 topologically-sorted list, but hey ho.
1708 if (_process_graph) {
1709 _process_graph->rechain (sorted_routes, edges);
1712 _current_route_graph = edges;
1714 /* Complete the building of the routes' lists of what directly
1715 or indirectly feeds them.
1717 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1718 trace_terminal (*i, *i);
1721 *r = *sorted_routes;
1724 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1725 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1726 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1727 (*i)->name(), (*i)->order_key ()));
1731 SuccessfulGraphSort (); /* EMIT SIGNAL */
1734 /* The topological sort failed, so we have a problem. Tell everyone
1735 and stick to the old graph; this will continue to be processed, so
1736 until the feedback is fixed, what is played back will not quite
1737 reflect what is actually connected. Note also that we do not
1738 do trace_terminal here, as it would fail due to an endless recursion,
1739 so the solo code will think that everything is still connected
1743 FeedbackDetected (); /* EMIT SIGNAL */
1748 /** Find a route name starting with \a base, maybe followed by the
1749 * lowest \a id. \a id will always be added if \a definitely_add_number
1750 * is true on entry; otherwise it will only be added if required
1751 * to make the name unique.
1753 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1754 * The available route name with the lowest ID will be used, and \a id
1755 * will be set to the ID.
1757 * \return false if a route name could not be found, and \a track_name
1758 * and \a id do not reflect a free route name.
1761 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1763 if (!definitely_add_number && route_by_name (base) == 0) {
1764 /* juse use the base */
1765 snprintf (name, name_len, "%s", base.c_str());
1770 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1772 if (route_by_name (name) == 0) {
1778 } while (id < (UINT_MAX-1));
1783 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1785 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1787 in = ChanCount::ZERO;
1788 out = ChanCount::ZERO;
1790 boost::shared_ptr<RouteList> r = routes.reader ();
1792 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1793 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1794 if (tr && !tr->is_auditioner()) {
1795 in += tr->n_inputs();
1796 out += tr->n_outputs();
1801 /** Caller must not hold process lock
1802 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1803 * @param instrument plugin info for the instrument to insert pre-fader, if any
1805 list<boost::shared_ptr<MidiTrack> >
1806 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1807 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1809 char track_name[32];
1810 uint32_t track_id = 0;
1812 RouteList new_routes;
1813 list<boost::shared_ptr<MidiTrack> > ret;
1815 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1818 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1819 error << "cannot find name for new midi track" << endmsg;
1823 boost::shared_ptr<MidiTrack> track;
1826 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1828 if (track->init ()) {
1832 track->use_new_diskstream();
1834 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1835 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1838 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1839 if (track->input()->ensure_io (input, false, this)) {
1840 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1844 if (track->output()->ensure_io (output, false, this)) {
1845 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1850 track->non_realtime_input_change();
1853 route_group->add (track);
1856 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1858 if (Config->get_remote_model() == UserOrdered) {
1859 track->set_remote_control_id (next_control_id());
1862 new_routes.push_back (track);
1863 ret.push_back (track);
1866 catch (failed_constructor &err) {
1867 error << _("Session: could not create new midi track.") << endmsg;
1871 catch (AudioEngine::PortRegistrationFailure& pfe) {
1873 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;
1881 if (!new_routes.empty()) {
1882 add_routes (new_routes, true, true, true);
1885 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1886 PluginPtr plugin = instrument->load (*this);
1887 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1888 (*r)->add_processor (p, PreFader);
1898 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1900 boost::shared_ptr<Route> midi_track (wmt.lock());
1906 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1908 if (change.after.n_audio() <= change.before.n_audio()) {
1912 /* new audio ports: make sure the audio goes somewhere useful,
1913 unless the user has no-auto-connect selected.
1915 The existing ChanCounts don't matter for this call as they are only
1916 to do with matching input and output indices, and we are only changing
1922 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1926 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1927 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1928 * @param output_start As \a input_start, but for outputs.
1931 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1932 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1934 if (!IO::connecting_legal) {
1938 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1944 /* If both inputs and outputs are auto-connected to physical ports,
1945 use the max of input and output offsets to ensure auto-connected
1946 port numbers always match up (e.g. the first audio input and the
1947 first audio output of the route will have the same physical
1948 port number). Otherwise just use the lowest input or output
1952 DEBUG_TRACE (DEBUG::Graph,
1953 string_compose("Auto-connect: existing in = %1 out = %2\n",
1954 existing_inputs, existing_outputs));
1956 const bool in_out_physical =
1957 (Config->get_input_auto_connect() & AutoConnectPhysical)
1958 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1961 const ChanCount in_offset = in_out_physical
1962 ? ChanCount::max(existing_inputs, existing_outputs)
1965 const ChanCount out_offset = in_out_physical
1966 ? ChanCount::max(existing_inputs, existing_outputs)
1969 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1970 vector<string> physinputs;
1971 vector<string> physoutputs;
1973 _engine.get_physical_outputs (*t, physoutputs);
1974 _engine.get_physical_inputs (*t, physinputs);
1976 if (!physinputs.empty() && connect_inputs) {
1977 uint32_t nphysical_in = physinputs.size();
1979 DEBUG_TRACE (DEBUG::Graph,
1980 string_compose("There are %1 physical inputs of type %2\n",
1983 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1986 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1987 DEBUG_TRACE (DEBUG::Graph,
1988 string_compose("Get index %1 + %2 % %3 = %4\n",
1989 in_offset.get(*t), i, nphysical_in,
1990 (in_offset.get(*t) + i) % nphysical_in));
1991 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1994 DEBUG_TRACE (DEBUG::Graph,
1995 string_compose("Connect route %1 IN to %2\n",
1996 route->name(), port));
1998 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2002 ChanCount one_added (*t, 1);
2003 existing_inputs += one_added;
2007 if (!physoutputs.empty()) {
2008 uint32_t nphysical_out = physoutputs.size();
2009 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2012 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2013 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2014 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2015 /* master bus is audio only */
2016 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2017 port = _master_out->input()->ports().port(*t,
2018 i % _master_out->input()->n_ports().get(*t))->name();
2022 DEBUG_TRACE (DEBUG::Graph,
2023 string_compose("Connect route %1 OUT to %2\n",
2024 route->name(), port));
2026 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2030 ChanCount one_added (*t, 1);
2031 existing_outputs += one_added;
2037 /** Caller must not hold process lock
2038 * @param name_template string to use for the start of the name, or "" to use "Audio".
2040 list< boost::shared_ptr<AudioTrack> >
2041 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2042 uint32_t how_many, string name_template)
2044 char track_name[32];
2045 uint32_t track_id = 0;
2047 RouteList new_routes;
2048 list<boost::shared_ptr<AudioTrack> > ret;
2050 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2053 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2054 error << "cannot find name for new audio track" << endmsg;
2058 boost::shared_ptr<AudioTrack> track;
2061 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2063 if (track->init ()) {
2067 track->use_new_diskstream();
2069 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2070 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2073 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2075 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2076 error << string_compose (
2077 _("cannot configure %1 in/%2 out configuration for new audio track"),
2078 input_channels, output_channels)
2083 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2084 error << string_compose (
2085 _("cannot configure %1 in/%2 out configuration for new audio track"),
2086 input_channels, output_channels)
2093 route_group->add (track);
2096 track->non_realtime_input_change();
2098 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2099 if (Config->get_remote_model() == UserOrdered) {
2100 track->set_remote_control_id (next_control_id());
2103 new_routes.push_back (track);
2104 ret.push_back (track);
2107 catch (failed_constructor &err) {
2108 error << _("Session: could not create new audio track.") << endmsg;
2112 catch (AudioEngine::PortRegistrationFailure& pfe) {
2114 error << pfe.what() << endmsg;
2122 if (!new_routes.empty()) {
2123 add_routes (new_routes, true, true, true);
2129 /** Caller must not hold process lock.
2130 * @param name_template string to use for the start of the name, or "" to use "Bus".
2133 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2136 uint32_t bus_id = 0;
2140 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2143 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2144 error << "cannot find name for new audio bus" << endmsg;
2149 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2155 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2156 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2159 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2161 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2162 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2163 input_channels, output_channels)
2169 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2170 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2171 input_channels, output_channels)
2178 route_group->add (bus);
2180 if (Config->get_remote_model() == UserOrdered) {
2181 bus->set_remote_control_id (next_control_id());
2184 bus->add_internal_return ();
2186 ret.push_back (bus);
2192 catch (failed_constructor &err) {
2193 error << _("Session: could not create new audio route.") << endmsg;
2197 catch (AudioEngine::PortRegistrationFailure& pfe) {
2198 error << pfe.what() << endmsg;
2208 add_routes (ret, false, true, true); // autoconnect outputs only
2216 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2219 uint32_t control_id;
2221 uint32_t number = 0;
2222 const uint32_t being_added = how_many;
2224 if (!tree.read (template_path.c_str())) {
2228 XMLNode* node = tree.root();
2230 IO::disable_connecting ();
2232 control_id = next_control_id ();
2236 XMLNode node_copy (*node);
2238 /* Remove IDs of everything so that new ones are used */
2239 node_copy.remove_property_recursively (X_("id"));
2244 if (!name_base.empty()) {
2246 /* if we're adding more than one routes, force
2247 * all the names of the new routes to be
2248 * numbered, via the final parameter.
2251 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2252 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2258 string const route_name = node_copy.property(X_("name"))->value ();
2260 /* generate a new name by adding a number to the end of the template name */
2261 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2262 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2267 /* set this name in the XML description that we are about to use */
2268 Route::set_name_in_state (node_copy, name);
2270 /* trim bitslots from listen sends so that new ones are used */
2271 XMLNodeList children = node_copy.children ();
2272 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2273 if ((*i)->name() == X_("Processor")) {
2274 XMLProperty* role = (*i)->property (X_("role"));
2275 if (role && role->value() == X_("Listen")) {
2276 (*i)->remove_property (X_("bitslot"));
2281 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2284 error << _("Session: cannot create track/bus from template description") << endmsg;
2288 if (boost::dynamic_pointer_cast<Track>(route)) {
2289 /* force input/output change signals so that the new diskstream
2290 picks up the configuration of the route. During session
2291 loading this normally happens in a different way.
2294 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2296 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2297 change.after = route->input()->n_ports();
2298 route->input()->changed (change, this);
2299 change.after = route->output()->n_ports();
2300 route->output()->changed (change, this);
2303 route->set_remote_control_id (control_id);
2306 ret.push_back (route);
2309 catch (failed_constructor &err) {
2310 error << _("Session: could not create new route from template") << endmsg;
2314 catch (AudioEngine::PortRegistrationFailure& pfe) {
2315 error << pfe.what() << endmsg;
2324 add_routes (ret, true, true, true);
2325 IO::enable_connecting ();
2332 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2335 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2336 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2339 error << _("Adding new tracks/busses failed") << endmsg;
2344 update_latency (true);
2345 update_latency (false);
2350 save_state (_current_snapshot_name);
2353 RouteAdded (new_routes); /* EMIT SIGNAL */
2357 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2359 ChanCount existing_inputs;
2360 ChanCount existing_outputs;
2361 uint32_t order = next_control_id();
2363 if (_order_hint != 0) {
2364 order = _order_hint;
2368 count_existing_track_channels (existing_inputs, existing_outputs);
2371 RCUWriter<RouteList> writer (routes);
2372 boost::shared_ptr<RouteList> r = writer.get_copy ();
2373 r->insert (r->end(), new_routes.begin(), new_routes.end());
2375 /* if there is no control out and we're not in the middle of loading,
2376 resort the graph here. if there is a control out, we will resort
2377 toward the end of this method. if we are in the middle of loading,
2378 we will resort when done.
2381 if (!_monitor_out && IO::connecting_legal) {
2382 resort_routes_using (r);
2386 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2388 boost::weak_ptr<Route> wpr (*x);
2389 boost::shared_ptr<Route> r (*x);
2391 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2392 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2393 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2394 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2395 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2396 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2398 if (r->is_master()) {
2402 if (r->is_monitor()) {
2406 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2408 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2409 track_playlist_changed (boost::weak_ptr<Track> (tr));
2410 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2412 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2414 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2415 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2420 if (input_auto_connect || output_auto_connect) {
2421 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2424 /* order keys are a GUI responsibility but we need to set up
2425 reasonable defaults because they also affect the remote control
2426 ID in most situations.
2429 if (!r->has_order_key ()) {
2430 if (r->is_auditioner()) {
2431 /* use an arbitrarily high value */
2432 r->set_order_key (UINT_MAX);
2434 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2435 r->set_order_key (order);
2443 if (_monitor_out && IO::connecting_legal) {
2444 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2446 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2447 if ((*x)->is_monitor()) {
2449 } else if ((*x)->is_master()) {
2452 (*x)->enable_monitor_send ();
2459 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2461 boost::shared_ptr<RouteList> r = routes.reader ();
2462 boost::shared_ptr<Send> s;
2464 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2465 if ((s = (*i)->internal_send_for (dest)) != 0) {
2466 s->amp()->gain_control()->set_value (0.0);
2472 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2474 boost::shared_ptr<RouteList> r = routes.reader ();
2475 boost::shared_ptr<Send> s;
2477 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2478 if ((s = (*i)->internal_send_for (dest)) != 0) {
2479 s->amp()->gain_control()->set_value (1.0);
2485 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2487 boost::shared_ptr<RouteList> r = routes.reader ();
2488 boost::shared_ptr<Send> s;
2490 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2491 if ((s = (*i)->internal_send_for (dest)) != 0) {
2492 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2497 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2499 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2501 boost::shared_ptr<RouteList> r = routes.reader ();
2502 boost::shared_ptr<RouteList> t (new RouteList);
2504 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2505 /* no MIDI sends because there are no MIDI busses yet */
2506 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2511 add_internal_sends (dest, p, t);
2515 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2517 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2518 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2523 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2525 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2529 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2531 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2535 if (!dest->internal_return()) {
2536 dest->add_internal_return ();
2539 sender->add_aux_send (dest, before);
2545 Session::remove_route (boost::shared_ptr<Route> route)
2547 if (route == _master_out) {
2551 route->set_solo (false, this);
2554 RCUWriter<RouteList> writer (routes);
2555 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2559 /* deleting the master out seems like a dumb
2560 idea, but its more of a UI policy issue
2564 if (route == _master_out) {
2565 _master_out = boost::shared_ptr<Route> ();
2568 if (route == _monitor_out) {
2569 _monitor_out.reset ();
2572 /* writer goes out of scope, forces route list update */
2575 update_route_solo_state ();
2577 // We need to disconnect the route's inputs and outputs
2579 route->input()->disconnect (0);
2580 route->output()->disconnect (0);
2582 /* if the route had internal sends sending to it, remove them */
2583 if (route->internal_return()) {
2585 boost::shared_ptr<RouteList> r = routes.reader ();
2586 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2587 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2589 (*i)->remove_processor (s);
2594 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2595 if (mt && mt->step_editing()) {
2596 if (_step_editors > 0) {
2601 update_latency_compensation ();
2604 /* Re-sort routes to remove the graph's current references to the one that is
2605 * going away, then flush old references out of the graph.
2609 if (_process_graph) {
2610 _process_graph->clear_other_chain ();
2613 /* get rid of it from the dead wood collection in the route list manager */
2615 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2619 /* try to cause everyone to drop their references */
2621 route->drop_references ();
2623 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2625 /* save the new state of the world */
2627 if (save_state (_current_snapshot_name)) {
2628 save_history (_current_snapshot_name);
2633 Session::route_mute_changed (void* /*src*/)
2639 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2641 boost::shared_ptr<Route> route = wpr.lock();
2643 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2647 if (route->listening_via_monitor ()) {
2649 if (Config->get_exclusive_solo()) {
2650 /* new listen: disable all other listen */
2651 boost::shared_ptr<RouteList> r = routes.reader ();
2652 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2653 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2656 (*i)->set_listen (false, this);
2662 } else if (_listen_cnt > 0) {
2667 update_route_solo_state ();
2670 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2672 boost::shared_ptr<Route> route = wpr.lock ();
2675 /* should not happen */
2676 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2680 bool send_changed = false;
2682 if (route->solo_isolated()) {
2683 if (_solo_isolated_cnt == 0) {
2684 send_changed = true;
2686 _solo_isolated_cnt++;
2687 } else if (_solo_isolated_cnt > 0) {
2688 _solo_isolated_cnt--;
2689 if (_solo_isolated_cnt == 0) {
2690 send_changed = true;
2695 IsolatedChanged (); /* EMIT SIGNAL */
2700 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2702 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2704 if (!self_solo_change) {
2705 // session doesn't care about changes to soloed-by-others
2709 if (solo_update_disabled) {
2711 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2715 boost::shared_ptr<Route> route = wpr.lock ();
2718 boost::shared_ptr<RouteList> r = routes.reader ();
2721 if (route->self_soloed()) {
2727 RouteGroup* rg = route->route_group ();
2728 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2730 if (delta == 1 && Config->get_exclusive_solo()) {
2732 /* new solo: disable all other solos, but not the group if its solo-enabled */
2734 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2735 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2736 (leave_group_alone && ((*i)->route_group() == rg))) {
2739 (*i)->set_solo (false, this);
2743 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2745 solo_update_disabled = true;
2747 RouteList uninvolved;
2749 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2751 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2752 bool via_sends_only;
2753 bool in_signal_flow;
2755 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2756 (leave_group_alone && ((*i)->route_group() == rg))) {
2760 in_signal_flow = false;
2762 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2764 if ((*i)->feeds (route, &via_sends_only)) {
2765 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2766 if (!via_sends_only) {
2767 if (!route->soloed_by_others_upstream()) {
2768 (*i)->mod_solo_by_others_downstream (delta);
2771 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2773 in_signal_flow = true;
2775 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2778 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2780 if (route->feeds (*i, &via_sends_only)) {
2781 /* propagate solo upstream only if routing other than
2782 sends is involved, but do consider the other route
2783 (*i) to be part of the signal flow even if only
2786 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2790 route->soloed_by_others_downstream(),
2791 route->soloed_by_others_upstream()));
2792 if (!via_sends_only) {
2793 if (!route->soloed_by_others_downstream()) {
2794 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2795 (*i)->mod_solo_by_others_upstream (delta);
2797 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2800 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2802 in_signal_flow = true;
2804 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2807 if (!in_signal_flow) {
2808 uninvolved.push_back (*i);
2812 solo_update_disabled = false;
2813 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2815 update_route_solo_state (r);
2817 /* now notify that the mute state of the routes not involved in the signal
2818 pathway of the just-solo-changed route may have altered.
2821 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2822 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2823 (*i)->mute_changed (this);
2826 SoloChanged (); /* EMIT SIGNAL */
2831 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2833 /* now figure out if anything that matters is soloed (or is "listening")*/
2835 bool something_soloed = false;
2836 uint32_t listeners = 0;
2837 uint32_t isolated = 0;
2840 r = routes.reader();
2843 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2844 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2845 something_soloed = true;
2848 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2849 if (Config->get_solo_control_is_listen_control()) {
2852 (*i)->set_listen (false, this);
2856 if ((*i)->solo_isolated()) {
2861 if (something_soloed != _non_soloed_outs_muted) {
2862 _non_soloed_outs_muted = something_soloed;
2863 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2866 _listen_cnt = listeners;
2868 if (isolated != _solo_isolated_cnt) {
2869 _solo_isolated_cnt = isolated;
2870 IsolatedChanged (); /* EMIT SIGNAL */
2873 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2874 something_soloed, listeners, isolated));
2877 boost::shared_ptr<RouteList>
2878 Session::get_routes_with_internal_returns() const
2880 boost::shared_ptr<RouteList> r = routes.reader ();
2881 boost::shared_ptr<RouteList> rl (new RouteList);
2883 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2884 if ((*i)->internal_return ()) {
2892 Session::io_name_is_legal (const std::string& name)
2894 boost::shared_ptr<RouteList> r = routes.reader ();
2896 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2897 if ((*i)->name() == name) {
2901 if ((*i)->has_io_processor_named (name)) {
2910 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2913 vector<string> connections;
2915 /* if we are passed only a single route and we're not told to turn
2916 * others off, then just do the simple thing.
2919 if (flip_others == false && rl->size() == 1) {
2920 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2922 mt->set_input_active (onoff);
2927 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2929 PortSet& ps ((*rt)->input()->ports());
2931 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2932 p->get_connections (connections);
2935 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2936 routes_using_input_from (*s, rl2);
2939 /* scan all relevant routes to see if others are on or off */
2941 bool others_are_already_on = false;
2943 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2945 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2951 if ((*r) != (*rt)) {
2952 if (mt->input_active()) {
2953 others_are_already_on = true;
2956 /* this one needs changing */
2957 mt->set_input_active (onoff);
2963 /* globally reverse other routes */
2965 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2966 if ((*r) != (*rt)) {
2967 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2969 mt->set_input_active (!others_are_already_on);
2978 Session::routes_using_input_from (const string& str, RouteList& rl)
2980 boost::shared_ptr<RouteList> r = routes.reader();
2982 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2983 if ((*i)->input()->connected_to (str)) {
2989 boost::shared_ptr<Route>
2990 Session::route_by_name (string name)
2992 boost::shared_ptr<RouteList> r = routes.reader ();
2994 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2995 if ((*i)->name() == name) {
3000 return boost::shared_ptr<Route> ((Route*) 0);
3003 boost::shared_ptr<Route>
3004 Session::route_by_id (PBD::ID id)
3006 boost::shared_ptr<RouteList> r = routes.reader ();
3008 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3009 if ((*i)->id() == id) {
3014 return boost::shared_ptr<Route> ((Route*) 0);
3017 boost::shared_ptr<Track>
3018 Session::track_by_diskstream_id (PBD::ID id)
3020 boost::shared_ptr<RouteList> r = routes.reader ();
3022 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3023 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3024 if (t && t->using_diskstream_id (id)) {
3029 return boost::shared_ptr<Track> ();
3032 boost::shared_ptr<Route>
3033 Session::route_by_remote_id (uint32_t id)
3035 boost::shared_ptr<RouteList> r = routes.reader ();
3037 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3038 if ((*i)->remote_control_id() == id) {
3043 return boost::shared_ptr<Route> ((Route*) 0);
3047 Session::playlist_region_added (boost::weak_ptr<Region> w)
3049 boost::shared_ptr<Region> r = w.lock ();
3054 /* These are the operations that are currently in progress... */
3055 list<GQuark> curr = _current_trans_quarks;
3058 /* ...and these are the operations during which we want to update
3059 the session range location markers.
3062 ops.push_back (Operations::capture);
3063 ops.push_back (Operations::paste);
3064 ops.push_back (Operations::duplicate_region);
3065 ops.push_back (Operations::insert_file);
3066 ops.push_back (Operations::insert_region);
3067 ops.push_back (Operations::drag_region_brush);
3068 ops.push_back (Operations::region_drag);
3069 ops.push_back (Operations::selection_grab);
3070 ops.push_back (Operations::region_fill);
3071 ops.push_back (Operations::fill_selection);
3072 ops.push_back (Operations::create_region);
3073 ops.push_back (Operations::region_copy);
3074 ops.push_back (Operations::fixed_time_region_copy);
3077 /* See if any of the current operations match the ones that we want */
3079 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3081 /* If so, update the session range markers */
3083 maybe_update_session_range (r->position (), r->last_frame ());
3087 /** Update the session range markers if a is before the current start or
3088 * b is after the current end.
3091 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3093 if (_state_of_the_state & Loading) {
3097 if (_session_range_location == 0) {
3099 add_session_range_location (a, b);
3103 if (a < _session_range_location->start()) {
3104 _session_range_location->set_start (a);
3107 if (b > _session_range_location->end()) {
3108 _session_range_location->set_end (b);
3114 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3116 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3117 maybe_update_session_range (i->to, i->to + i->length);
3122 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3124 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3125 maybe_update_session_range (i->from, i->to);
3129 /* Region management */
3131 boost::shared_ptr<Region>
3132 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3134 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3135 RegionFactory::RegionMap::const_iterator i;
3136 boost::shared_ptr<Region> region;
3138 Glib::Threads::Mutex::Lock lm (region_lock);
3140 for (i = regions.begin(); i != regions.end(); ++i) {
3144 if (region->whole_file()) {
3146 if (child->source_equivalent (region)) {
3152 return boost::shared_ptr<Region> ();
3156 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3158 set<boost::shared_ptr<Region> > relevant_regions;
3160 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3161 RegionFactory::get_regions_using_source (*s, relevant_regions);
3164 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3165 set<boost::shared_ptr<Region> >::iterator tmp;
3170 playlists->destroy_region (*r);
3171 RegionFactory::map_remove (*r);
3173 (*r)->drop_sources ();
3174 (*r)->drop_references ();
3176 relevant_regions.erase (r);
3181 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3184 Glib::Threads::Mutex::Lock ls (source_lock);
3185 /* remove from the main source list */
3186 sources.erase ((*s)->id());
3189 (*s)->mark_for_remove ();
3190 (*s)->drop_references ();
3199 Session::remove_last_capture ()
3201 list<boost::shared_ptr<Source> > srcs;
3203 boost::shared_ptr<RouteList> rl = routes.reader ();
3204 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3205 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3210 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3213 srcs.insert (srcs.end(), l.begin(), l.end());
3218 destroy_sources (srcs);
3220 save_state (_current_snapshot_name);
3225 /* Source Management */
3228 Session::add_source (boost::shared_ptr<Source> source)
3230 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3231 pair<SourceMap::iterator,bool> result;
3233 entry.first = source->id();
3234 entry.second = source;
3237 Glib::Threads::Mutex::Lock lm (source_lock);
3238 result = sources.insert (entry);
3241 if (result.second) {
3243 /* yay, new source */
3245 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3248 if (!fs->within_session()) {
3249 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3255 boost::shared_ptr<AudioFileSource> afs;
3257 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3258 if (Config->get_auto_analyse_audio()) {
3259 Analyser::queue_source_for_analysis (source, false);
3263 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3268 Session::remove_source (boost::weak_ptr<Source> src)
3270 if (_state_of_the_state & Deletion) {
3274 SourceMap::iterator i;
3275 boost::shared_ptr<Source> source = src.lock();
3282 Glib::Threads::Mutex::Lock lm (source_lock);
3284 if ((i = sources.find (source->id())) != sources.end()) {
3289 if (!(_state_of_the_state & InCleanup)) {
3291 /* save state so we don't end up with a session file
3292 referring to non-existent sources.
3295 save_state (_current_snapshot_name);
3299 boost::shared_ptr<Source>
3300 Session::source_by_id (const PBD::ID& id)
3302 Glib::Threads::Mutex::Lock lm (source_lock);
3303 SourceMap::iterator i;
3304 boost::shared_ptr<Source> source;
3306 if ((i = sources.find (id)) != sources.end()) {
3313 boost::shared_ptr<AudioFileSource>
3314 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3316 /* Restricted to audio files because only audio sources have channel
3320 Glib::Threads::Mutex::Lock lm (source_lock);
3322 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3323 boost::shared_ptr<AudioFileSource> afs
3324 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3326 if (afs && afs->path() == path && chn == afs->channel()) {
3331 return boost::shared_ptr<AudioFileSource>();
3334 boost::shared_ptr<MidiSource>
3335 Session::midi_source_by_path (const std::string& path) const
3337 /* Restricted to MIDI files because audio sources require a channel
3338 for unique identification, in addition to a path.
3341 Glib::Threads::Mutex::Lock lm (source_lock);
3343 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3344 boost::shared_ptr<MidiSource> ms
3345 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3346 boost::shared_ptr<FileSource> fs
3347 = boost::dynamic_pointer_cast<FileSource>(s->second);
3349 if (ms && fs && fs->path() == path) {
3354 return boost::shared_ptr<MidiSource>();
3358 Session::count_sources_by_origin (const string& path)
3361 Glib::Threads::Mutex::Lock lm (source_lock);
3363 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3364 boost::shared_ptr<FileSource> fs
3365 = boost::dynamic_pointer_cast<FileSource>(i->second);
3367 if (fs && fs->origin() == path) {
3375 /** Return the full path (in some session directory) for a new within-session source.
3376 * \a name must be a session-unique name that does not contain slashes
3377 * (e.g. as returned by new_*_source_name)
3380 Session::new_source_path_from_name (DataType type, const string& name)
3382 assert(name.find("/") == string::npos);
3384 SessionDirectory sdir(get_best_session_directory_for_new_source());
3387 if (type == DataType::AUDIO) {
3388 p = sdir.sound_path();
3389 } else if (type == DataType::MIDI) {
3390 p = sdir.midi_path();
3392 error << "Unknown source type, unable to create file path" << endmsg;
3396 return Glib::build_filename (p, name);
3400 Session::peak_path (string base) const
3402 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3405 /** Return a unique name based on \a base for a new internal audio source */
3407 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3410 char buf[PATH_MAX+1];
3411 const uint32_t limit = 10000;
3413 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3416 legalized = legalize_for_path (base);
3418 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3419 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3421 vector<space_and_path>::iterator i;
3422 uint32_t existing = 0;
3424 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3429 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3430 cnt, legalized.c_str(), ext.c_str());
3431 } else if (nchan == 2) {
3433 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3434 cnt, legalized.c_str(), ext.c_str());
3436 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3437 cnt, legalized.c_str(), ext.c_str());
3439 } else if (nchan < 26) {
3440 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3441 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3443 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3444 cnt, legalized.c_str(), ext.c_str());
3450 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3451 } else if (nchan == 2) {
3453 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3455 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3457 } else if (nchan < 26) {
3458 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3460 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3464 SessionDirectory sdir((*i).path);
3466 string spath = sdir.sound_path();
3468 /* note that we search *without* the extension so that
3469 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3470 in the event that this new name is required for
3471 a file format change.
3474 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3479 /* it is possible that we have the path already
3480 * assigned to a source that has not yet been written
3481 * (ie. the write source for a diskstream). we have to
3482 * check this in order to make sure that our candidate
3483 * path isn't used again, because that can lead to
3484 * two Sources point to the same file with different
3485 * notions of their removability.
3488 string possible_path = Glib::build_filename (spath, buf);
3490 if (audio_source_by_path_and_channel (possible_path, chan)) {
3496 if (existing == 0) {
3501 error << string_compose(
3502 _("There are already %1 recordings for %2, which I consider too many."),
3503 limit, base) << endmsg;
3505 throw failed_constructor();
3509 return Glib::path_get_basename (buf);
3512 /** Create a new within-session audio source */
3513 boost::shared_ptr<AudioFileSource>
3514 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3516 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3517 const string path = new_source_path_from_name(DataType::AUDIO, name);
3519 return boost::dynamic_pointer_cast<AudioFileSource> (
3520 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3523 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3525 Session::new_midi_source_name (const string& owner_name)
3528 char buf[PATH_MAX+1];
3529 const uint32_t limit = 10000;
3531 string possible_name;
3534 legalized = legalize_for_path (owner_name);
3536 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3538 for (cnt = 1; cnt <= limit; ++cnt) {
3540 vector<space_and_path>::iterator i;
3541 uint32_t existing = 0;
3543 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3545 SessionDirectory sdir((*i).path);
3547 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3548 possible_name = buf;
3550 std::string possible_path = Glib::build_filename (sdir.midi_path(), possible_name);
3552 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3556 if (midi_source_by_path (possible_path)) {
3561 if (existing == 0) {
3566 error << string_compose(
3567 _("There are already %1 recordings for %2, which I consider too many."),
3568 limit, owner_name) << endmsg;
3570 throw failed_constructor();
3574 return possible_name;
3578 /** Create a new within-session MIDI source */
3579 boost::shared_ptr<MidiSource>
3580 Session::create_midi_source_for_session (string const & basic_name)
3585 name = new_midi_source_name (basic_name);
3588 const string path = new_source_path_from_name (DataType::MIDI, name);
3590 return boost::dynamic_pointer_cast<SMFSource> (
3591 SourceFactory::createWritable (
3592 DataType::MIDI, *this, path, false, frame_rate()));
3595 /** Create a new within-session MIDI source */
3596 boost::shared_ptr<MidiSource>
3597 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3599 /* the caller passes in the track the source will be used in,
3600 so that we can keep the numbering sane.
3602 Rationale: a track with the name "Foo" that has had N
3603 captures carried out so far will ALREADY have a write source
3604 named "Foo-N+1.mid" waiting to be used for the next capture.
3606 If we call new_midi_source_name() we will get "Foo-N+2". But
3607 there is no region corresponding to "Foo-N+1", so when
3608 "Foo-N+2" appears in the track, the gap presents the user
3609 with odd behaviour - why did it skip past Foo-N+1?
3611 We could explain this to the user in some odd way, but
3612 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3615 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3618 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3620 std::string name = track->steal_write_source_name ();
3623 return boost::shared_ptr<MidiSource>();
3626 const string path = new_source_path_from_name (DataType::MIDI, name);
3628 return boost::dynamic_pointer_cast<SMFSource> (
3629 SourceFactory::createWritable (
3630 DataType::MIDI, *this, path, false, frame_rate()));
3635 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3637 if (playlist->hidden()) {
3641 playlists->add (playlist);
3644 playlist->release();
3651 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3653 if (_state_of_the_state & Deletion) {
3657 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3663 playlists->remove (playlist);
3669 Session::set_audition (boost::shared_ptr<Region> r)
3671 pending_audition_region = r;
3672 add_post_transport_work (PostTransportAudition);
3673 _butler->schedule_transport_work ();
3677 Session::audition_playlist ()
3679 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3680 ev->region.reset ();
3685 Session::non_realtime_set_audition ()
3687 assert (pending_audition_region);
3688 auditioner->audition_region (pending_audition_region);
3689 pending_audition_region.reset ();
3690 AuditionActive (true); /* EMIT SIGNAL */
3694 Session::audition_region (boost::shared_ptr<Region> r)
3696 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3702 Session::cancel_audition ()
3704 if (auditioner->auditioning()) {
3705 auditioner->cancel_audition ();
3706 AuditionActive (false); /* EMIT SIGNAL */
3711 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3713 if (a->is_monitor()) {
3716 if (b->is_monitor()) {
3719 return a->order_key () < b->order_key ();
3723 Session::is_auditioning () const
3725 /* can be called before we have an auditioner object */
3727 return auditioner->auditioning();
3734 Session::graph_reordered ()
3736 /* don't do this stuff if we are setting up connections
3737 from a set_state() call or creating new tracks. Ditto for deletion.
3740 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3744 /* every track/bus asked for this to be handled but it was deferred because
3745 we were connecting. do it now.
3748 request_input_change_handling ();
3752 /* force all diskstreams to update their capture offset values to
3753 reflect any changes in latencies within the graph.
3756 boost::shared_ptr<RouteList> rl = routes.reader ();
3757 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3758 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3760 tr->set_capture_offset ();
3765 /** @return Number of frames that there is disk space available to write,
3768 boost::optional<framecnt_t>
3769 Session::available_capture_duration ()
3771 Glib::Threads::Mutex::Lock lm (space_lock);
3773 if (_total_free_4k_blocks_uncertain) {
3774 return boost::optional<framecnt_t> ();
3777 float sample_bytes_on_disk = 4.0; // keep gcc happy
3779 switch (config.get_native_file_data_format()) {
3781 sample_bytes_on_disk = 4.0;
3785 sample_bytes_on_disk = 3.0;
3789 sample_bytes_on_disk = 2.0;
3793 /* impossible, but keep some gcc versions happy */
3794 fatal << string_compose (_("programming error: %1"),
3795 X_("illegal native file data format"))
3800 double scale = 4096.0 / sample_bytes_on_disk;
3802 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3803 return max_framecnt;
3806 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3810 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3813 RCUWriter<BundleList> writer (_bundles);
3814 boost::shared_ptr<BundleList> b = writer.get_copy ();
3815 b->push_back (bundle);
3818 BundleAdded (bundle); /* EMIT SIGNAL */
3824 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3826 bool removed = false;
3829 RCUWriter<BundleList> writer (_bundles);
3830 boost::shared_ptr<BundleList> b = writer.get_copy ();
3831 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3833 if (i != b->end()) {
3840 BundleRemoved (bundle); /* EMIT SIGNAL */
3846 boost::shared_ptr<Bundle>
3847 Session::bundle_by_name (string name) const
3849 boost::shared_ptr<BundleList> b = _bundles.reader ();
3851 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3852 if ((*i)->name() == name) {
3857 return boost::shared_ptr<Bundle> ();
3861 Session::tempo_map_changed (const PropertyChange&)
3865 playlists->update_after_tempo_map_change ();
3867 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3873 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3875 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3876 (*i)->recompute_frames_from_bbt ();
3880 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3881 * the given count with the current block size.
3884 Session::ensure_buffers (ChanCount howmany)
3886 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
3890 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3892 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3893 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3898 Session::next_insert_id ()
3900 /* this doesn't really loop forever. just think about it */
3903 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3904 if (!insert_bitset[n]) {
3905 insert_bitset[n] = true;
3911 /* none available, so resize and try again */
3913 insert_bitset.resize (insert_bitset.size() + 16, false);
3918 Session::next_send_id ()
3920 /* this doesn't really loop forever. just think about it */
3923 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3924 if (!send_bitset[n]) {
3925 send_bitset[n] = true;
3931 /* none available, so resize and try again */
3933 send_bitset.resize (send_bitset.size() + 16, false);
3938 Session::next_aux_send_id ()
3940 /* this doesn't really loop forever. just think about it */
3943 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3944 if (!aux_send_bitset[n]) {
3945 aux_send_bitset[n] = true;
3951 /* none available, so resize and try again */
3953 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3958 Session::next_return_id ()
3960 /* this doesn't really loop forever. just think about it */
3963 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3964 if (!return_bitset[n]) {
3965 return_bitset[n] = true;
3971 /* none available, so resize and try again */
3973 return_bitset.resize (return_bitset.size() + 16, false);
3978 Session::mark_send_id (uint32_t id)
3980 if (id >= send_bitset.size()) {
3981 send_bitset.resize (id+16, false);
3983 if (send_bitset[id]) {
3984 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3986 send_bitset[id] = true;
3990 Session::mark_aux_send_id (uint32_t id)
3992 if (id >= aux_send_bitset.size()) {
3993 aux_send_bitset.resize (id+16, false);
3995 if (aux_send_bitset[id]) {
3996 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
3998 aux_send_bitset[id] = true;
4002 Session::mark_return_id (uint32_t id)
4004 if (id >= return_bitset.size()) {
4005 return_bitset.resize (id+16, false);
4007 if (return_bitset[id]) {
4008 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4010 return_bitset[id] = true;
4014 Session::mark_insert_id (uint32_t id)
4016 if (id >= insert_bitset.size()) {
4017 insert_bitset.resize (id+16, false);
4019 if (insert_bitset[id]) {
4020 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4022 insert_bitset[id] = true;
4026 Session::unmark_send_id (uint32_t id)
4028 if (id < send_bitset.size()) {
4029 send_bitset[id] = false;
4034 Session::unmark_aux_send_id (uint32_t id)
4036 if (id < aux_send_bitset.size()) {
4037 aux_send_bitset[id] = false;
4042 Session::unmark_return_id (uint32_t id)
4044 if (id < return_bitset.size()) {
4045 return_bitset[id] = false;
4050 Session::unmark_insert_id (uint32_t id)
4052 if (id < insert_bitset.size()) {
4053 insert_bitset[id] = false;
4058 Session::reset_native_file_format ()
4060 boost::shared_ptr<RouteList> rl = routes.reader ();
4061 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4062 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4064 /* don't save state as we do this, there's no point
4067 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4068 tr->reset_write_sources (false);
4069 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4075 Session::route_name_unique (string n) const
4077 boost::shared_ptr<RouteList> r = routes.reader ();
4079 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4080 if ((*i)->name() == n) {
4089 Session::route_name_internal (string n) const
4091 if (auditioner && auditioner->name() == n) {
4095 if (_click_io && _click_io->name() == n) {
4103 Session::freeze_all (InterThreadInfo& itt)
4105 boost::shared_ptr<RouteList> r = routes.reader ();
4107 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4109 boost::shared_ptr<Track> t;
4111 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4112 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4122 boost::shared_ptr<Region>
4123 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4124 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4125 InterThreadInfo& itt,
4126 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4129 boost::shared_ptr<Region> result;
4130 boost::shared_ptr<Playlist> playlist;
4131 boost::shared_ptr<AudioFileSource> fsource;
4133 char buf[PATH_MAX+1];
4134 ChanCount diskstream_channels (track.n_channels());
4135 framepos_t position;
4136 framecnt_t this_chunk;
4138 framepos_t latency_skip;
4140 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4141 const string sound_dir = sdir.sound_path();
4142 framepos_t len = end - start;
4143 bool need_block_size_reset = false;
4145 ChanCount const max_proc = track.max_processor_streams ();
4148 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4149 end, start) << endmsg;
4153 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint, include_endpoint, for_export);
4155 if (diskstream_channels.n_audio() < 1) {
4156 error << _("Cannot write a range with no audio.") << endmsg;
4160 // block all process callback handling
4162 block_processing ();
4165 // synchronize with AudioEngine::process_callback()
4166 // make sure processing is not currently running
4167 // and processing_blocked() is honored before
4168 // acquiring thread buffers
4169 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4172 _bounce_processing_active = true;
4174 /* call tree *MUST* hold route_lock */
4176 if ((playlist = track.playlist()) == 0) {
4180 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4182 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4184 for (x = 0; x < 99999; ++x) {
4185 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());
4186 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
4192 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4197 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4198 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4201 catch (failed_constructor& err) {
4202 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4206 srcs.push_back (fsource);
4209 /* tell redirects that care that we are about to use a much larger
4210 * blocksize. this will flush all plugins too, so that they are ready
4211 * to be used for this process.
4214 need_block_size_reset = true;
4215 track.set_block_size (bounce_chunk_size);
4216 _engine.main_thread()->get_buffers ();
4220 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export);
4222 /* create a set of reasonably-sized buffers */
4223 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4224 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4226 buffers.set_count (max_proc);
4228 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4229 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4231 afs->prepare_for_peakfile_writes ();
4234 while (to_do && !itt.cancel) {
4236 this_chunk = min (to_do, bounce_chunk_size);
4238 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export)) {
4242 start += this_chunk;
4243 to_do -= this_chunk;
4244 itt.progress = (float) (1.0 - ((double) to_do / len));
4246 if (latency_skip >= bounce_chunk_size) {
4247 latency_skip -= bounce_chunk_size;
4251 const framecnt_t current_chunk = this_chunk - latency_skip;
4254 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4255 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4258 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4266 /* post-roll, pick up delayed processor output */
4267 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export);
4269 while (latency_skip && !itt.cancel) {
4270 this_chunk = min (latency_skip, bounce_chunk_size);
4271 latency_skip -= this_chunk;
4273 buffers.silence (this_chunk, 0);
4274 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export);
4277 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4278 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4281 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4293 xnow = localtime (&now);
4295 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4296 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4299 afs->update_header (position, *xnow, now);
4300 afs->flush_header ();
4304 /* construct a region to represent the bounced material */
4308 plist.add (Properties::start, 0);
4309 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4310 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4312 result = RegionFactory::create (srcs, plist);
4318 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4319 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4322 afs->mark_for_remove ();
4325 (*src)->drop_references ();
4329 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4330 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4333 afs->done_with_peakfile_writes ();
4337 _bounce_processing_active = false;
4339 if (need_block_size_reset) {
4340 _engine.main_thread()->drop_buffers ();
4341 track.set_block_size (get_block_size());
4344 unblock_processing ();
4350 Session::gain_automation_buffer() const
4352 return ProcessThread::gain_automation_buffer ();
4356 Session::send_gain_automation_buffer() const
4358 return ProcessThread::send_gain_automation_buffer ();
4362 Session::pan_automation_buffer() const
4364 return ProcessThread::pan_automation_buffer ();
4368 Session::get_silent_buffers (ChanCount count)
4370 return ProcessThread::get_silent_buffers (count);
4374 Session::get_scratch_buffers (ChanCount count, bool silence)
4376 return ProcessThread::get_scratch_buffers (count, silence);
4380 Session::get_route_buffers (ChanCount count, bool silence)
4382 return ProcessThread::get_route_buffers (count, silence);
4387 Session::get_mix_buffers (ChanCount count)
4389 return ProcessThread::get_mix_buffers (count);
4393 Session::ntracks () const
4396 boost::shared_ptr<RouteList> r = routes.reader ();
4398 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4399 if (boost::dynamic_pointer_cast<Track> (*i)) {
4408 Session::nbusses () const
4411 boost::shared_ptr<RouteList> r = routes.reader ();
4413 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4414 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4423 Session::add_automation_list(AutomationList *al)
4425 automation_lists[al->id()] = al;
4428 /** @return true if there is at least one record-enabled track, otherwise false */
4430 Session::have_rec_enabled_track () const
4432 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4435 /** Update the state of our rec-enabled tracks flag */
4437 Session::update_have_rec_enabled_track ()
4439 boost::shared_ptr<RouteList> rl = routes.reader ();
4440 RouteList::iterator i = rl->begin();
4441 while (i != rl->end ()) {
4443 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4444 if (tr && tr->record_enabled ()) {
4451 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4453 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4455 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4456 RecordStateChanged (); /* EMIT SIGNAL */
4461 Session::listen_position_changed ()
4463 boost::shared_ptr<RouteList> r = routes.reader ();
4465 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4466 (*i)->listen_position_changed ();
4471 Session::solo_control_mode_changed ()
4473 /* cancel all solo or all listen when solo control mode changes */
4476 set_solo (get_routes(), false);
4477 } else if (listening()) {
4478 set_listen (get_routes(), false);
4482 /** Called when a property of one of our route groups changes */
4484 Session::route_group_property_changed (RouteGroup* rg)
4486 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4489 /** Called when a route is added to one of our route groups */
4491 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4493 RouteAddedToRouteGroup (rg, r);
4496 /** Called when a route is removed from one of our route groups */
4498 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4500 RouteRemovedFromRouteGroup (rg, r);
4503 boost::shared_ptr<RouteList>
4504 Session::get_routes_with_regions_at (framepos_t const p) const
4506 boost::shared_ptr<RouteList> r = routes.reader ();
4507 boost::shared_ptr<RouteList> rl (new RouteList);
4509 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4510 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4515 boost::shared_ptr<Playlist> pl = tr->playlist ();
4520 if (pl->has_region_at (p)) {
4529 Session::goto_end ()
4531 if (_session_range_location) {
4532 request_locate (_session_range_location->end(), false);
4534 request_locate (0, false);
4539 Session::goto_start ()
4541 if (_session_range_location) {
4542 request_locate (_session_range_location->start(), false);
4544 request_locate (0, false);
4549 Session::current_start_frame () const
4551 return _session_range_location ? _session_range_location->start() : 0;
4555 Session::current_end_frame () const
4557 return _session_range_location ? _session_range_location->end() : 0;
4561 Session::add_session_range_location (framepos_t start, framepos_t end)
4563 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4564 _locations->add (_session_range_location);
4568 Session::step_edit_status_change (bool yn)
4574 send = (_step_editors == 0);
4579 send = (_step_editors == 1);
4582 if (_step_editors > 0) {
4588 StepEditStatusChange (val);
4594 Session::start_time_changed (framepos_t old)
4596 /* Update the auto loop range to match the session range
4597 (unless the auto loop range has been changed by the user)
4600 Location* s = _locations->session_range_location ();
4605 Location* l = _locations->auto_loop_location ();
4607 if (l && l->start() == old) {
4608 l->set_start (s->start(), true);
4613 Session::end_time_changed (framepos_t old)
4615 /* Update the auto loop range to match the session range
4616 (unless the auto loop range has been changed by the user)
4619 Location* s = _locations->session_range_location ();
4624 Location* l = _locations->auto_loop_location ();
4626 if (l && l->end() == old) {
4627 l->set_end (s->end(), true);
4631 std::vector<std::string>
4632 Session::source_search_path (DataType type) const
4636 if (session_dirs.size() == 1) {
4638 case DataType::AUDIO:
4639 sp.push_back (_session_dir->sound_path());
4641 case DataType::MIDI:
4642 sp.push_back (_session_dir->midi_path());
4646 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4647 SessionDirectory sdir (i->path);
4649 case DataType::AUDIO:
4650 sp.push_back (sdir.sound_path());
4652 case DataType::MIDI:
4653 sp.push_back (sdir.midi_path());
4659 if (type == DataType::AUDIO) {
4660 const string sound_path_2X = _session_dir->sound_path_2X();
4661 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4662 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
4663 sp.push_back (sound_path_2X);
4668 // now check the explicit (possibly user-specified) search path
4671 case DataType::AUDIO:
4672 sp += Searchpath(config.get_audio_search_path ());
4674 case DataType::MIDI:
4675 sp += Searchpath(config.get_midi_search_path ());
4683 Session::ensure_search_path_includes (const string& path, DataType type)
4692 case DataType::AUDIO:
4693 sp += Searchpath(config.get_audio_search_path ());
4695 case DataType::MIDI:
4696 sp += Searchpath (config.get_midi_search_path ());
4700 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
4701 /* No need to add this new directory if it has the same inode as
4702 an existing one; checking inode rather than name prevents duplicated
4703 directories when we are using symlinks.
4705 On Windows, I think we could just do if (*i == path) here.
4707 if (PBD::equivalent_paths (*i, path)) {
4715 case DataType::AUDIO:
4716 config.set_audio_search_path (sp.to_string());
4718 case DataType::MIDI:
4719 config.set_midi_search_path (sp.to_string());
4724 boost::shared_ptr<Speakers>
4725 Session::get_speakers()
4731 Session::unknown_processors () const
4735 boost::shared_ptr<RouteList> r = routes.reader ();
4736 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4737 list<string> t = (*i)->unknown_processors ();
4738 copy (t.begin(), t.end(), back_inserter (p));
4748 Session::update_latency (bool playback)
4750 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4752 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4756 boost::shared_ptr<RouteList> r = routes.reader ();
4757 framecnt_t max_latency = 0;
4760 /* reverse the list so that we work backwards from the last route to run to the first */
4761 RouteList* rl = routes.reader().get();
4762 r.reset (new RouteList (*rl));
4763 reverse (r->begin(), r->end());
4766 /* compute actual latency values for the given direction and store them all in per-port
4767 structures. this will also publish the same values (to JACK) so that computation of latency
4768 for routes can consistently use public latency values.
4771 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4772 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4775 /* because we latency compensate playback, our published playback latencies should
4776 be the same for all output ports - all material played back by ardour has
4777 the same latency, whether its caused by plugins or by latency compensation. since
4778 these may differ from the values computed above, reset all playback port latencies
4782 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4784 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4785 (*i)->set_public_port_latencies (max_latency, playback);
4790 post_playback_latency ();
4794 post_capture_latency ();
4797 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4801 Session::post_playback_latency ()
4803 set_worst_playback_latency ();
4805 boost::shared_ptr<RouteList> r = routes.reader ();
4807 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4808 if (!(*i)->is_auditioner() && ((*i)->active())) {
4809 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4813 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4814 (*i)->set_latency_compensation (_worst_track_latency);
4819 Session::post_capture_latency ()
4821 set_worst_capture_latency ();
4823 /* reflect any changes in capture latencies into capture offsets
4826 boost::shared_ptr<RouteList> rl = routes.reader();
4827 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4828 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4830 tr->set_capture_offset ();
4836 Session::initialize_latencies ()
4839 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4840 update_latency (false);
4841 update_latency (true);
4844 set_worst_io_latencies ();
4848 Session::set_worst_io_latencies ()
4850 set_worst_playback_latency ();
4851 set_worst_capture_latency ();
4855 Session::set_worst_playback_latency ()
4857 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4861 _worst_output_latency = 0;
4863 if (!_engine.connected()) {
4867 boost::shared_ptr<RouteList> r = routes.reader ();
4869 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4870 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4873 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4877 Session::set_worst_capture_latency ()
4879 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4883 _worst_input_latency = 0;
4885 if (!_engine.connected()) {
4889 boost::shared_ptr<RouteList> r = routes.reader ();
4891 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4892 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4895 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4899 Session::update_latency_compensation (bool force_whole_graph)
4901 bool some_track_latency_changed = false;
4903 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4907 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4909 _worst_track_latency = 0;
4911 boost::shared_ptr<RouteList> r = routes.reader ();
4913 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4914 if (!(*i)->is_auditioner() && ((*i)->active())) {
4916 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4917 some_track_latency_changed = true;
4919 _worst_track_latency = max (tl, _worst_track_latency);
4923 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4924 (some_track_latency_changed ? "yes" : "no")));
4926 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4928 if (some_track_latency_changed || force_whole_graph) {
4929 _engine.update_latencies ();
4933 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4934 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4938 tr->set_capture_offset ();
4943 Session::session_name_is_legal (const string& path)
4945 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4947 for (int i = 0; illegal_chars[i]; ++i) {
4948 if (path.find (illegal_chars[i]) != string::npos) {
4949 return illegal_chars[i];
4957 Session::next_control_id () const
4961 /* the monitor bus remote ID is in a different
4962 * "namespace" than regular routes. its existence doesn't
4963 * affect normal (low) numbered routes.
4970 return nroutes() - subtract;
4974 Session::notify_remote_id_change ()
4976 if (deletion_in_progress()) {
4980 switch (Config->get_remote_model()) {
4982 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4990 Session::sync_order_keys ()
4992 if (deletion_in_progress()) {
4996 /* tell everyone that something has happened to the sort keys
4997 and let them sync up with the change(s)
4998 this will give objects that manage the sort order keys the
4999 opportunity to keep them in sync if they wish to.
5002 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5004 Route::SyncOrderKeys (); /* EMIT SIGNAL */
5006 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5010 Session::operation_in_progress (GQuark op) const
5012 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5015 boost::shared_ptr<Port>
5016 Session::ltc_input_port () const
5018 return _ltc_input->nth (0);
5021 boost::shared_ptr<Port>
5022 Session::ltc_output_port () const
5024 return _ltc_output->nth (0);
5028 Session::reconnect_ltc_input ()
5032 string src = Config->get_ltc_source_port();
5034 _ltc_input->disconnect (this);
5036 if (src != _("None") && !src.empty()) {
5037 _ltc_input->nth (0)->connect (src);
5043 Session::reconnect_ltc_output ()
5048 string src = Config->get_ltc_sink_port();
5050 _ltc_output->disconnect (this);
5052 if (src != _("None") && !src.empty()) {
5053 _ltc_output->nth (0)->connect (src);