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/stl_delete.h"
42 #include "pbd/basename.h"
43 #include "pbd/stacktrace.h"
44 #include "pbd/file_utils.h"
45 #include "pbd/convert.h"
46 #include "pbd/unwind.h"
47 #include "pbd/search_path.h"
49 #include "ardour/amp.h"
50 #include "ardour/analyser.h"
51 #include "ardour/async_midi_port.h"
52 #include "ardour/audio_buffer.h"
53 #include "ardour/audio_diskstream.h"
54 #include "ardour/audio_port.h"
55 #include "ardour/audio_track.h"
56 #include "ardour/audioengine.h"
57 #include "ardour/audiofilesource.h"
58 #include "ardour/auditioner.h"
59 #include "ardour/buffer_manager.h"
60 #include "ardour/buffer_set.h"
61 #include "ardour/bundle.h"
62 #include "ardour/butler.h"
63 #include "ardour/click.h"
64 #include "ardour/control_protocol_manager.h"
65 #include "ardour/data_type.h"
66 #include "ardour/debug.h"
67 #include "ardour/filename_extensions.h"
68 #include "ardour/graph.h"
69 #include "ardour/midiport_manager.h"
70 #include "ardour/scene_changer.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/midi_ui.h"
73 #include "ardour/operations.h"
74 #include "ardour/playlist.h"
75 #include "ardour/plugin.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/rc_configuration.h"
79 #include "ardour/recent_sessions.h"
80 #include "ardour/region.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/route_graph.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_playlists.h"
88 #include "ardour/smf_source.h"
89 #include "ardour/source_factory.h"
90 #include "ardour/speakers.h"
91 #include "ardour/track.h"
92 #include "ardour/utils.h"
94 #include "midi++/port.h"
95 #include "midi++/mmc.h"
106 using namespace ARDOUR;
109 bool Session::_disable_all_loaded_plugins = false;
111 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
112 PBD::Signal1<void,std::string> Session::Dialog;
113 PBD::Signal0<int> Session::AskAboutPendingState;
114 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
115 PBD::Signal0<void> Session::SendFeedback;
116 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
118 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
119 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
120 PBD::Signal2<void,std::string, std::string> Session::Exported;
121 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
122 PBD::Signal0<void> Session::Quit;
123 PBD::Signal0<void> Session::FeedbackDetected;
124 PBD::Signal0<void> Session::SuccessfulGraphSort;
125 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
127 const framecnt_t Session::bounce_chunk_size = 65536;
128 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
129 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
131 /** @param snapshot_name Snapshot name, without .ardour suffix */
132 Session::Session (AudioEngine &eng,
133 const string& fullpath,
134 const string& snapshot_name,
135 BusProfile* bus_profile,
137 : playlists (new SessionPlaylists)
139 , process_function (&Session::process_with_events)
140 , _bounce_processing_active (false)
141 , waiting_for_sync_offset (false)
142 , _base_frame_rate (0)
143 , _current_frame_rate (0)
144 , _nominal_frame_rate (0)
145 , transport_sub_state (0)
146 , _record_status (Disabled)
147 , _transport_frame (0)
148 , _session_range_location (0)
151 , _transport_speed (0)
152 , _default_transport_speed (1.0)
153 , _last_transport_speed (0)
154 , _target_transport_speed (0.0)
155 , auto_play_legal (false)
156 , _last_slave_transport_frame (0)
157 , maximum_output_latency (0)
158 , _requested_return_frame (-1)
159 , current_block_size (0)
160 , _worst_output_latency (0)
161 , _worst_input_latency (0)
162 , _worst_track_latency (0)
163 , _have_captured (false)
166 , _non_soloed_outs_muted (false)
168 , _solo_isolated_cnt (0)
170 , _was_seamless (Config->get_seamless_loop ())
171 , _under_nsm_control (false)
172 , delta_accumulator_cnt (0)
173 , average_slave_delta (1800) // !!! why 1800 ???
175 , have_first_delta_accumulator (false)
176 , _slave_state (Stopped)
177 , post_export_sync (false)
178 , post_export_position (0)
180 , _export_started (false)
181 , _export_rolling (false)
182 , _pre_export_mmc_enabled (false)
183 , _name (snapshot_name)
185 , _send_qf_mtc (false)
186 , _pframes_since_last_mtc (0)
187 , session_midi_feedback (0)
189 , loop_changing (false)
191 , _session_dir (new SessionDirectory (fullpath))
192 , _current_snapshot_name (snapshot_name)
194 , state_was_pending (false)
195 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
196 , _last_roll_location (0)
197 , _last_roll_or_reversal_location (0)
198 , _last_record_location (0)
199 , pending_locate_roll (false)
200 , pending_locate_frame (0)
201 , pending_locate_flush (false)
202 , pending_abort (false)
203 , pending_auto_loop (false)
204 , _butler (new Butler (*this))
205 , _post_transport_work (0)
206 , cumulative_rf_motion (0)
208 , _locations (new Locations (*this))
210 , outbound_mtc_timecode_frame (0)
211 , next_quarter_frame_to_send (-1)
212 , _frames_per_timecode_frame (0)
213 , _frames_per_hour (0)
214 , _timecode_frames_per_hour (0)
215 , last_timecode_valid (false)
216 , last_timecode_when (0)
217 , _send_timecode_update (false)
229 , ltc_timecode_offset (0)
230 , ltc_timecode_negative_offset (false)
231 , midi_control_ui (0)
233 , _all_route_group (new RouteGroup (*this, "all"))
234 , routes (new RouteList)
235 , _adding_routes_in_progress (false)
236 , destructive_index (0)
237 , solo_update_disabled (false)
238 , default_fade_steepness (0)
239 , default_fade_msecs (0)
240 , _total_free_4k_blocks (0)
241 , _total_free_4k_blocks_uncertain (false)
242 , no_questions_about_missing_files (false)
245 , _bundles (new BundleList)
246 , _bundle_xml_node (0)
250 , click_emphasis_data (0)
252 , click_emphasis_length (0)
253 , _clicks_cleared (0)
254 , _play_range (false)
256 , first_file_data_format_reset (true)
257 , first_file_header_format_reset (true)
258 , have_looped (false)
259 , _have_rec_enabled_track (false)
261 , _suspend_timecode_transmission (0)
262 , _speakers (new Speakers)
264 , ignore_route_processor_changes (false)
271 pre_engine_init (fullpath);
274 if (ensure_engine (sr)) {
276 throw failed_constructor ();
279 if (create (mix_template, bus_profile)) {
281 throw failed_constructor ();
284 /* if a mix template was provided, then ::create() will
285 * have copied it into the session and we need to load it
286 * so that we have the state ready for ::set_state()
287 * after the engine is started.
289 * Note that we do NOT try to get the sample rate from
290 * the template at this time, though doing so would
291 * be easy if we decided this was an appropriate part
295 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
296 throw failed_constructor ();
301 if (load_state (_current_snapshot_name)) {
302 throw failed_constructor ();
305 /* try to get sample rate from XML state so that we
306 * can influence the SR if we set up the audio
311 const XMLProperty* prop;
312 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
313 sr = atoi (prop->value());
317 if (ensure_engine (sr)) {
319 throw failed_constructor ();
323 if (post_engine_init ()) {
325 throw failed_constructor ();
328 store_recent_sessions (_name, _path);
330 bool was_dirty = dirty();
332 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
334 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
335 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
338 DirtyChanged (); /* EMIT SIGNAL */
341 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
342 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
346 /* hook us up to the engine since we are now completely constructed */
348 BootMessage (_("Connect to engine"));
350 _engine.set_session (this);
351 _engine.reset_timebase ();
353 BootMessage (_("Session loading complete"));
366 Session::ensure_engine (uint32_t desired_sample_rate)
368 if (_engine.current_backend() == 0) {
369 /* backend is unknown ... */
370 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
371 if (r.get_value_or (-1) != 0) {
374 } else if (_engine.setup_required()) {
375 /* backend is known, but setup is needed */
376 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
377 if (r.get_value_or (-1) != 0) {
380 } else if (!_engine.running()) {
381 if (_engine.start()) {
386 /* at this point the engine should be running
389 if (!_engine.running()) {
393 return immediately_post_engine ();
398 Session::immediately_post_engine ()
400 /* Do various initializations that should take place directly after we
401 * know that the engine is running, but before we either create a
402 * session or set state for an existing one.
405 if (how_many_dsp_threads () > 1) {
406 /* For now, only create the graph if we are using >1 DSP threads, as
407 it is a bit slower than the old code with 1 thread.
409 _process_graph.reset (new Graph (*this));
412 /* every time we reconnect, recompute worst case output latencies */
414 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
416 if (synced_to_engine()) {
417 _engine.transport_stop ();
420 if (config.get_jack_time_master()) {
421 _engine.transport_locate (_transport_frame);
425 BootMessage (_("Set up LTC"));
427 BootMessage (_("Set up Click"));
429 BootMessage (_("Set up standard connections"));
433 catch (failed_constructor& err) {
443 vector<void*> debug_pointers;
445 /* if we got to here, leaving pending capture state around
449 remove_pending_capture_state ();
451 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
453 /* disconnect from any and all signals that we are connected to */
457 _engine.remove_session ();
459 /* deregister all ports - there will be no process or any other
460 * callbacks from the engine any more.
463 Port::PortDrop (); /* EMIT SIGNAL */
467 /* clear history so that no references to objects are held any more */
471 /* clear state tree so that no references to objects are held any more */
475 /* reset dynamic state version back to default */
477 Stateful::loading_state_version = 0;
479 _butler->drop_references ();
483 delete midi_control_ui;
484 delete _all_route_group;
486 if (click_data != default_click) {
487 delete [] click_data;
490 if (click_emphasis_data != default_click_emphasis) {
491 delete [] click_emphasis_data;
496 /* clear out any pending dead wood from RCU managed objects */
501 AudioDiskstream::free_working_buffers();
503 /* tell everyone who is still standing that we're about to die */
506 /* tell everyone to drop references and delete objects as we go */
508 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
509 RegionFactory::delete_all_regions ();
511 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
513 /* reset these three references to special routes before we do the usual route delete thing */
516 _master_out.reset ();
517 _monitor_out.reset ();
520 RCUWriter<RouteList> writer (routes);
521 boost::shared_ptr<RouteList> r = writer.get_copy ();
523 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
524 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
525 (*i)->drop_references ();
529 /* writer goes out of scope and updates master */
534 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
535 Glib::Threads::Mutex::Lock lm (source_lock);
536 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
537 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
538 i->second->drop_references ();
544 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
545 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
550 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
553 delete _scene_changer; _scene_changer = 0;
555 delete _mmc; _mmc = 0;
556 delete _midi_ports; _midi_ports = 0;
557 delete _locations; _locations = 0;
559 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
561 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
562 boost_debug_list_ptrs ();
567 Session::setup_ltc ()
571 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
572 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
574 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
575 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
578 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
579 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
581 reconnect_ltc_input ();
584 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
585 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
588 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
589 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
591 reconnect_ltc_output ();
594 /* fix up names of LTC ports because we don't want the normal
595 * IO style of NAME/TYPE-{in,out}N
598 _ltc_input->nth (0)->set_name (X_("LTC-in"));
599 _ltc_output->nth (0)->set_name (X_("LTC-out"));
603 Session::setup_click ()
606 _click_io.reset (new ClickIO (*this, X_("Click")));
607 _click_gain.reset (new Amp (*this));
608 _click_gain->activate ();
610 setup_click_state (state_tree->root());
612 setup_click_state (0);
617 Session::setup_click_state (const XMLNode* node)
619 const XMLNode* child = 0;
621 if (node && (child = find_named_node (*node, "Click")) != 0) {
623 /* existing state for Click */
626 if (Stateful::loading_state_version < 3000) {
627 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
629 const XMLNodeList& children (child->children());
630 XMLNodeList::const_iterator i = children.begin();
631 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
633 if (i != children.end()) {
634 c = _click_gain->set_state (**i, Stateful::loading_state_version);
640 _clicking = Config->get_clicking ();
644 error << _("could not setup Click I/O") << endmsg;
651 /* default state for Click: dual-mono to first 2 physical outputs */
654 _engine.get_physical_outputs (DataType::AUDIO, outs);
656 for (uint32_t physport = 0; physport < 2; ++physport) {
657 if (outs.size() > physport) {
658 if (_click_io->add_port (outs[physport], this)) {
659 // relax, even though its an error
664 if (_click_io->n_ports () > ChanCount::ZERO) {
665 _clicking = Config->get_clicking ();
671 Session::setup_bundles ()
673 vector<string> inputs[DataType::num_types];
674 vector<string> outputs[DataType::num_types];
675 for (uint32_t i = 0; i < DataType::num_types; ++i) {
676 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
677 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
680 /* Create a set of Bundle objects that map
681 to the physical I/O currently available. We create both
682 mono and stereo bundles, so that the common cases of mono
683 and stereo tracks get bundles to put in their mixer strip
684 in / out menus. There may be a nicer way of achieving that;
685 it doesn't really scale that well to higher channel counts
688 /* mono output bundles */
690 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
692 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
694 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
695 c->add_channel (_("mono"), DataType::AUDIO);
696 c->set_port (0, outputs[DataType::AUDIO][np]);
701 /* stereo output bundles */
703 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
704 if (np + 1 < outputs[DataType::AUDIO].size()) {
706 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
707 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
708 c->add_channel (_("L"), DataType::AUDIO);
709 c->set_port (0, outputs[DataType::AUDIO][np]);
710 c->add_channel (_("R"), DataType::AUDIO);
711 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
717 /* mono input bundles */
719 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
721 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
723 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
724 c->add_channel (_("mono"), DataType::AUDIO);
725 c->set_port (0, inputs[DataType::AUDIO][np]);
730 /* stereo input bundles */
732 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
733 if (np + 1 < inputs[DataType::AUDIO].size()) {
735 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
737 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
738 c->add_channel (_("L"), DataType::AUDIO);
739 c->set_port (0, inputs[DataType::AUDIO][np]);
740 c->add_channel (_("R"), DataType::AUDIO);
741 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
747 /* MIDI input bundles */
749 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
750 string n = inputs[DataType::MIDI][np];
751 boost::erase_first (n, X_("alsa_pcm:"));
753 boost::shared_ptr<Bundle> c (new Bundle (n, false));
754 c->add_channel ("", DataType::MIDI);
755 c->set_port (0, inputs[DataType::MIDI][np]);
759 /* MIDI output bundles */
761 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
762 string n = outputs[DataType::MIDI][np];
763 boost::erase_first (n, X_("alsa_pcm:"));
765 boost::shared_ptr<Bundle> c (new Bundle (n, true));
766 c->add_channel ("", DataType::MIDI);
767 c->set_port (0, outputs[DataType::MIDI][np]);
774 Session::auto_connect_master_bus ()
776 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
780 /* if requested auto-connect the outputs to the first N physical ports.
783 uint32_t limit = _master_out->n_outputs().n_total();
784 vector<string> outputs[DataType::num_types];
786 for (uint32_t i = 0; i < DataType::num_types; ++i) {
787 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
790 for (uint32_t n = 0; n < limit; ++n) {
791 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
793 if (outputs[p->type()].size() > n) {
794 connect_to = outputs[p->type()][n];
797 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
798 if (_master_out->output()->connect (p, connect_to, this)) {
799 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
808 Session::remove_monitor_section ()
814 /* force reversion to Solo-In-Place */
815 Config->set_solo_control_is_listen_control (false);
817 /* if we are auditioning, cancel it ... this is a workaround
818 to a problem (auditioning does not execute the process graph,
819 which is needed to remove routes when using >1 core for processing)
824 /* Hold process lock while doing this so that we don't hear bits and
825 * pieces of audio as we work on each route.
828 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
830 /* Connect tracks to monitor section. Note that in an
831 existing session, the internal sends will already exist, but we want the
832 routes to notice that they connect to the control out specifically.
836 boost::shared_ptr<RouteList> r = routes.reader ();
837 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
839 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
841 if ((*x)->is_monitor()) {
843 } else if ((*x)->is_master()) {
846 (*x)->remove_aux_or_listen (_monitor_out);
851 remove_route (_monitor_out);
852 auto_connect_master_bus ();
855 auditioner->connect ();
860 Session::add_monitor_section ()
864 if (_monitor_out || !_master_out) {
868 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
874 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
875 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
878 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
879 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
880 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
884 add_routes (rl, false, false, false);
886 assert (_monitor_out);
888 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
889 are undefined, at best.
892 uint32_t limit = _monitor_out->n_inputs().n_audio();
896 /* connect the inputs to the master bus outputs. this
897 * represents a separate data feed from the internal sends from
898 * each route. as of jan 2011, it allows the monitor section to
899 * conditionally ignore either the internal sends or the normal
900 * input feed, but we should really find a better way to do
904 _master_out->output()->disconnect (this);
906 for (uint32_t n = 0; n < limit; ++n) {
907 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
908 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
911 string connect_to = o->name();
912 if (_monitor_out->input()->connect (p, connect_to, this)) {
913 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
921 /* if monitor section is not connected, connect it to physical outs
924 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
926 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
928 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
931 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
933 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
934 Config->get_monitor_bus_preferred_bundle())
940 /* Monitor bus is audio only */
942 vector<string> outputs[DataType::num_types];
944 for (uint32_t i = 0; i < DataType::num_types; ++i) {
945 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
948 uint32_t mod = outputs[DataType::AUDIO].size();
949 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
953 for (uint32_t n = 0; n < limit; ++n) {
955 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
957 if (outputs[DataType::AUDIO].size() > (n % mod)) {
958 connect_to = outputs[DataType::AUDIO][n % mod];
961 if (!connect_to.empty()) {
962 if (_monitor_out->output()->connect (p, connect_to, this)) {
963 error << string_compose (
964 _("cannot connect control output %1 to %2"),
975 /* Hold process lock while doing this so that we don't hear bits and
976 * pieces of audio as we work on each route.
979 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
981 /* Connect tracks to monitor section. Note that in an
982 existing session, the internal sends will already exist, but we want the
983 routes to notice that they connect to the control out specifically.
987 boost::shared_ptr<RouteList> rls = routes.reader ();
989 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
991 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
993 if ((*x)->is_monitor()) {
995 } else if ((*x)->is_master()) {
998 (*x)->enable_monitor_send ();
1003 auditioner->connect ();
1008 Session::hookup_io ()
1010 /* stop graph reordering notifications from
1011 causing resorts, etc.
1014 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1018 /* we delay creating the auditioner till now because
1019 it makes its own connections to ports.
1023 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1025 throw failed_constructor ();
1027 a->use_new_diskstream ();
1031 catch (failed_constructor& err) {
1032 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1036 /* load bundles, which we may have postponed earlier on */
1037 if (_bundle_xml_node) {
1038 load_bundles (*_bundle_xml_node);
1039 delete _bundle_xml_node;
1042 /* Tell all IO objects to connect themselves together */
1044 IO::enable_connecting ();
1046 /* Now tell all "floating" ports to connect to whatever
1047 they should be connected to.
1050 AudioEngine::instance()->reconnect_ports ();
1052 /* Anyone who cares about input state, wake up and do something */
1054 IOConnectionsComplete (); /* EMIT SIGNAL */
1056 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1058 /* now handle the whole enchilada as if it was one
1059 graph reorder event.
1064 /* update the full solo state, which can't be
1065 correctly determined on a per-route basis, but
1066 needs the global overview that only the session
1070 update_route_solo_state ();
1074 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1076 boost::shared_ptr<Track> track = wp.lock ();
1081 boost::shared_ptr<Playlist> playlist;
1083 if ((playlist = track->playlist()) != 0) {
1084 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1085 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1086 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1091 Session::record_enabling_legal () const
1093 /* this used to be in here, but survey says.... we don't need to restrict it */
1094 // if (record_status() == Recording) {
1098 if (Config->get_all_safe()) {
1105 Session::set_track_monitor_input_status (bool yn)
1107 boost::shared_ptr<RouteList> rl = routes.reader ();
1108 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1109 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1110 if (tr && tr->record_enabled ()) {
1111 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1112 tr->request_input_monitoring (yn);
1118 Session::auto_punch_start_changed (Location* location)
1120 replace_event (SessionEvent::PunchIn, location->start());
1122 if (get_record_enabled() && config.get_punch_in()) {
1123 /* capture start has been changed, so save new pending state */
1124 save_state ("", true);
1129 Session::auto_punch_end_changed (Location* location)
1131 framepos_t when_to_stop = location->end();
1132 // when_to_stop += _worst_output_latency + _worst_input_latency;
1133 replace_event (SessionEvent::PunchOut, when_to_stop);
1137 Session::auto_punch_changed (Location* location)
1139 framepos_t when_to_stop = location->end();
1141 replace_event (SessionEvent::PunchIn, location->start());
1142 //when_to_stop += _worst_output_latency + _worst_input_latency;
1143 replace_event (SessionEvent::PunchOut, when_to_stop);
1146 /** @param loc A loop location.
1147 * @param pos Filled in with the start time of the required fade-out (in session frames).
1148 * @param length Filled in with the length of the required fade-out.
1151 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1153 pos = max (loc->start(), loc->end() - 64);
1154 length = loc->end() - pos;
1158 Session::auto_loop_changed (Location* location)
1160 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1163 auto_loop_declick_range (location, dcp, dcl);
1164 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1166 if (transport_rolling() && play_loop) {
1169 // if (_transport_frame > location->end()) {
1171 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1172 // relocate to beginning of loop
1173 clear_events (SessionEvent::LocateRoll);
1175 request_locate (location->start(), true);
1178 else if (Config->get_seamless_loop() && !loop_changing) {
1180 // schedule a locate-roll to refill the diskstreams at the
1181 // previous loop end
1182 loop_changing = true;
1184 if (location->end() > last_loopend) {
1185 clear_events (SessionEvent::LocateRoll);
1186 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1193 last_loopend = location->end();
1197 Session::set_auto_punch_location (Location* location)
1201 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1202 punch_connections.drop_connections();
1203 existing->set_auto_punch (false, this);
1204 remove_event (existing->start(), SessionEvent::PunchIn);
1205 clear_events (SessionEvent::PunchOut);
1206 auto_punch_location_changed (0);
1211 if (location == 0) {
1215 if (location->end() <= location->start()) {
1216 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1220 punch_connections.drop_connections ();
1222 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1223 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1224 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1226 location->set_auto_punch (true, this);
1228 auto_punch_changed (location);
1230 auto_punch_location_changed (location);
1234 Session::set_auto_loop_location (Location* location)
1238 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1239 loop_connections.drop_connections ();
1240 existing->set_auto_loop (false, this);
1241 remove_event (existing->end(), SessionEvent::AutoLoop);
1244 auto_loop_declick_range (existing, dcp, dcl);
1245 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1246 auto_loop_location_changed (0);
1251 if (location == 0) {
1255 if (location->end() <= location->start()) {
1256 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1260 last_loopend = location->end();
1262 loop_connections.drop_connections ();
1264 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1265 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1266 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1268 location->set_auto_loop (true, this);
1270 /* take care of our stuff first */
1272 auto_loop_changed (location);
1274 /* now tell everyone else */
1276 auto_loop_location_changed (location);
1280 Session::locations_added (Location *)
1286 Session::locations_changed ()
1288 _locations->apply (*this, &Session::handle_locations_changed);
1292 Session::handle_locations_changed (Locations::LocationList& locations)
1294 Locations::LocationList::iterator i;
1296 bool set_loop = false;
1297 bool set_punch = false;
1299 for (i = locations.begin(); i != locations.end(); ++i) {
1303 if (location->is_auto_punch()) {
1304 set_auto_punch_location (location);
1307 if (location->is_auto_loop()) {
1308 set_auto_loop_location (location);
1312 if (location->is_session_range()) {
1313 _session_range_location = location;
1318 set_auto_loop_location (0);
1321 set_auto_punch_location (0);
1328 Session::enable_record ()
1330 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1331 /* no recording at anything except normal speed */
1336 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1338 if (rs == Recording) {
1342 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1344 _last_record_location = _transport_frame;
1345 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1347 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1348 set_track_monitor_input_status (true);
1351 RecordStateChanged ();
1358 Session::disable_record (bool rt_context, bool force)
1362 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1364 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1365 g_atomic_int_set (&_record_status, Disabled);
1366 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1368 if (rs == Recording) {
1369 g_atomic_int_set (&_record_status, Enabled);
1373 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1374 set_track_monitor_input_status (false);
1377 RecordStateChanged (); /* emit signal */
1380 remove_pending_capture_state ();
1386 Session::step_back_from_record ()
1388 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1390 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1391 set_track_monitor_input_status (false);
1394 RecordStateChanged (); /* emit signal */
1399 Session::maybe_enable_record ()
1401 if (_step_editors > 0) {
1405 g_atomic_int_set (&_record_status, Enabled);
1407 /* This function is currently called from somewhere other than an RT thread.
1408 This save_state() call therefore doesn't impact anything. Doing it here
1409 means that we save pending state of which sources the next record will use,
1410 which gives us some chance of recovering from a crash during the record.
1413 save_state ("", true);
1415 if (_transport_speed) {
1416 if (!config.get_punch_in()) {
1420 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1421 RecordStateChanged (); /* EMIT SIGNAL */
1428 Session::audible_frame () const
1434 /* the first of these two possible settings for "offset"
1435 mean that the audible frame is stationary until
1436 audio emerges from the latency compensation
1439 the second means that the audible frame is stationary
1440 until audio would emerge from a physical port
1441 in the absence of any plugin latency compensation
1444 offset = worst_playback_latency ();
1446 if (offset > current_block_size) {
1447 offset -= current_block_size;
1449 /* XXX is this correct? if we have no external
1450 physical connections and everything is internal
1451 then surely this is zero? still, how
1452 likely is that anyway?
1454 offset = current_block_size;
1457 if (synced_to_engine()) {
1458 tf = _engine.transport_frame();
1460 tf = _transport_frame;
1465 if (!non_realtime_work_pending()) {
1469 /* Check to see if we have passed the first guaranteed
1470 audible frame past our last start position. if not,
1471 return that last start point because in terms
1472 of audible frames, we have not moved yet.
1474 `Start position' in this context means the time we last
1475 either started, located, or changed transport direction.
1478 if (_transport_speed > 0.0f) {
1480 if (!play_loop || !have_looped) {
1481 if (tf < _last_roll_or_reversal_location + offset) {
1482 return _last_roll_or_reversal_location;
1490 } else if (_transport_speed < 0.0f) {
1492 /* XXX wot? no backward looping? */
1494 if (tf > _last_roll_or_reversal_location - offset) {
1495 return _last_roll_or_reversal_location;
1507 Session::set_frame_rate (framecnt_t frames_per_second)
1509 /** \fn void Session::set_frame_size(framecnt_t)
1510 the AudioEngine object that calls this guarantees
1511 that it will not be called while we are also in
1512 ::process(). Its fine to do things that block
1516 _base_frame_rate = frames_per_second;
1517 _nominal_frame_rate = frames_per_second;
1523 // XXX we need some equivalent to this, somehow
1524 // SndFileSource::setup_standard_crossfades (frames_per_second);
1528 /* XXX need to reset/reinstantiate all LADSPA plugins */
1532 Session::set_block_size (pframes_t nframes)
1534 /* the AudioEngine guarantees
1535 that it will not be called while we are also in
1536 ::process(). It is therefore fine to do things that block
1541 current_block_size = nframes;
1545 boost::shared_ptr<RouteList> r = routes.reader ();
1547 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1548 (*i)->set_block_size (nframes);
1551 boost::shared_ptr<RouteList> rl = routes.reader ();
1552 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1553 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1555 tr->set_block_size (nframes);
1559 set_worst_io_latencies ();
1565 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1567 boost::shared_ptr<Route> r2;
1569 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1570 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1574 /* make a copy of the existing list of routes that feed r1 */
1576 Route::FedBy existing (r1->fed_by());
1578 /* for each route that feeds r1, recurse, marking it as feeding
1582 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1583 if (!(r2 = i->r.lock ())) {
1584 /* (*i) went away, ignore it */
1588 /* r2 is a route that feeds r1 which somehow feeds base. mark
1589 base as being fed by r2
1592 rbase->add_fed_by (r2, i->sends_only);
1596 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1600 if (r1->feeds (r2) && r2->feeds (r1)) {
1604 /* now recurse, so that we can mark base as being fed by
1605 all routes that feed r2
1608 trace_terminal (r2, rbase);
1615 Session::resort_routes ()
1617 /* don't do anything here with signals emitted
1618 by Routes during initial setup or while we
1619 are being destroyed.
1622 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1627 RCUWriter<RouteList> writer (routes);
1628 boost::shared_ptr<RouteList> r = writer.get_copy ();
1629 resort_routes_using (r);
1630 /* writer goes out of scope and forces update */
1634 boost::shared_ptr<RouteList> rl = routes.reader ();
1635 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1636 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1638 const Route::FedBy& fb ((*i)->fed_by());
1640 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1641 boost::shared_ptr<Route> sf = f->r.lock();
1643 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1651 /** This is called whenever we need to rebuild the graph of how we will process
1653 * @param r List of routes, in any order.
1657 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1659 /* We are going to build a directed graph of our routes;
1660 this is where the edges of that graph are put.
1665 /* Go through all routes doing two things:
1667 * 1. Collect the edges of the route graph. Each of these edges
1668 * is a pair of routes, one of which directly feeds the other
1669 * either by a JACK connection or by an internal send.
1671 * 2. Begin the process of making routes aware of which other
1672 * routes directly or indirectly feed them. This information
1673 * is used by the solo code.
1676 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1678 /* Clear out the route's list of direct or indirect feeds */
1679 (*i)->clear_fed_by ();
1681 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1683 bool via_sends_only;
1685 /* See if this *j feeds *i according to the current state of the JACK
1686 connections and internal sends.
1688 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1689 /* add the edge to the graph (part #1) */
1690 edges.add (*j, *i, via_sends_only);
1691 /* tell the route (for part #2) */
1692 (*i)->add_fed_by (*j, via_sends_only);
1697 /* Attempt a topological sort of the route graph */
1698 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1700 if (sorted_routes) {
1701 /* We got a satisfactory topological sort, so there is no feedback;
1704 Note: the process graph rechain does not require a
1705 topologically-sorted list, but hey ho.
1707 if (_process_graph) {
1708 _process_graph->rechain (sorted_routes, edges);
1711 _current_route_graph = edges;
1713 /* Complete the building of the routes' lists of what directly
1714 or indirectly feeds them.
1716 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1717 trace_terminal (*i, *i);
1720 *r = *sorted_routes;
1723 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1724 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1725 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1726 (*i)->name(), (*i)->order_key ()));
1730 SuccessfulGraphSort (); /* EMIT SIGNAL */
1733 /* The topological sort failed, so we have a problem. Tell everyone
1734 and stick to the old graph; this will continue to be processed, so
1735 until the feedback is fixed, what is played back will not quite
1736 reflect what is actually connected. Note also that we do not
1737 do trace_terminal here, as it would fail due to an endless recursion,
1738 so the solo code will think that everything is still connected
1742 FeedbackDetected (); /* EMIT SIGNAL */
1747 /** Find a route name starting with \a base, maybe followed by the
1748 * lowest \a id. \a id will always be added if \a definitely_add_number
1749 * is true on entry; otherwise it will only be added if required
1750 * to make the name unique.
1752 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1753 * The available route name with the lowest ID will be used, and \a id
1754 * will be set to the ID.
1756 * \return false if a route name could not be found, and \a track_name
1757 * and \a id do not reflect a free route name.
1760 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1762 if (!definitely_add_number && route_by_name (base) == 0) {
1763 /* juse use the base */
1764 snprintf (name, name_len, "%s", base.c_str());
1769 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1771 if (route_by_name (name) == 0) {
1777 } while (id < (UINT_MAX-1));
1782 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1784 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1786 in = ChanCount::ZERO;
1787 out = ChanCount::ZERO;
1789 boost::shared_ptr<RouteList> r = routes.reader ();
1791 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1792 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1793 if (tr && !tr->is_auditioner()) {
1794 in += tr->n_inputs();
1795 out += tr->n_outputs();
1800 /** Caller must not hold process lock
1801 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1802 * @param instrument plugin info for the instrument to insert pre-fader, if any
1804 list<boost::shared_ptr<MidiTrack> >
1805 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1806 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1808 char track_name[32];
1809 uint32_t track_id = 0;
1811 RouteList new_routes;
1812 list<boost::shared_ptr<MidiTrack> > ret;
1814 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1817 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1818 error << "cannot find name for new midi track" << endmsg;
1822 boost::shared_ptr<MidiTrack> track;
1825 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1827 if (track->init ()) {
1831 track->use_new_diskstream();
1833 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1834 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1837 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1838 if (track->input()->ensure_io (input, false, this)) {
1839 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1843 if (track->output()->ensure_io (output, false, this)) {
1844 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1849 track->non_realtime_input_change();
1852 route_group->add (track);
1855 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1857 if (Config->get_remote_model() == UserOrdered) {
1858 track->set_remote_control_id (next_control_id());
1861 new_routes.push_back (track);
1862 ret.push_back (track);
1865 catch (failed_constructor &err) {
1866 error << _("Session: could not create new midi track.") << endmsg;
1870 catch (AudioEngine::PortRegistrationFailure& pfe) {
1872 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;
1880 if (!new_routes.empty()) {
1881 add_routes (new_routes, true, true, true);
1884 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1885 PluginPtr plugin = instrument->load (*this);
1886 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1887 (*r)->add_processor (p, PreFader);
1897 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1899 boost::shared_ptr<Route> midi_track (wmt.lock());
1905 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1907 if (change.after.n_audio() <= change.before.n_audio()) {
1911 /* new audio ports: make sure the audio goes somewhere useful,
1912 unless the user has no-auto-connect selected.
1914 The existing ChanCounts don't matter for this call as they are only
1915 to do with matching input and output indices, and we are only changing
1921 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1925 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1926 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1927 * @param output_start As \a input_start, but for outputs.
1930 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1931 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1933 if (!IO::connecting_legal) {
1937 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1943 /* If both inputs and outputs are auto-connected to physical ports,
1944 use the max of input and output offsets to ensure auto-connected
1945 port numbers always match up (e.g. the first audio input and the
1946 first audio output of the route will have the same physical
1947 port number). Otherwise just use the lowest input or output
1951 DEBUG_TRACE (DEBUG::Graph,
1952 string_compose("Auto-connect: existing in = %1 out = %2\n",
1953 existing_inputs, existing_outputs));
1955 const bool in_out_physical =
1956 (Config->get_input_auto_connect() & AutoConnectPhysical)
1957 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1960 const ChanCount in_offset = in_out_physical
1961 ? ChanCount::max(existing_inputs, existing_outputs)
1964 const ChanCount out_offset = in_out_physical
1965 ? ChanCount::max(existing_inputs, existing_outputs)
1968 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1969 vector<string> physinputs;
1970 vector<string> physoutputs;
1972 _engine.get_physical_outputs (*t, physoutputs);
1973 _engine.get_physical_inputs (*t, physinputs);
1975 if (!physinputs.empty() && connect_inputs) {
1976 uint32_t nphysical_in = physinputs.size();
1978 DEBUG_TRACE (DEBUG::Graph,
1979 string_compose("There are %1 physical inputs of type %2\n",
1982 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1985 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1986 DEBUG_TRACE (DEBUG::Graph,
1987 string_compose("Get index %1 + %2 % %3 = %4\n",
1988 in_offset.get(*t), i, nphysical_in,
1989 (in_offset.get(*t) + i) % nphysical_in));
1990 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1993 DEBUG_TRACE (DEBUG::Graph,
1994 string_compose("Connect route %1 IN to %2\n",
1995 route->name(), port));
1997 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2001 ChanCount one_added (*t, 1);
2002 existing_inputs += one_added;
2006 if (!physoutputs.empty()) {
2007 uint32_t nphysical_out = physoutputs.size();
2008 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2011 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2012 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2013 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2014 /* master bus is audio only */
2015 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2016 port = _master_out->input()->ports().port(*t,
2017 i % _master_out->input()->n_ports().get(*t))->name();
2021 DEBUG_TRACE (DEBUG::Graph,
2022 string_compose("Connect route %1 OUT to %2\n",
2023 route->name(), port));
2025 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2029 ChanCount one_added (*t, 1);
2030 existing_outputs += one_added;
2036 /** Caller must not hold process lock
2037 * @param name_template string to use for the start of the name, or "" to use "Audio".
2039 list< boost::shared_ptr<AudioTrack> >
2040 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2041 uint32_t how_many, string name_template)
2043 char track_name[32];
2044 uint32_t track_id = 0;
2046 RouteList new_routes;
2047 list<boost::shared_ptr<AudioTrack> > ret;
2049 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2052 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2053 error << "cannot find name for new audio track" << endmsg;
2057 boost::shared_ptr<AudioTrack> track;
2060 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2062 if (track->init ()) {
2066 track->use_new_diskstream();
2068 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2069 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2072 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2074 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2075 error << string_compose (
2076 _("cannot configure %1 in/%2 out configuration for new audio track"),
2077 input_channels, output_channels)
2082 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2083 error << string_compose (
2084 _("cannot configure %1 in/%2 out configuration for new audio track"),
2085 input_channels, output_channels)
2092 route_group->add (track);
2095 track->non_realtime_input_change();
2097 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2098 if (Config->get_remote_model() == UserOrdered) {
2099 track->set_remote_control_id (next_control_id());
2102 new_routes.push_back (track);
2103 ret.push_back (track);
2106 catch (failed_constructor &err) {
2107 error << _("Session: could not create new audio track.") << endmsg;
2111 catch (AudioEngine::PortRegistrationFailure& pfe) {
2113 error << pfe.what() << endmsg;
2121 if (!new_routes.empty()) {
2122 add_routes (new_routes, true, true, true);
2128 /** Caller must not hold process lock.
2129 * @param name_template string to use for the start of the name, or "" to use "Bus".
2132 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2135 uint32_t bus_id = 0;
2139 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2142 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2143 error << "cannot find name for new audio bus" << endmsg;
2148 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2154 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2155 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2158 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2160 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2161 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2162 input_channels, output_channels)
2168 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2169 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2170 input_channels, output_channels)
2177 route_group->add (bus);
2179 if (Config->get_remote_model() == UserOrdered) {
2180 bus->set_remote_control_id (next_control_id());
2183 bus->add_internal_return ();
2185 ret.push_back (bus);
2191 catch (failed_constructor &err) {
2192 error << _("Session: could not create new audio route.") << endmsg;
2196 catch (AudioEngine::PortRegistrationFailure& pfe) {
2197 error << pfe.what() << endmsg;
2207 add_routes (ret, false, true, true); // autoconnect outputs only
2215 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2218 uint32_t control_id;
2220 uint32_t number = 0;
2221 const uint32_t being_added = how_many;
2223 if (!tree.read (template_path.c_str())) {
2227 XMLNode* node = tree.root();
2229 IO::disable_connecting ();
2231 control_id = next_control_id ();
2235 XMLNode node_copy (*node);
2237 /* Remove IDs of everything so that new ones are used */
2238 node_copy.remove_property_recursively (X_("id"));
2243 if (!name_base.empty()) {
2245 /* if we're adding more than one routes, force
2246 * all the names of the new routes to be
2247 * numbered, via the final parameter.
2250 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2251 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2257 string const route_name = node_copy.property(X_("name"))->value ();
2259 /* generate a new name by adding a number to the end of the template name */
2260 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2261 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2266 /* set this name in the XML description that we are about to use */
2267 Route::set_name_in_state (node_copy, name);
2269 /* trim bitslots from listen sends so that new ones are used */
2270 XMLNodeList children = node_copy.children ();
2271 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2272 if ((*i)->name() == X_("Processor")) {
2273 XMLProperty* role = (*i)->property (X_("role"));
2274 if (role && role->value() == X_("Listen")) {
2275 (*i)->remove_property (X_("bitslot"));
2280 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2283 error << _("Session: cannot create track/bus from template description") << endmsg;
2287 if (boost::dynamic_pointer_cast<Track>(route)) {
2288 /* force input/output change signals so that the new diskstream
2289 picks up the configuration of the route. During session
2290 loading this normally happens in a different way.
2293 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2295 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2296 change.after = route->input()->n_ports();
2297 route->input()->changed (change, this);
2298 change.after = route->output()->n_ports();
2299 route->output()->changed (change, this);
2302 route->set_remote_control_id (control_id);
2305 ret.push_back (route);
2308 catch (failed_constructor &err) {
2309 error << _("Session: could not create new route from template") << endmsg;
2313 catch (AudioEngine::PortRegistrationFailure& pfe) {
2314 error << pfe.what() << endmsg;
2323 add_routes (ret, true, true, true);
2324 IO::enable_connecting ();
2331 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2334 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2335 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2338 error << _("Adding new tracks/busses failed") << endmsg;
2343 update_latency (true);
2344 update_latency (false);
2349 save_state (_current_snapshot_name);
2352 RouteAdded (new_routes); /* EMIT SIGNAL */
2356 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2358 ChanCount existing_inputs;
2359 ChanCount existing_outputs;
2360 uint32_t order = next_control_id();
2362 if (_order_hint != 0) {
2363 order = _order_hint;
2367 count_existing_track_channels (existing_inputs, existing_outputs);
2370 RCUWriter<RouteList> writer (routes);
2371 boost::shared_ptr<RouteList> r = writer.get_copy ();
2372 r->insert (r->end(), new_routes.begin(), new_routes.end());
2374 /* if there is no control out and we're not in the middle of loading,
2375 resort the graph here. if there is a control out, we will resort
2376 toward the end of this method. if we are in the middle of loading,
2377 we will resort when done.
2380 if (!_monitor_out && IO::connecting_legal) {
2381 resort_routes_using (r);
2385 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2387 boost::weak_ptr<Route> wpr (*x);
2388 boost::shared_ptr<Route> r (*x);
2390 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2391 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2392 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2393 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2394 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2395 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2397 if (r->is_master()) {
2401 if (r->is_monitor()) {
2405 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2407 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2408 track_playlist_changed (boost::weak_ptr<Track> (tr));
2409 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2411 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2413 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2414 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2419 if (input_auto_connect || output_auto_connect) {
2420 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2423 /* order keys are a GUI responsibility but we need to set up
2424 reasonable defaults because they also affect the remote control
2425 ID in most situations.
2428 if (!r->has_order_key ()) {
2429 if (r->is_auditioner()) {
2430 /* use an arbitrarily high value */
2431 r->set_order_key (UINT_MAX);
2433 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2434 r->set_order_key (order);
2442 if (_monitor_out && IO::connecting_legal) {
2443 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2445 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2446 if ((*x)->is_monitor()) {
2448 } else if ((*x)->is_master()) {
2451 (*x)->enable_monitor_send ();
2458 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2460 boost::shared_ptr<RouteList> r = routes.reader ();
2461 boost::shared_ptr<Send> s;
2463 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2464 if ((s = (*i)->internal_send_for (dest)) != 0) {
2465 s->amp()->gain_control()->set_value (0.0);
2471 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2473 boost::shared_ptr<RouteList> r = routes.reader ();
2474 boost::shared_ptr<Send> s;
2476 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2477 if ((s = (*i)->internal_send_for (dest)) != 0) {
2478 s->amp()->gain_control()->set_value (1.0);
2484 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2486 boost::shared_ptr<RouteList> r = routes.reader ();
2487 boost::shared_ptr<Send> s;
2489 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2490 if ((s = (*i)->internal_send_for (dest)) != 0) {
2491 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2496 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2498 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2500 boost::shared_ptr<RouteList> r = routes.reader ();
2501 boost::shared_ptr<RouteList> t (new RouteList);
2503 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2504 /* no MIDI sends because there are no MIDI busses yet */
2505 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2510 add_internal_sends (dest, p, t);
2514 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2516 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2517 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2522 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2524 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2528 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2530 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2534 if (!dest->internal_return()) {
2535 dest->add_internal_return ();
2538 sender->add_aux_send (dest, before);
2544 Session::remove_route (boost::shared_ptr<Route> route)
2546 if (route == _master_out) {
2550 route->set_solo (false, this);
2553 RCUWriter<RouteList> writer (routes);
2554 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2558 /* deleting the master out seems like a dumb
2559 idea, but its more of a UI policy issue
2563 if (route == _master_out) {
2564 _master_out = boost::shared_ptr<Route> ();
2567 if (route == _monitor_out) {
2568 _monitor_out.reset ();
2571 /* writer goes out of scope, forces route list update */
2574 update_route_solo_state ();
2576 // We need to disconnect the route's inputs and outputs
2578 route->input()->disconnect (0);
2579 route->output()->disconnect (0);
2581 /* if the route had internal sends sending to it, remove them */
2582 if (route->internal_return()) {
2584 boost::shared_ptr<RouteList> r = routes.reader ();
2585 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2586 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2588 (*i)->remove_processor (s);
2593 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2594 if (mt && mt->step_editing()) {
2595 if (_step_editors > 0) {
2600 update_latency_compensation ();
2603 /* Re-sort routes to remove the graph's current references to the one that is
2604 * going away, then flush old references out of the graph.
2608 if (_process_graph) {
2609 _process_graph->clear_other_chain ();
2612 /* get rid of it from the dead wood collection in the route list manager */
2614 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2618 /* try to cause everyone to drop their references */
2620 route->drop_references ();
2622 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2624 /* save the new state of the world */
2626 if (save_state (_current_snapshot_name)) {
2627 save_history (_current_snapshot_name);
2632 Session::route_mute_changed (void* /*src*/)
2638 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2640 boost::shared_ptr<Route> route = wpr.lock();
2642 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2646 if (route->listening_via_monitor ()) {
2648 if (Config->get_exclusive_solo()) {
2649 /* new listen: disable all other listen */
2650 boost::shared_ptr<RouteList> r = routes.reader ();
2651 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2652 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2655 (*i)->set_listen (false, this);
2661 } else if (_listen_cnt > 0) {
2666 update_route_solo_state ();
2669 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2671 boost::shared_ptr<Route> route = wpr.lock ();
2674 /* should not happen */
2675 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2679 bool send_changed = false;
2681 if (route->solo_isolated()) {
2682 if (_solo_isolated_cnt == 0) {
2683 send_changed = true;
2685 _solo_isolated_cnt++;
2686 } else if (_solo_isolated_cnt > 0) {
2687 _solo_isolated_cnt--;
2688 if (_solo_isolated_cnt == 0) {
2689 send_changed = true;
2694 IsolatedChanged (); /* EMIT SIGNAL */
2699 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2701 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2703 if (!self_solo_change) {
2704 // session doesn't care about changes to soloed-by-others
2708 if (solo_update_disabled) {
2710 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2714 boost::shared_ptr<Route> route = wpr.lock ();
2717 boost::shared_ptr<RouteList> r = routes.reader ();
2720 if (route->self_soloed()) {
2726 RouteGroup* rg = route->route_group ();
2727 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2729 if (delta == 1 && Config->get_exclusive_solo()) {
2731 /* new solo: disable all other solos, but not the group if its solo-enabled */
2733 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2734 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2735 (leave_group_alone && ((*i)->route_group() == rg))) {
2738 (*i)->set_solo (false, this);
2742 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2744 solo_update_disabled = true;
2746 RouteList uninvolved;
2748 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2750 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2751 bool via_sends_only;
2752 bool in_signal_flow;
2754 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2755 (leave_group_alone && ((*i)->route_group() == rg))) {
2759 in_signal_flow = false;
2761 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2763 if ((*i)->feeds (route, &via_sends_only)) {
2764 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2765 if (!via_sends_only) {
2766 if (!route->soloed_by_others_upstream()) {
2767 (*i)->mod_solo_by_others_downstream (delta);
2770 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2772 in_signal_flow = true;
2774 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2777 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2779 if (route->feeds (*i, &via_sends_only)) {
2780 /* propagate solo upstream only if routing other than
2781 sends is involved, but do consider the other route
2782 (*i) to be part of the signal flow even if only
2785 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2789 route->soloed_by_others_downstream(),
2790 route->soloed_by_others_upstream()));
2791 if (!via_sends_only) {
2792 if (!route->soloed_by_others_downstream()) {
2793 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2794 (*i)->mod_solo_by_others_upstream (delta);
2796 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2799 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2801 in_signal_flow = true;
2803 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2806 if (!in_signal_flow) {
2807 uninvolved.push_back (*i);
2811 solo_update_disabled = false;
2812 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2814 update_route_solo_state (r);
2816 /* now notify that the mute state of the routes not involved in the signal
2817 pathway of the just-solo-changed route may have altered.
2820 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2821 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2822 (*i)->mute_changed (this);
2825 SoloChanged (); /* EMIT SIGNAL */
2830 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2832 /* now figure out if anything that matters is soloed (or is "listening")*/
2834 bool something_soloed = false;
2835 uint32_t listeners = 0;
2836 uint32_t isolated = 0;
2839 r = routes.reader();
2842 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2843 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2844 something_soloed = true;
2847 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2848 if (Config->get_solo_control_is_listen_control()) {
2851 (*i)->set_listen (false, this);
2855 if ((*i)->solo_isolated()) {
2860 if (something_soloed != _non_soloed_outs_muted) {
2861 _non_soloed_outs_muted = something_soloed;
2862 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2865 _listen_cnt = listeners;
2867 if (isolated != _solo_isolated_cnt) {
2868 _solo_isolated_cnt = isolated;
2869 IsolatedChanged (); /* EMIT SIGNAL */
2872 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2873 something_soloed, listeners, isolated));
2876 boost::shared_ptr<RouteList>
2877 Session::get_routes_with_internal_returns() const
2879 boost::shared_ptr<RouteList> r = routes.reader ();
2880 boost::shared_ptr<RouteList> rl (new RouteList);
2882 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2883 if ((*i)->internal_return ()) {
2891 Session::io_name_is_legal (const std::string& name)
2893 boost::shared_ptr<RouteList> r = routes.reader ();
2895 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2896 if ((*i)->name() == name) {
2900 if ((*i)->has_io_processor_named (name)) {
2909 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2912 vector<string> connections;
2914 /* if we are passed only a single route and we're not told to turn
2915 * others off, then just do the simple thing.
2918 if (flip_others == false && rl->size() == 1) {
2919 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2921 mt->set_input_active (onoff);
2926 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2928 PortSet& ps ((*rt)->input()->ports());
2930 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2931 p->get_connections (connections);
2934 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2935 routes_using_input_from (*s, rl2);
2938 /* scan all relevant routes to see if others are on or off */
2940 bool others_are_already_on = false;
2942 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2944 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2950 if ((*r) != (*rt)) {
2951 if (mt->input_active()) {
2952 others_are_already_on = true;
2955 /* this one needs changing */
2956 mt->set_input_active (onoff);
2962 /* globally reverse other routes */
2964 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2965 if ((*r) != (*rt)) {
2966 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2968 mt->set_input_active (!others_are_already_on);
2977 Session::routes_using_input_from (const string& str, RouteList& rl)
2979 boost::shared_ptr<RouteList> r = routes.reader();
2981 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2982 if ((*i)->input()->connected_to (str)) {
2988 boost::shared_ptr<Route>
2989 Session::route_by_name (string name)
2991 boost::shared_ptr<RouteList> r = routes.reader ();
2993 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2994 if ((*i)->name() == name) {
2999 return boost::shared_ptr<Route> ((Route*) 0);
3002 boost::shared_ptr<Route>
3003 Session::route_by_id (PBD::ID id)
3005 boost::shared_ptr<RouteList> r = routes.reader ();
3007 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3008 if ((*i)->id() == id) {
3013 return boost::shared_ptr<Route> ((Route*) 0);
3016 boost::shared_ptr<Track>
3017 Session::track_by_diskstream_id (PBD::ID id)
3019 boost::shared_ptr<RouteList> r = routes.reader ();
3021 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3022 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3023 if (t && t->using_diskstream_id (id)) {
3028 return boost::shared_ptr<Track> ();
3031 boost::shared_ptr<Route>
3032 Session::route_by_remote_id (uint32_t id)
3034 boost::shared_ptr<RouteList> r = routes.reader ();
3036 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3037 if ((*i)->remote_control_id() == id) {
3042 return boost::shared_ptr<Route> ((Route*) 0);
3046 Session::playlist_region_added (boost::weak_ptr<Region> w)
3048 boost::shared_ptr<Region> r = w.lock ();
3053 /* These are the operations that are currently in progress... */
3054 list<GQuark> curr = _current_trans_quarks;
3057 /* ...and these are the operations during which we want to update
3058 the session range location markers.
3061 ops.push_back (Operations::capture);
3062 ops.push_back (Operations::paste);
3063 ops.push_back (Operations::duplicate_region);
3064 ops.push_back (Operations::insert_file);
3065 ops.push_back (Operations::insert_region);
3066 ops.push_back (Operations::drag_region_brush);
3067 ops.push_back (Operations::region_drag);
3068 ops.push_back (Operations::selection_grab);
3069 ops.push_back (Operations::region_fill);
3070 ops.push_back (Operations::fill_selection);
3071 ops.push_back (Operations::create_region);
3072 ops.push_back (Operations::region_copy);
3073 ops.push_back (Operations::fixed_time_region_copy);
3076 /* See if any of the current operations match the ones that we want */
3078 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3080 /* If so, update the session range markers */
3082 maybe_update_session_range (r->position (), r->last_frame ());
3086 /** Update the session range markers if a is before the current start or
3087 * b is after the current end.
3090 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3092 if (_state_of_the_state & Loading) {
3096 if (_session_range_location == 0) {
3098 add_session_range_location (a, b);
3102 if (a < _session_range_location->start()) {
3103 _session_range_location->set_start (a);
3106 if (b > _session_range_location->end()) {
3107 _session_range_location->set_end (b);
3113 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3115 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3116 maybe_update_session_range (i->to, i->to + i->length);
3121 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3123 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3124 maybe_update_session_range (i->from, i->to);
3128 /* Region management */
3130 boost::shared_ptr<Region>
3131 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3133 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3134 RegionFactory::RegionMap::const_iterator i;
3135 boost::shared_ptr<Region> region;
3137 Glib::Threads::Mutex::Lock lm (region_lock);
3139 for (i = regions.begin(); i != regions.end(); ++i) {
3143 if (region->whole_file()) {
3145 if (child->source_equivalent (region)) {
3151 return boost::shared_ptr<Region> ();
3155 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3157 set<boost::shared_ptr<Region> > relevant_regions;
3159 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3160 RegionFactory::get_regions_using_source (*s, relevant_regions);
3163 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3164 set<boost::shared_ptr<Region> >::iterator tmp;
3169 playlists->destroy_region (*r);
3170 RegionFactory::map_remove (*r);
3172 (*r)->drop_sources ();
3173 (*r)->drop_references ();
3175 relevant_regions.erase (r);
3180 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3183 Glib::Threads::Mutex::Lock ls (source_lock);
3184 /* remove from the main source list */
3185 sources.erase ((*s)->id());
3188 (*s)->mark_for_remove ();
3189 (*s)->drop_references ();
3198 Session::remove_last_capture ()
3200 list<boost::shared_ptr<Source> > srcs;
3202 boost::shared_ptr<RouteList> rl = routes.reader ();
3203 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3204 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3209 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3212 srcs.insert (srcs.end(), l.begin(), l.end());
3217 destroy_sources (srcs);
3219 save_state (_current_snapshot_name);
3224 /* Source Management */
3227 Session::add_source (boost::shared_ptr<Source> source)
3229 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3230 pair<SourceMap::iterator,bool> result;
3232 entry.first = source->id();
3233 entry.second = source;
3236 Glib::Threads::Mutex::Lock lm (source_lock);
3237 result = sources.insert (entry);
3240 if (result.second) {
3242 /* yay, new source */
3244 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3247 if (!fs->within_session()) {
3248 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3254 boost::shared_ptr<AudioFileSource> afs;
3256 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3257 if (Config->get_auto_analyse_audio()) {
3258 Analyser::queue_source_for_analysis (source, false);
3262 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3267 Session::remove_source (boost::weak_ptr<Source> src)
3269 if (_state_of_the_state & Deletion) {
3273 SourceMap::iterator i;
3274 boost::shared_ptr<Source> source = src.lock();
3281 Glib::Threads::Mutex::Lock lm (source_lock);
3283 if ((i = sources.find (source->id())) != sources.end()) {
3288 if (!(_state_of_the_state & InCleanup)) {
3290 /* save state so we don't end up with a session file
3291 referring to non-existent sources.
3294 save_state (_current_snapshot_name);
3298 boost::shared_ptr<Source>
3299 Session::source_by_id (const PBD::ID& id)
3301 Glib::Threads::Mutex::Lock lm (source_lock);
3302 SourceMap::iterator i;
3303 boost::shared_ptr<Source> source;
3305 if ((i = sources.find (id)) != sources.end()) {
3312 boost::shared_ptr<AudioFileSource>
3313 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3315 /* Restricted to audio files because only audio sources have channel
3319 Glib::Threads::Mutex::Lock lm (source_lock);
3321 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3322 boost::shared_ptr<AudioFileSource> afs
3323 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3325 if (afs && afs->path() == path && chn == afs->channel()) {
3330 return boost::shared_ptr<AudioFileSource>();
3333 boost::shared_ptr<MidiSource>
3334 Session::midi_source_by_path (const std::string& path) const
3336 /* Restricted to MIDI files because audio sources require a channel
3337 for unique identification, in addition to a path.
3340 Glib::Threads::Mutex::Lock lm (source_lock);
3342 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3343 boost::shared_ptr<MidiSource> ms
3344 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3345 boost::shared_ptr<FileSource> fs
3346 = boost::dynamic_pointer_cast<FileSource>(s->second);
3348 if (ms && fs && fs->path() == path) {
3353 return boost::shared_ptr<MidiSource>();
3357 Session::count_sources_by_origin (const string& path)
3360 Glib::Threads::Mutex::Lock lm (source_lock);
3362 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3363 boost::shared_ptr<FileSource> fs
3364 = boost::dynamic_pointer_cast<FileSource>(i->second);
3366 if (fs && fs->origin() == path) {
3374 /** Return the full path (in some session directory) for a new within-session source.
3375 * \a name must be a session-unique name that does not contain slashes
3376 * (e.g. as returned by new_*_source_name)
3379 Session::new_source_path_from_name (DataType type, const string& name)
3381 assert(name.find("/") == string::npos);
3383 SessionDirectory sdir(get_best_session_directory_for_new_source());
3386 if (type == DataType::AUDIO) {
3387 p = sdir.sound_path();
3388 } else if (type == DataType::MIDI) {
3389 p = sdir.midi_path();
3391 error << "Unknown source type, unable to create file path" << endmsg;
3395 return Glib::build_filename (p, name);
3399 Session::peak_path (string base) const
3401 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3404 /** Return a unique name based on \a base for a new internal audio source */
3406 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3409 char buf[PATH_MAX+1];
3410 const uint32_t limit = 10000;
3412 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3415 legalized = legalize_for_path (base);
3417 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3418 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3420 vector<space_and_path>::iterator i;
3421 uint32_t existing = 0;
3423 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3428 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3429 cnt, legalized.c_str(), ext.c_str());
3430 } else if (nchan == 2) {
3432 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3433 cnt, legalized.c_str(), ext.c_str());
3435 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3436 cnt, legalized.c_str(), ext.c_str());
3438 } else if (nchan < 26) {
3439 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3440 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3442 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3443 cnt, legalized.c_str(), ext.c_str());
3449 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3450 } else if (nchan == 2) {
3452 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3454 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3456 } else if (nchan < 26) {
3457 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3459 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3463 SessionDirectory sdir((*i).path);
3465 string spath = sdir.sound_path();
3467 /* note that we search *without* the extension so that
3468 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3469 in the event that this new name is required for
3470 a file format change.
3473 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3478 /* it is possible that we have the path already
3479 * assigned to a source that has not yet been written
3480 * (ie. the write source for a diskstream). we have to
3481 * check this in order to make sure that our candidate
3482 * path isn't used again, because that can lead to
3483 * two Sources point to the same file with different
3484 * notions of their removability.
3487 string possible_path = Glib::build_filename (spath, buf);
3489 if (audio_source_by_path_and_channel (possible_path, chan)) {
3495 if (existing == 0) {
3500 error << string_compose(
3501 _("There are already %1 recordings for %2, which I consider too many."),
3502 limit, base) << endmsg;
3504 throw failed_constructor();
3508 return Glib::path_get_basename (buf);
3511 /** Create a new within-session audio source */
3512 boost::shared_ptr<AudioFileSource>
3513 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3515 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3516 const string path = new_source_path_from_name(DataType::AUDIO, name);
3518 return boost::dynamic_pointer_cast<AudioFileSource> (
3519 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3522 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3524 Session::new_midi_source_name (const string& owner_name)
3527 char buf[PATH_MAX+1];
3528 const uint32_t limit = 10000;
3530 string possible_name;
3533 legalized = legalize_for_path (owner_name);
3535 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3537 for (cnt = 1; cnt <= limit; ++cnt) {
3539 vector<space_and_path>::iterator i;
3540 uint32_t existing = 0;
3542 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3544 SessionDirectory sdir((*i).path);
3546 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3547 possible_name = buf;
3549 std::string possible_path = Glib::build_filename (sdir.midi_path(), possible_name);
3551 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3555 if (midi_source_by_path (possible_path)) {
3560 if (existing == 0) {
3565 error << string_compose(
3566 _("There are already %1 recordings for %2, which I consider too many."),
3567 limit, owner_name) << endmsg;
3569 throw failed_constructor();
3573 return possible_name;
3577 /** Create a new within-session MIDI source */
3578 boost::shared_ptr<MidiSource>
3579 Session::create_midi_source_for_session (string const & basic_name)
3584 name = new_midi_source_name (basic_name);
3587 const string path = new_source_path_from_name (DataType::MIDI, name);
3589 return boost::dynamic_pointer_cast<SMFSource> (
3590 SourceFactory::createWritable (
3591 DataType::MIDI, *this, path, false, frame_rate()));
3594 /** Create a new within-session MIDI source */
3595 boost::shared_ptr<MidiSource>
3596 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3598 /* the caller passes in the track the source will be used in,
3599 so that we can keep the numbering sane.
3601 Rationale: a track with the name "Foo" that has had N
3602 captures carried out so far will ALREADY have a write source
3603 named "Foo-N+1.mid" waiting to be used for the next capture.
3605 If we call new_midi_source_name() we will get "Foo-N+2". But
3606 there is no region corresponding to "Foo-N+1", so when
3607 "Foo-N+2" appears in the track, the gap presents the user
3608 with odd behaviour - why did it skip past Foo-N+1?
3610 We could explain this to the user in some odd way, but
3611 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3614 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3617 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3619 std::string name = track->steal_write_source_name ();
3622 return boost::shared_ptr<MidiSource>();
3625 const string path = new_source_path_from_name (DataType::MIDI, name);
3627 return boost::dynamic_pointer_cast<SMFSource> (
3628 SourceFactory::createWritable (
3629 DataType::MIDI, *this, path, false, frame_rate()));
3634 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3636 if (playlist->hidden()) {
3640 playlists->add (playlist);
3643 playlist->release();
3650 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3652 if (_state_of_the_state & Deletion) {
3656 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3662 playlists->remove (playlist);
3668 Session::set_audition (boost::shared_ptr<Region> r)
3670 pending_audition_region = r;
3671 add_post_transport_work (PostTransportAudition);
3672 _butler->schedule_transport_work ();
3676 Session::audition_playlist ()
3678 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3679 ev->region.reset ();
3684 Session::non_realtime_set_audition ()
3686 assert (pending_audition_region);
3687 auditioner->audition_region (pending_audition_region);
3688 pending_audition_region.reset ();
3689 AuditionActive (true); /* EMIT SIGNAL */
3693 Session::audition_region (boost::shared_ptr<Region> r)
3695 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3701 Session::cancel_audition ()
3703 if (auditioner->auditioning()) {
3704 auditioner->cancel_audition ();
3705 AuditionActive (false); /* EMIT SIGNAL */
3710 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3712 if (a->is_monitor()) {
3715 if (b->is_monitor()) {
3718 return a->order_key () < b->order_key ();
3722 Session::is_auditioning () const
3724 /* can be called before we have an auditioner object */
3726 return auditioner->auditioning();
3733 Session::graph_reordered ()
3735 /* don't do this stuff if we are setting up connections
3736 from a set_state() call or creating new tracks. Ditto for deletion.
3739 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3743 /* every track/bus asked for this to be handled but it was deferred because
3744 we were connecting. do it now.
3747 request_input_change_handling ();
3751 /* force all diskstreams to update their capture offset values to
3752 reflect any changes in latencies within the graph.
3755 boost::shared_ptr<RouteList> rl = routes.reader ();
3756 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3757 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3759 tr->set_capture_offset ();
3764 /** @return Number of frames that there is disk space available to write,
3767 boost::optional<framecnt_t>
3768 Session::available_capture_duration ()
3770 Glib::Threads::Mutex::Lock lm (space_lock);
3772 if (_total_free_4k_blocks_uncertain) {
3773 return boost::optional<framecnt_t> ();
3776 float sample_bytes_on_disk = 4.0; // keep gcc happy
3778 switch (config.get_native_file_data_format()) {
3780 sample_bytes_on_disk = 4.0;
3784 sample_bytes_on_disk = 3.0;
3788 sample_bytes_on_disk = 2.0;
3792 /* impossible, but keep some gcc versions happy */
3793 fatal << string_compose (_("programming error: %1"),
3794 X_("illegal native file data format"))
3799 double scale = 4096.0 / sample_bytes_on_disk;
3801 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3802 return max_framecnt;
3805 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3809 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3812 RCUWriter<BundleList> writer (_bundles);
3813 boost::shared_ptr<BundleList> b = writer.get_copy ();
3814 b->push_back (bundle);
3817 BundleAdded (bundle); /* EMIT SIGNAL */
3823 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3825 bool removed = false;
3828 RCUWriter<BundleList> writer (_bundles);
3829 boost::shared_ptr<BundleList> b = writer.get_copy ();
3830 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3832 if (i != b->end()) {
3839 BundleRemoved (bundle); /* EMIT SIGNAL */
3845 boost::shared_ptr<Bundle>
3846 Session::bundle_by_name (string name) const
3848 boost::shared_ptr<BundleList> b = _bundles.reader ();
3850 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3851 if ((*i)->name() == name) {
3856 return boost::shared_ptr<Bundle> ();
3860 Session::tempo_map_changed (const PropertyChange&)
3864 playlists->update_after_tempo_map_change ();
3866 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3872 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3874 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3875 (*i)->recompute_frames_from_bbt ();
3879 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3880 * the given count with the current block size.
3883 Session::ensure_buffers (ChanCount howmany)
3885 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
3889 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3891 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3892 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3897 Session::next_insert_id ()
3899 /* this doesn't really loop forever. just think about it */
3902 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3903 if (!insert_bitset[n]) {
3904 insert_bitset[n] = true;
3910 /* none available, so resize and try again */
3912 insert_bitset.resize (insert_bitset.size() + 16, false);
3917 Session::next_send_id ()
3919 /* this doesn't really loop forever. just think about it */
3922 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3923 if (!send_bitset[n]) {
3924 send_bitset[n] = true;
3930 /* none available, so resize and try again */
3932 send_bitset.resize (send_bitset.size() + 16, false);
3937 Session::next_aux_send_id ()
3939 /* this doesn't really loop forever. just think about it */
3942 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3943 if (!aux_send_bitset[n]) {
3944 aux_send_bitset[n] = true;
3950 /* none available, so resize and try again */
3952 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
3957 Session::next_return_id ()
3959 /* this doesn't really loop forever. just think about it */
3962 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3963 if (!return_bitset[n]) {
3964 return_bitset[n] = true;
3970 /* none available, so resize and try again */
3972 return_bitset.resize (return_bitset.size() + 16, false);
3977 Session::mark_send_id (uint32_t id)
3979 if (id >= send_bitset.size()) {
3980 send_bitset.resize (id+16, false);
3982 if (send_bitset[id]) {
3983 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3985 send_bitset[id] = true;
3989 Session::mark_aux_send_id (uint32_t id)
3991 if (id >= aux_send_bitset.size()) {
3992 aux_send_bitset.resize (id+16, false);
3994 if (aux_send_bitset[id]) {
3995 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
3997 aux_send_bitset[id] = true;
4001 Session::mark_return_id (uint32_t id)
4003 if (id >= return_bitset.size()) {
4004 return_bitset.resize (id+16, false);
4006 if (return_bitset[id]) {
4007 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4009 return_bitset[id] = true;
4013 Session::mark_insert_id (uint32_t id)
4015 if (id >= insert_bitset.size()) {
4016 insert_bitset.resize (id+16, false);
4018 if (insert_bitset[id]) {
4019 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4021 insert_bitset[id] = true;
4025 Session::unmark_send_id (uint32_t id)
4027 if (id < send_bitset.size()) {
4028 send_bitset[id] = false;
4033 Session::unmark_aux_send_id (uint32_t id)
4035 if (id < aux_send_bitset.size()) {
4036 aux_send_bitset[id] = false;
4041 Session::unmark_return_id (uint32_t id)
4043 if (id < return_bitset.size()) {
4044 return_bitset[id] = false;
4049 Session::unmark_insert_id (uint32_t id)
4051 if (id < insert_bitset.size()) {
4052 insert_bitset[id] = false;
4057 Session::reset_native_file_format ()
4059 boost::shared_ptr<RouteList> rl = routes.reader ();
4060 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4061 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4063 /* don't save state as we do this, there's no point
4066 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4067 tr->reset_write_sources (false);
4068 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4074 Session::route_name_unique (string n) const
4076 boost::shared_ptr<RouteList> r = routes.reader ();
4078 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4079 if ((*i)->name() == n) {
4088 Session::route_name_internal (string n) const
4090 if (auditioner && auditioner->name() == n) {
4094 if (_click_io && _click_io->name() == n) {
4102 Session::freeze_all (InterThreadInfo& itt)
4104 boost::shared_ptr<RouteList> r = routes.reader ();
4106 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4108 boost::shared_ptr<Track> t;
4110 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4111 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4121 boost::shared_ptr<Region>
4122 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4123 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4124 InterThreadInfo& itt,
4125 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4126 bool for_export, bool for_freeze)
4128 boost::shared_ptr<Region> result;
4129 boost::shared_ptr<Playlist> playlist;
4130 boost::shared_ptr<AudioFileSource> fsource;
4132 ChanCount diskstream_channels (track.n_channels());
4133 framepos_t position;
4134 framecnt_t this_chunk;
4136 framepos_t latency_skip;
4138 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4139 const string sound_dir = sdir.sound_path();
4140 framepos_t len = end - start;
4141 bool need_block_size_reset = false;
4143 ChanCount const max_proc = track.max_processor_streams ();
4144 string legal_playlist_name;
4145 string possible_path;
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,
4154 include_endpoint, for_export, for_freeze);
4156 if (diskstream_channels.n_audio() < 1) {
4157 error << _("Cannot write a range with no audio.") << endmsg;
4161 // block all process callback handling
4163 block_processing ();
4166 // synchronize with AudioEngine::process_callback()
4167 // make sure processing is not currently running
4168 // and processing_blocked() is honored before
4169 // acquiring thread buffers
4170 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4173 _bounce_processing_active = true;
4175 /* call tree *MUST* hold route_lock */
4177 if ((playlist = track.playlist()) == 0) {
4181 legal_playlist_name = legalize_for_path (playlist->name());
4183 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4185 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4187 for (x = 0; x < 99999; ++x) {
4188 possible_path = Glib::build_filename (sound_dir, string_compose ("%1-%2-bounce-%3%4", legal_playlist_name.c_str(), chan_n, x+1, ext.c_str()));
4189 if (!Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4195 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4200 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4201 SourceFactory::createWritable (DataType::AUDIO, *this, possible_path, false, frame_rate()));
4204 catch (failed_constructor& err) {
4205 error << string_compose (_("cannot create new audio file \"%1\" for %2"), possible_path, track.name()) << endmsg;
4209 srcs.push_back (fsource);
4212 /* tell redirects that care that we are about to use a much larger
4213 * blocksize. this will flush all plugins too, so that they are ready
4214 * to be used for this process.
4217 need_block_size_reset = true;
4218 track.set_block_size (bounce_chunk_size);
4219 _engine.main_thread()->get_buffers ();
4223 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4225 /* create a set of reasonably-sized buffers */
4226 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4227 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4229 buffers.set_count (max_proc);
4231 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4232 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4234 afs->prepare_for_peakfile_writes ();
4237 while (to_do && !itt.cancel) {
4239 this_chunk = min (to_do, bounce_chunk_size);
4241 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
4245 start += this_chunk;
4246 to_do -= this_chunk;
4247 itt.progress = (float) (1.0 - ((double) to_do / len));
4249 if (latency_skip >= bounce_chunk_size) {
4250 latency_skip -= bounce_chunk_size;
4254 const framecnt_t current_chunk = this_chunk - latency_skip;
4257 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4258 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4261 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4269 /* post-roll, pick up delayed processor output */
4270 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4272 while (latency_skip && !itt.cancel) {
4273 this_chunk = min (latency_skip, bounce_chunk_size);
4274 latency_skip -= this_chunk;
4276 buffers.silence (this_chunk, 0);
4277 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
4280 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4281 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4284 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4296 xnow = localtime (&now);
4298 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4299 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4302 afs->update_header (position, *xnow, now);
4303 afs->flush_header ();
4307 /* construct a region to represent the bounced material */
4311 plist.add (Properties::start, 0);
4312 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4313 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4315 result = RegionFactory::create (srcs, plist);
4321 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4322 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4325 afs->mark_for_remove ();
4328 (*src)->drop_references ();
4332 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4333 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4336 afs->done_with_peakfile_writes ();
4340 _bounce_processing_active = false;
4342 if (need_block_size_reset) {
4343 _engine.main_thread()->drop_buffers ();
4344 track.set_block_size (get_block_size());
4347 unblock_processing ();
4353 Session::gain_automation_buffer() const
4355 return ProcessThread::gain_automation_buffer ();
4359 Session::send_gain_automation_buffer() const
4361 return ProcessThread::send_gain_automation_buffer ();
4365 Session::pan_automation_buffer() const
4367 return ProcessThread::pan_automation_buffer ();
4371 Session::get_silent_buffers (ChanCount count)
4373 return ProcessThread::get_silent_buffers (count);
4377 Session::get_scratch_buffers (ChanCount count, bool silence)
4379 return ProcessThread::get_scratch_buffers (count, silence);
4383 Session::get_route_buffers (ChanCount count, bool silence)
4385 return ProcessThread::get_route_buffers (count, silence);
4390 Session::get_mix_buffers (ChanCount count)
4392 return ProcessThread::get_mix_buffers (count);
4396 Session::ntracks () const
4399 boost::shared_ptr<RouteList> r = routes.reader ();
4401 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4402 if (boost::dynamic_pointer_cast<Track> (*i)) {
4411 Session::nbusses () const
4414 boost::shared_ptr<RouteList> r = routes.reader ();
4416 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4417 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4426 Session::add_automation_list(AutomationList *al)
4428 automation_lists[al->id()] = al;
4431 /** @return true if there is at least one record-enabled track, otherwise false */
4433 Session::have_rec_enabled_track () const
4435 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4438 /** Update the state of our rec-enabled tracks flag */
4440 Session::update_have_rec_enabled_track ()
4442 boost::shared_ptr<RouteList> rl = routes.reader ();
4443 RouteList::iterator i = rl->begin();
4444 while (i != rl->end ()) {
4446 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4447 if (tr && tr->record_enabled ()) {
4454 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4456 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4458 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4459 RecordStateChanged (); /* EMIT SIGNAL */
4464 Session::listen_position_changed ()
4466 boost::shared_ptr<RouteList> r = routes.reader ();
4468 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4469 (*i)->listen_position_changed ();
4474 Session::solo_control_mode_changed ()
4476 /* cancel all solo or all listen when solo control mode changes */
4479 set_solo (get_routes(), false);
4480 } else if (listening()) {
4481 set_listen (get_routes(), false);
4485 /** Called when a property of one of our route groups changes */
4487 Session::route_group_property_changed (RouteGroup* rg)
4489 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4492 /** Called when a route is added to one of our route groups */
4494 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4496 RouteAddedToRouteGroup (rg, r);
4499 /** Called when a route is removed from one of our route groups */
4501 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4503 RouteRemovedFromRouteGroup (rg, r);
4506 boost::shared_ptr<RouteList>
4507 Session::get_routes_with_regions_at (framepos_t const p) const
4509 boost::shared_ptr<RouteList> r = routes.reader ();
4510 boost::shared_ptr<RouteList> rl (new RouteList);
4512 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4513 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4518 boost::shared_ptr<Playlist> pl = tr->playlist ();
4523 if (pl->has_region_at (p)) {
4532 Session::goto_end ()
4534 if (_session_range_location) {
4535 request_locate (_session_range_location->end(), false);
4537 request_locate (0, false);
4542 Session::goto_start ()
4544 if (_session_range_location) {
4545 request_locate (_session_range_location->start(), false);
4547 request_locate (0, false);
4552 Session::current_start_frame () const
4554 return _session_range_location ? _session_range_location->start() : 0;
4558 Session::current_end_frame () const
4560 return _session_range_location ? _session_range_location->end() : 0;
4564 Session::add_session_range_location (framepos_t start, framepos_t end)
4566 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4567 _locations->add (_session_range_location);
4571 Session::step_edit_status_change (bool yn)
4577 send = (_step_editors == 0);
4582 send = (_step_editors == 1);
4585 if (_step_editors > 0) {
4591 StepEditStatusChange (val);
4597 Session::start_time_changed (framepos_t old)
4599 /* Update the auto loop range to match the session range
4600 (unless the auto loop range has been changed by the user)
4603 Location* s = _locations->session_range_location ();
4608 Location* l = _locations->auto_loop_location ();
4610 if (l && l->start() == old) {
4611 l->set_start (s->start(), true);
4616 Session::end_time_changed (framepos_t old)
4618 /* Update the auto loop range to match the session range
4619 (unless the auto loop range has been changed by the user)
4622 Location* s = _locations->session_range_location ();
4627 Location* l = _locations->auto_loop_location ();
4629 if (l && l->end() == old) {
4630 l->set_end (s->end(), true);
4634 std::vector<std::string>
4635 Session::source_search_path (DataType type) const
4639 if (session_dirs.size() == 1) {
4641 case DataType::AUDIO:
4642 sp.push_back (_session_dir->sound_path());
4644 case DataType::MIDI:
4645 sp.push_back (_session_dir->midi_path());
4649 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4650 SessionDirectory sdir (i->path);
4652 case DataType::AUDIO:
4653 sp.push_back (sdir.sound_path());
4655 case DataType::MIDI:
4656 sp.push_back (sdir.midi_path());
4662 if (type == DataType::AUDIO) {
4663 const string sound_path_2X = _session_dir->sound_path_2X();
4664 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4665 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
4666 sp.push_back (sound_path_2X);
4671 // now check the explicit (possibly user-specified) search path
4674 case DataType::AUDIO:
4675 sp += Searchpath(config.get_audio_search_path ());
4677 case DataType::MIDI:
4678 sp += Searchpath(config.get_midi_search_path ());
4686 Session::ensure_search_path_includes (const string& path, DataType type)
4695 case DataType::AUDIO:
4696 sp += Searchpath(config.get_audio_search_path ());
4698 case DataType::MIDI:
4699 sp += Searchpath (config.get_midi_search_path ());
4703 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
4704 /* No need to add this new directory if it has the same inode as
4705 an existing one; checking inode rather than name prevents duplicated
4706 directories when we are using symlinks.
4708 On Windows, I think we could just do if (*i == path) here.
4710 if (PBD::equivalent_paths (*i, path)) {
4718 case DataType::AUDIO:
4719 config.set_audio_search_path (sp.to_string());
4721 case DataType::MIDI:
4722 config.set_midi_search_path (sp.to_string());
4727 boost::shared_ptr<Speakers>
4728 Session::get_speakers()
4734 Session::unknown_processors () const
4738 boost::shared_ptr<RouteList> r = routes.reader ();
4739 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4740 list<string> t = (*i)->unknown_processors ();
4741 copy (t.begin(), t.end(), back_inserter (p));
4751 Session::update_latency (bool playback)
4753 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4755 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4759 boost::shared_ptr<RouteList> r = routes.reader ();
4760 framecnt_t max_latency = 0;
4763 /* reverse the list so that we work backwards from the last route to run to the first */
4764 RouteList* rl = routes.reader().get();
4765 r.reset (new RouteList (*rl));
4766 reverse (r->begin(), r->end());
4769 /* compute actual latency values for the given direction and store them all in per-port
4770 structures. this will also publish the same values (to JACK) so that computation of latency
4771 for routes can consistently use public latency values.
4774 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4775 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4778 /* because we latency compensate playback, our published playback latencies should
4779 be the same for all output ports - all material played back by ardour has
4780 the same latency, whether its caused by plugins or by latency compensation. since
4781 these may differ from the values computed above, reset all playback port latencies
4785 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4787 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4788 (*i)->set_public_port_latencies (max_latency, playback);
4793 post_playback_latency ();
4797 post_capture_latency ();
4800 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4804 Session::post_playback_latency ()
4806 set_worst_playback_latency ();
4808 boost::shared_ptr<RouteList> r = routes.reader ();
4810 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4811 if (!(*i)->is_auditioner() && ((*i)->active())) {
4812 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4816 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4817 (*i)->set_latency_compensation (_worst_track_latency);
4822 Session::post_capture_latency ()
4824 set_worst_capture_latency ();
4826 /* reflect any changes in capture latencies into capture offsets
4829 boost::shared_ptr<RouteList> rl = routes.reader();
4830 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4831 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4833 tr->set_capture_offset ();
4839 Session::initialize_latencies ()
4842 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4843 update_latency (false);
4844 update_latency (true);
4847 set_worst_io_latencies ();
4851 Session::set_worst_io_latencies ()
4853 set_worst_playback_latency ();
4854 set_worst_capture_latency ();
4858 Session::set_worst_playback_latency ()
4860 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4864 _worst_output_latency = 0;
4866 if (!_engine.connected()) {
4870 boost::shared_ptr<RouteList> r = routes.reader ();
4872 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4873 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4876 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4880 Session::set_worst_capture_latency ()
4882 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4886 _worst_input_latency = 0;
4888 if (!_engine.connected()) {
4892 boost::shared_ptr<RouteList> r = routes.reader ();
4894 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4895 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4898 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4902 Session::update_latency_compensation (bool force_whole_graph)
4904 bool some_track_latency_changed = false;
4906 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4910 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4912 _worst_track_latency = 0;
4914 boost::shared_ptr<RouteList> r = routes.reader ();
4916 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4917 if (!(*i)->is_auditioner() && ((*i)->active())) {
4919 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4920 some_track_latency_changed = true;
4922 _worst_track_latency = max (tl, _worst_track_latency);
4926 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4927 (some_track_latency_changed ? "yes" : "no")));
4929 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4931 if (some_track_latency_changed || force_whole_graph) {
4932 _engine.update_latencies ();
4936 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4937 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4941 tr->set_capture_offset ();
4946 Session::session_name_is_legal (const string& path)
4948 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4950 for (int i = 0; illegal_chars[i]; ++i) {
4951 if (path.find (illegal_chars[i]) != string::npos) {
4952 return illegal_chars[i];
4960 Session::next_control_id () const
4964 /* the monitor bus remote ID is in a different
4965 * "namespace" than regular routes. its existence doesn't
4966 * affect normal (low) numbered routes.
4973 return nroutes() - subtract;
4977 Session::notify_remote_id_change ()
4979 if (deletion_in_progress()) {
4983 switch (Config->get_remote_model()) {
4985 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
4993 Session::sync_order_keys ()
4995 if (deletion_in_progress()) {
4999 /* tell everyone that something has happened to the sort keys
5000 and let them sync up with the change(s)
5001 this will give objects that manage the sort order keys the
5002 opportunity to keep them in sync if they wish to.
5005 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5007 Route::SyncOrderKeys (); /* EMIT SIGNAL */
5009 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5013 Session::operation_in_progress (GQuark op) const
5015 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5018 boost::shared_ptr<Port>
5019 Session::ltc_input_port () const
5021 return _ltc_input->nth (0);
5024 boost::shared_ptr<Port>
5025 Session::ltc_output_port () const
5027 return _ltc_output->nth (0);
5031 Session::reconnect_ltc_input ()
5035 string src = Config->get_ltc_source_port();
5037 _ltc_input->disconnect (this);
5039 if (src != _("None") && !src.empty()) {
5040 _ltc_input->nth (0)->connect (src);
5046 Session::reconnect_ltc_output ()
5051 string src = Config->get_ltc_sink_port();
5053 _ltc_output->disconnect (this);
5055 if (src != _("None") && !src.empty()) {
5056 _ltc_output->nth (0)->connect (src);