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/convert.h"
40 #include "pbd/error.h"
41 #include "pbd/boost_debug.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/unwind.h"
48 #include "pbd/search_path.h"
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/scene_changer.h"
72 #include "ardour/midi_track.h"
73 #include "ardour/midi_ui.h"
74 #include "ardour/operations.h"
75 #include "ardour/playlist.h"
76 #include "ardour/plugin.h"
77 #include "ardour/plugin_insert.h"
78 #include "ardour/process_thread.h"
79 #include "ardour/rc_configuration.h"
80 #include "ardour/recent_sessions.h"
81 #include "ardour/region.h"
82 #include "ardour/region_factory.h"
83 #include "ardour/route_graph.h"
84 #include "ardour/route_group.h"
85 #include "ardour/route_sorters.h"
86 #include "ardour/send.h"
87 #include "ardour/session.h"
88 #include "ardour/session_directory.h"
89 #include "ardour/session_playlists.h"
90 #include "ardour/smf_source.h"
91 #include "ardour/source_factory.h"
92 #include "ardour/speakers.h"
93 #include "ardour/track.h"
94 #include "ardour/utils.h"
96 #include "midi++/port.h"
97 #include "midi++/mmc.h"
108 using namespace ARDOUR;
111 bool Session::_disable_all_loaded_plugins = false;
113 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
114 PBD::Signal1<void,std::string> Session::Dialog;
115 PBD::Signal0<int> Session::AskAboutPendingState;
116 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
117 PBD::Signal0<void> Session::SendFeedback;
118 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
120 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
121 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
122 PBD::Signal2<void,std::string, std::string> Session::Exported;
123 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
124 PBD::Signal0<void> Session::Quit;
125 PBD::Signal0<void> Session::FeedbackDetected;
126 PBD::Signal0<void> Session::SuccessfulGraphSort;
127 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
129 const framecnt_t Session::bounce_chunk_size = 65536;
130 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
131 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
133 /** @param snapshot_name Snapshot name, without .ardour suffix */
134 Session::Session (AudioEngine &eng,
135 const string& fullpath,
136 const string& snapshot_name,
137 BusProfile* bus_profile,
139 : playlists (new SessionPlaylists)
141 , process_function (&Session::process_with_events)
142 , _bounce_processing_active (false)
143 , waiting_for_sync_offset (false)
144 , _base_frame_rate (0)
145 , _current_frame_rate (0)
146 , _nominal_frame_rate (0)
147 , transport_sub_state (0)
148 , _record_status (Disabled)
149 , _transport_frame (0)
150 , _session_range_location (0)
153 , _transport_speed (0)
154 , _default_transport_speed (1.0)
155 , _last_transport_speed (0)
156 , _target_transport_speed (0.0)
157 , auto_play_legal (false)
158 , _last_slave_transport_frame (0)
159 , maximum_output_latency (0)
160 , _requested_return_frame (-1)
161 , current_block_size (0)
162 , _worst_output_latency (0)
163 , _worst_input_latency (0)
164 , _worst_track_latency (0)
165 , _have_captured (false)
168 , _non_soloed_outs_muted (false)
170 , _solo_isolated_cnt (0)
172 , _was_seamless (Config->get_seamless_loop ())
173 , _under_nsm_control (false)
174 , delta_accumulator_cnt (0)
175 , average_slave_delta (1800) // !!! why 1800 ???
177 , have_first_delta_accumulator (false)
178 , _slave_state (Stopped)
179 , post_export_sync (false)
180 , post_export_position (0)
182 , _export_started (false)
183 , _export_rolling (false)
184 , _pre_export_mmc_enabled (false)
185 , _name (snapshot_name)
187 , _send_qf_mtc (false)
188 , _pframes_since_last_mtc (0)
189 , session_midi_feedback (0)
191 , loop_changing (false)
193 , _session_dir (new SessionDirectory (fullpath))
194 , _current_snapshot_name (snapshot_name)
196 , state_was_pending (false)
197 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
199 , _save_queued (false)
200 , _last_roll_location (0)
201 , _last_roll_or_reversal_location (0)
202 , _last_record_location (0)
203 , pending_locate_roll (false)
204 , pending_locate_frame (0)
205 , pending_locate_flush (false)
206 , pending_abort (false)
207 , pending_auto_loop (false)
208 , _butler (new Butler (*this))
209 , _post_transport_work (0)
210 , cumulative_rf_motion (0)
212 , _locations (new Locations (*this))
214 , outbound_mtc_timecode_frame (0)
215 , next_quarter_frame_to_send (-1)
216 , _frames_per_timecode_frame (0)
217 , _frames_per_hour (0)
218 , _timecode_frames_per_hour (0)
219 , last_timecode_valid (false)
220 , last_timecode_when (0)
221 , _send_timecode_update (false)
233 , ltc_timecode_offset (0)
234 , ltc_timecode_negative_offset (false)
235 , midi_control_ui (0)
237 , _all_route_group (new RouteGroup (*this, "all"))
238 , routes (new RouteList)
239 , _adding_routes_in_progress (false)
240 , destructive_index (0)
241 , _track_number_decimals(1)
242 , solo_update_disabled (false)
243 , default_fade_steepness (0)
244 , default_fade_msecs (0)
245 , _total_free_4k_blocks (0)
246 , _total_free_4k_blocks_uncertain (false)
247 , no_questions_about_missing_files (false)
250 , _bundles (new BundleList)
251 , _bundle_xml_node (0)
255 , click_emphasis_data (0)
257 , click_emphasis_length (0)
258 , _clicks_cleared (0)
259 , _play_range (false)
261 , first_file_data_format_reset (true)
262 , first_file_header_format_reset (true)
263 , have_looped (false)
264 , _have_rec_enabled_track (false)
266 , _suspend_timecode_transmission (0)
267 , _speakers (new Speakers)
269 , ignore_route_processor_changes (false)
276 pre_engine_init (fullpath);
279 if (ensure_engine (sr)) {
281 throw failed_constructor ();
284 if (create (mix_template, bus_profile)) {
286 throw failed_constructor ();
289 /* if a mix template was provided, then ::create() will
290 * have copied it into the session and we need to load it
291 * so that we have the state ready for ::set_state()
292 * after the engine is started.
294 * Note that we do NOT try to get the sample rate from
295 * the template at this time, though doing so would
296 * be easy if we decided this was an appropriate part
300 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
301 throw failed_constructor ();
304 /* load default session properties - if any */
309 if (load_state (_current_snapshot_name)) {
310 throw failed_constructor ();
313 /* try to get sample rate from XML state so that we
314 * can influence the SR if we set up the audio
319 const XMLProperty* prop;
320 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
321 sr = atoi (prop->value());
325 if (ensure_engine (sr)) {
327 throw failed_constructor ();
331 if (post_engine_init ()) {
333 throw failed_constructor ();
336 store_recent_sessions (_name, _path);
338 bool was_dirty = dirty();
340 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
342 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
343 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
346 DirtyChanged (); /* EMIT SIGNAL */
349 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
350 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
354 /* hook us up to the engine since we are now completely constructed */
356 BootMessage (_("Connect to engine"));
358 _engine.set_session (this);
359 _engine.reset_timebase ();
361 BootMessage (_("Session loading complete"));
374 Session::ensure_engine (uint32_t desired_sample_rate)
376 if (_engine.current_backend() == 0) {
377 /* backend is unknown ... */
378 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
379 if (r.get_value_or (-1) != 0) {
382 } else if (_engine.setup_required()) {
383 /* backend is known, but setup is needed */
384 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
385 if (r.get_value_or (-1) != 0) {
388 } else if (!_engine.running()) {
389 if (_engine.start()) {
394 /* at this point the engine should be running
397 if (!_engine.running()) {
401 return immediately_post_engine ();
406 Session::immediately_post_engine ()
408 /* Do various initializations that should take place directly after we
409 * know that the engine is running, but before we either create a
410 * session or set state for an existing one.
413 if (how_many_dsp_threads () > 1) {
414 /* For now, only create the graph if we are using >1 DSP threads, as
415 it is a bit slower than the old code with 1 thread.
417 _process_graph.reset (new Graph (*this));
420 /* every time we reconnect, recompute worst case output latencies */
422 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
424 if (synced_to_engine()) {
425 _engine.transport_stop ();
428 if (config.get_jack_time_master()) {
429 _engine.transport_locate (_transport_frame);
433 BootMessage (_("Set up LTC"));
435 BootMessage (_("Set up Click"));
437 BootMessage (_("Set up standard connections"));
441 catch (failed_constructor& err) {
451 vector<void*> debug_pointers;
453 /* if we got to here, leaving pending capture state around
457 remove_pending_capture_state ();
459 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
461 /* disconnect from any and all signals that we are connected to */
465 _engine.remove_session ();
467 /* deregister all ports - there will be no process or any other
468 * callbacks from the engine any more.
471 Port::PortDrop (); /* EMIT SIGNAL */
475 /* clear history so that no references to objects are held any more */
479 /* clear state tree so that no references to objects are held any more */
483 /* reset dynamic state version back to default */
485 Stateful::loading_state_version = 0;
487 _butler->drop_references ();
491 delete midi_control_ui;
492 delete _all_route_group;
494 if (click_data != default_click) {
495 delete [] click_data;
498 if (click_emphasis_data != default_click_emphasis) {
499 delete [] click_emphasis_data;
504 /* need to remove auditioner before monitoring section
505 * otherwise it is re-connected */
508 /* drop references to routes held by the monitoring section
509 * specifically _monitor_out aux/listen references */
510 remove_monitor_section();
512 /* clear out any pending dead wood from RCU managed objects */
517 AudioDiskstream::free_working_buffers();
519 /* tell everyone who is still standing that we're about to die */
522 /* tell everyone to drop references and delete objects as we go */
524 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
525 RegionFactory::delete_all_regions ();
527 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
529 /* reset these three references to special routes before we do the usual route delete thing */
531 _master_out.reset ();
532 _monitor_out.reset ();
535 RCUWriter<RouteList> writer (routes);
536 boost::shared_ptr<RouteList> r = writer.get_copy ();
538 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
539 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
540 (*i)->drop_references ();
544 /* writer goes out of scope and updates master */
549 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
550 Glib::Threads::Mutex::Lock lm (source_lock);
551 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
552 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
553 i->second->drop_references ();
559 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
560 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
565 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
568 delete _scene_changer; _scene_changer = 0;
570 delete _mmc; _mmc = 0;
571 delete _midi_ports; _midi_ports = 0;
572 delete _locations; _locations = 0;
574 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
576 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
577 boost_debug_list_ptrs ();
582 Session::setup_ltc ()
586 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
587 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
589 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
590 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
593 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
594 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
596 reconnect_ltc_input ();
599 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
600 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
603 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
604 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
606 reconnect_ltc_output ();
609 /* fix up names of LTC ports because we don't want the normal
610 * IO style of NAME/TYPE-{in,out}N
613 _ltc_input->nth (0)->set_name (X_("LTC-in"));
614 _ltc_output->nth (0)->set_name (X_("LTC-out"));
618 Session::setup_click ()
621 _click_io.reset (new ClickIO (*this, X_("Click")));
622 _click_gain.reset (new Amp (*this));
623 _click_gain->activate ();
625 setup_click_state (state_tree->root());
627 setup_click_state (0);
632 Session::setup_click_state (const XMLNode* node)
634 const XMLNode* child = 0;
636 if (node && (child = find_named_node (*node, "Click")) != 0) {
638 /* existing state for Click */
641 if (Stateful::loading_state_version < 3000) {
642 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
644 const XMLNodeList& children (child->children());
645 XMLNodeList::const_iterator i = children.begin();
646 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
648 if (i != children.end()) {
649 c = _click_gain->set_state (**i, Stateful::loading_state_version);
655 _clicking = Config->get_clicking ();
659 error << _("could not setup Click I/O") << endmsg;
666 /* default state for Click: dual-mono to first 2 physical outputs */
669 _engine.get_physical_outputs (DataType::AUDIO, outs);
671 for (uint32_t physport = 0; physport < 2; ++physport) {
672 if (outs.size() > physport) {
673 if (_click_io->add_port (outs[physport], this)) {
674 // relax, even though its an error
679 if (_click_io->n_ports () > ChanCount::ZERO) {
680 _clicking = Config->get_clicking ();
686 Session::setup_bundles ()
688 vector<string> inputs[DataType::num_types];
689 vector<string> outputs[DataType::num_types];
690 for (uint32_t i = 0; i < DataType::num_types; ++i) {
691 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
692 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
695 /* Create a set of Bundle objects that map
696 to the physical I/O currently available. We create both
697 mono and stereo bundles, so that the common cases of mono
698 and stereo tracks get bundles to put in their mixer strip
699 in / out menus. There may be a nicer way of achieving that;
700 it doesn't really scale that well to higher channel counts
703 /* mono output bundles */
705 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
707 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
709 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
710 c->add_channel (_("mono"), DataType::AUDIO);
711 c->set_port (0, outputs[DataType::AUDIO][np]);
716 /* stereo output bundles */
718 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
719 if (np + 1 < outputs[DataType::AUDIO].size()) {
721 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
722 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
723 c->add_channel (_("L"), DataType::AUDIO);
724 c->set_port (0, outputs[DataType::AUDIO][np]);
725 c->add_channel (_("R"), DataType::AUDIO);
726 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
732 /* mono input bundles */
734 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
736 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
738 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
739 c->add_channel (_("mono"), DataType::AUDIO);
740 c->set_port (0, inputs[DataType::AUDIO][np]);
745 /* stereo input bundles */
747 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
748 if (np + 1 < inputs[DataType::AUDIO].size()) {
750 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
752 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
753 c->add_channel (_("L"), DataType::AUDIO);
754 c->set_port (0, inputs[DataType::AUDIO][np]);
755 c->add_channel (_("R"), DataType::AUDIO);
756 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
762 /* MIDI input bundles */
764 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
765 string n = inputs[DataType::MIDI][np];
766 boost::erase_first (n, X_("alsa_pcm:"));
768 boost::shared_ptr<Bundle> c (new Bundle (n, false));
769 c->add_channel ("", DataType::MIDI);
770 c->set_port (0, inputs[DataType::MIDI][np]);
774 /* MIDI output bundles */
776 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
777 string n = outputs[DataType::MIDI][np];
778 boost::erase_first (n, X_("alsa_pcm:"));
780 boost::shared_ptr<Bundle> c (new Bundle (n, true));
781 c->add_channel ("", DataType::MIDI);
782 c->set_port (0, outputs[DataType::MIDI][np]);
789 Session::auto_connect_master_bus ()
791 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
795 /* if requested auto-connect the outputs to the first N physical ports.
798 uint32_t limit = _master_out->n_outputs().n_total();
799 vector<string> outputs[DataType::num_types];
801 for (uint32_t i = 0; i < DataType::num_types; ++i) {
802 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
805 for (uint32_t n = 0; n < limit; ++n) {
806 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
808 if (outputs[p->type()].size() > n) {
809 connect_to = outputs[p->type()][n];
812 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
813 if (_master_out->output()->connect (p, connect_to, this)) {
814 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
823 Session::remove_monitor_section ()
829 /* force reversion to Solo-In-Place */
830 Config->set_solo_control_is_listen_control (false);
832 /* if we are auditioning, cancel it ... this is a workaround
833 to a problem (auditioning does not execute the process graph,
834 which is needed to remove routes when using >1 core for processing)
839 /* Hold process lock while doing this so that we don't hear bits and
840 * pieces of audio as we work on each route.
843 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
845 /* Connect tracks to monitor section. Note that in an
846 existing session, the internal sends will already exist, but we want the
847 routes to notice that they connect to the control out specifically.
851 boost::shared_ptr<RouteList> r = routes.reader ();
852 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
854 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
856 if ((*x)->is_monitor()) {
858 } else if ((*x)->is_master()) {
861 (*x)->remove_aux_or_listen (_monitor_out);
866 remove_route (_monitor_out);
867 auto_connect_master_bus ();
870 auditioner->connect ();
875 Session::add_monitor_section ()
879 if (_monitor_out || !_master_out) {
883 boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
889 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
890 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
893 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
894 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
895 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
899 add_routes (rl, false, false, false);
901 assert (_monitor_out);
903 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
904 are undefined, at best.
907 uint32_t limit = _monitor_out->n_inputs().n_audio();
911 /* connect the inputs to the master bus outputs. this
912 * represents a separate data feed from the internal sends from
913 * each route. as of jan 2011, it allows the monitor section to
914 * conditionally ignore either the internal sends or the normal
915 * input feed, but we should really find a better way to do
919 _master_out->output()->disconnect (this);
921 for (uint32_t n = 0; n < limit; ++n) {
922 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
923 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
926 string connect_to = o->name();
927 if (_monitor_out->input()->connect (p, connect_to, this)) {
928 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
936 /* if monitor section is not connected, connect it to physical outs
939 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
941 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
943 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
946 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
948 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
949 Config->get_monitor_bus_preferred_bundle())
955 /* Monitor bus is audio only */
957 vector<string> outputs[DataType::num_types];
959 for (uint32_t i = 0; i < DataType::num_types; ++i) {
960 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
963 uint32_t mod = outputs[DataType::AUDIO].size();
964 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
968 for (uint32_t n = 0; n < limit; ++n) {
970 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
972 if (outputs[DataType::AUDIO].size() > (n % mod)) {
973 connect_to = outputs[DataType::AUDIO][n % mod];
976 if (!connect_to.empty()) {
977 if (_monitor_out->output()->connect (p, connect_to, this)) {
978 error << string_compose (
979 _("cannot connect control output %1 to %2"),
990 /* Hold process lock while doing this so that we don't hear bits and
991 * pieces of audio as we work on each route.
994 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
996 /* Connect tracks to monitor section. Note that in an
997 existing session, the internal sends will already exist, but we want the
998 routes to notice that they connect to the control out specifically.
1002 boost::shared_ptr<RouteList> rls = routes.reader ();
1004 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1006 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1008 if ((*x)->is_monitor()) {
1010 } else if ((*x)->is_master()) {
1013 (*x)->enable_monitor_send ();
1018 auditioner->connect ();
1023 Session::hookup_io ()
1025 /* stop graph reordering notifications from
1026 causing resorts, etc.
1029 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1033 /* we delay creating the auditioner till now because
1034 it makes its own connections to ports.
1038 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1040 throw failed_constructor ();
1042 a->use_new_diskstream ();
1046 catch (failed_constructor& err) {
1047 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1051 /* load bundles, which we may have postponed earlier on */
1052 if (_bundle_xml_node) {
1053 load_bundles (*_bundle_xml_node);
1054 delete _bundle_xml_node;
1057 /* Tell all IO objects to connect themselves together */
1059 IO::enable_connecting ();
1061 /* Now tell all "floating" ports to connect to whatever
1062 they should be connected to.
1065 AudioEngine::instance()->reconnect_ports ();
1067 /* Anyone who cares about input state, wake up and do something */
1069 IOConnectionsComplete (); /* EMIT SIGNAL */
1071 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1073 /* now handle the whole enchilada as if it was one
1074 graph reorder event.
1079 /* update the full solo state, which can't be
1080 correctly determined on a per-route basis, but
1081 needs the global overview that only the session
1085 update_route_solo_state ();
1089 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1091 boost::shared_ptr<Track> track = wp.lock ();
1096 boost::shared_ptr<Playlist> playlist;
1098 if ((playlist = track->playlist()) != 0) {
1099 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1100 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1101 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1106 Session::record_enabling_legal () const
1108 /* this used to be in here, but survey says.... we don't need to restrict it */
1109 // if (record_status() == Recording) {
1113 if (Config->get_all_safe()) {
1120 Session::set_track_monitor_input_status (bool yn)
1122 boost::shared_ptr<RouteList> rl = routes.reader ();
1123 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1124 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1125 if (tr && tr->record_enabled ()) {
1126 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1127 tr->request_input_monitoring (yn);
1133 Session::auto_punch_start_changed (Location* location)
1135 replace_event (SessionEvent::PunchIn, location->start());
1137 if (get_record_enabled() && config.get_punch_in()) {
1138 /* capture start has been changed, so save new pending state */
1139 save_state ("", true);
1144 Session::auto_punch_end_changed (Location* location)
1146 framepos_t when_to_stop = location->end();
1147 // when_to_stop += _worst_output_latency + _worst_input_latency;
1148 replace_event (SessionEvent::PunchOut, when_to_stop);
1152 Session::auto_punch_changed (Location* location)
1154 framepos_t when_to_stop = location->end();
1156 replace_event (SessionEvent::PunchIn, location->start());
1157 //when_to_stop += _worst_output_latency + _worst_input_latency;
1158 replace_event (SessionEvent::PunchOut, when_to_stop);
1161 /** @param loc A loop location.
1162 * @param pos Filled in with the start time of the required fade-out (in session frames).
1163 * @param length Filled in with the length of the required fade-out.
1166 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1168 pos = max (loc->start(), loc->end() - 64);
1169 length = loc->end() - pos;
1173 Session::auto_loop_changed (Location* location)
1175 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1178 auto_loop_declick_range (location, dcp, dcl);
1179 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1181 if (transport_rolling() && play_loop) {
1184 // if (_transport_frame > location->end()) {
1186 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1187 // relocate to beginning of loop
1188 clear_events (SessionEvent::LocateRoll);
1190 request_locate (location->start(), true);
1193 else if (Config->get_seamless_loop() && !loop_changing) {
1195 // schedule a locate-roll to refill the diskstreams at the
1196 // previous loop end
1197 loop_changing = true;
1199 if (location->end() > last_loopend) {
1200 clear_events (SessionEvent::LocateRoll);
1201 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1208 last_loopend = location->end();
1212 Session::set_auto_punch_location (Location* location)
1216 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1217 punch_connections.drop_connections();
1218 existing->set_auto_punch (false, this);
1219 remove_event (existing->start(), SessionEvent::PunchIn);
1220 clear_events (SessionEvent::PunchOut);
1221 auto_punch_location_changed (0);
1226 if (location == 0) {
1230 if (location->end() <= location->start()) {
1231 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1235 punch_connections.drop_connections ();
1237 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1238 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1239 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1241 location->set_auto_punch (true, this);
1243 auto_punch_changed (location);
1245 auto_punch_location_changed (location);
1249 Session::set_auto_loop_location (Location* location)
1253 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1254 loop_connections.drop_connections ();
1255 existing->set_auto_loop (false, this);
1256 remove_event (existing->end(), SessionEvent::AutoLoop);
1259 auto_loop_declick_range (existing, dcp, dcl);
1260 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1261 auto_loop_location_changed (0);
1266 if (location == 0) {
1270 if (location->end() <= location->start()) {
1271 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1275 last_loopend = location->end();
1277 loop_connections.drop_connections ();
1279 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1280 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1281 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1283 location->set_auto_loop (true, this);
1285 /* take care of our stuff first */
1287 auto_loop_changed (location);
1289 /* now tell everyone else */
1291 auto_loop_location_changed (location);
1295 Session::locations_added (Location *)
1301 Session::locations_changed ()
1303 _locations->apply (*this, &Session::handle_locations_changed);
1307 Session::handle_locations_changed (Locations::LocationList& locations)
1309 Locations::LocationList::iterator i;
1311 bool set_loop = false;
1312 bool set_punch = false;
1314 for (i = locations.begin(); i != locations.end(); ++i) {
1318 if (location->is_auto_punch()) {
1319 set_auto_punch_location (location);
1322 if (location->is_auto_loop()) {
1323 set_auto_loop_location (location);
1327 if (location->is_session_range()) {
1328 _session_range_location = location;
1333 set_auto_loop_location (0);
1336 set_auto_punch_location (0);
1343 Session::enable_record ()
1345 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1346 /* no recording at anything except normal speed */
1351 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1353 if (rs == Recording) {
1357 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1359 _last_record_location = _transport_frame;
1360 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1362 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1363 set_track_monitor_input_status (true);
1366 RecordStateChanged ();
1373 Session::disable_record (bool rt_context, bool force)
1377 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1379 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1380 g_atomic_int_set (&_record_status, Disabled);
1381 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1383 if (rs == Recording) {
1384 g_atomic_int_set (&_record_status, Enabled);
1388 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1389 set_track_monitor_input_status (false);
1392 RecordStateChanged (); /* emit signal */
1395 remove_pending_capture_state ();
1401 Session::step_back_from_record ()
1403 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1405 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1406 set_track_monitor_input_status (false);
1409 RecordStateChanged (); /* emit signal */
1414 Session::maybe_enable_record ()
1416 if (_step_editors > 0) {
1420 g_atomic_int_set (&_record_status, Enabled);
1422 /* This function is currently called from somewhere other than an RT thread.
1423 This save_state() call therefore doesn't impact anything. Doing it here
1424 means that we save pending state of which sources the next record will use,
1425 which gives us some chance of recovering from a crash during the record.
1428 save_state ("", true);
1430 if (_transport_speed) {
1431 if (!config.get_punch_in()) {
1435 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1436 RecordStateChanged (); /* EMIT SIGNAL */
1443 Session::audible_frame () const
1449 /* the first of these two possible settings for "offset"
1450 mean that the audible frame is stationary until
1451 audio emerges from the latency compensation
1454 the second means that the audible frame is stationary
1455 until audio would emerge from a physical port
1456 in the absence of any plugin latency compensation
1459 offset = worst_playback_latency ();
1461 if (offset > current_block_size) {
1462 offset -= current_block_size;
1464 /* XXX is this correct? if we have no external
1465 physical connections and everything is internal
1466 then surely this is zero? still, how
1467 likely is that anyway?
1469 offset = current_block_size;
1472 if (synced_to_engine()) {
1473 tf = _engine.transport_frame();
1475 tf = _transport_frame;
1480 if (!non_realtime_work_pending()) {
1484 /* Check to see if we have passed the first guaranteed
1485 audible frame past our last start position. if not,
1486 return that last start point because in terms
1487 of audible frames, we have not moved yet.
1489 `Start position' in this context means the time we last
1490 either started, located, or changed transport direction.
1493 if (_transport_speed > 0.0f) {
1495 if (!play_loop || !have_looped) {
1496 if (tf < _last_roll_or_reversal_location + offset) {
1497 return _last_roll_or_reversal_location;
1505 } else if (_transport_speed < 0.0f) {
1507 /* XXX wot? no backward looping? */
1509 if (tf > _last_roll_or_reversal_location - offset) {
1510 return _last_roll_or_reversal_location;
1522 Session::set_frame_rate (framecnt_t frames_per_second)
1524 /** \fn void Session::set_frame_size(framecnt_t)
1525 the AudioEngine object that calls this guarantees
1526 that it will not be called while we are also in
1527 ::process(). Its fine to do things that block
1531 _base_frame_rate = frames_per_second;
1532 _nominal_frame_rate = frames_per_second;
1538 // XXX we need some equivalent to this, somehow
1539 // SndFileSource::setup_standard_crossfades (frames_per_second);
1543 /* XXX need to reset/reinstantiate all LADSPA plugins */
1547 Session::set_block_size (pframes_t nframes)
1549 /* the AudioEngine guarantees
1550 that it will not be called while we are also in
1551 ::process(). It is therefore fine to do things that block
1556 current_block_size = nframes;
1560 boost::shared_ptr<RouteList> r = routes.reader ();
1562 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1563 (*i)->set_block_size (nframes);
1566 boost::shared_ptr<RouteList> rl = routes.reader ();
1567 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1568 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1570 tr->set_block_size (nframes);
1574 set_worst_io_latencies ();
1580 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1582 boost::shared_ptr<Route> r2;
1584 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1585 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1589 /* make a copy of the existing list of routes that feed r1 */
1591 Route::FedBy existing (r1->fed_by());
1593 /* for each route that feeds r1, recurse, marking it as feeding
1597 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1598 if (!(r2 = i->r.lock ())) {
1599 /* (*i) went away, ignore it */
1603 /* r2 is a route that feeds r1 which somehow feeds base. mark
1604 base as being fed by r2
1607 rbase->add_fed_by (r2, i->sends_only);
1611 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1615 if (r1->feeds (r2) && r2->feeds (r1)) {
1619 /* now recurse, so that we can mark base as being fed by
1620 all routes that feed r2
1623 trace_terminal (r2, rbase);
1630 Session::resort_routes ()
1632 /* don't do anything here with signals emitted
1633 by Routes during initial setup or while we
1634 are being destroyed.
1637 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1642 RCUWriter<RouteList> writer (routes);
1643 boost::shared_ptr<RouteList> r = writer.get_copy ();
1644 resort_routes_using (r);
1645 /* writer goes out of scope and forces update */
1649 boost::shared_ptr<RouteList> rl = routes.reader ();
1650 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1651 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1653 const Route::FedBy& fb ((*i)->fed_by());
1655 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1656 boost::shared_ptr<Route> sf = f->r.lock();
1658 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1666 /** This is called whenever we need to rebuild the graph of how we will process
1668 * @param r List of routes, in any order.
1672 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1674 /* We are going to build a directed graph of our routes;
1675 this is where the edges of that graph are put.
1680 /* Go through all routes doing two things:
1682 * 1. Collect the edges of the route graph. Each of these edges
1683 * is a pair of routes, one of which directly feeds the other
1684 * either by a JACK connection or by an internal send.
1686 * 2. Begin the process of making routes aware of which other
1687 * routes directly or indirectly feed them. This information
1688 * is used by the solo code.
1691 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1693 /* Clear out the route's list of direct or indirect feeds */
1694 (*i)->clear_fed_by ();
1696 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1698 bool via_sends_only;
1700 /* See if this *j feeds *i according to the current state of the JACK
1701 connections and internal sends.
1703 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1704 /* add the edge to the graph (part #1) */
1705 edges.add (*j, *i, via_sends_only);
1706 /* tell the route (for part #2) */
1707 (*i)->add_fed_by (*j, via_sends_only);
1712 /* Attempt a topological sort of the route graph */
1713 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1715 if (sorted_routes) {
1716 /* We got a satisfactory topological sort, so there is no feedback;
1719 Note: the process graph rechain does not require a
1720 topologically-sorted list, but hey ho.
1722 if (_process_graph) {
1723 _process_graph->rechain (sorted_routes, edges);
1726 _current_route_graph = edges;
1728 /* Complete the building of the routes' lists of what directly
1729 or indirectly feeds them.
1731 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1732 trace_terminal (*i, *i);
1735 *r = *sorted_routes;
1738 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1739 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1740 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1741 (*i)->name(), (*i)->order_key ()));
1745 SuccessfulGraphSort (); /* EMIT SIGNAL */
1748 /* The topological sort failed, so we have a problem. Tell everyone
1749 and stick to the old graph; this will continue to be processed, so
1750 until the feedback is fixed, what is played back will not quite
1751 reflect what is actually connected. Note also that we do not
1752 do trace_terminal here, as it would fail due to an endless recursion,
1753 so the solo code will think that everything is still connected
1757 FeedbackDetected (); /* EMIT SIGNAL */
1762 /** Find a route name starting with \a base, maybe followed by the
1763 * lowest \a id. \a id will always be added if \a definitely_add_number
1764 * is true on entry; otherwise it will only be added if required
1765 * to make the name unique.
1767 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1768 * The available route name with the lowest ID will be used, and \a id
1769 * will be set to the ID.
1771 * \return false if a route name could not be found, and \a track_name
1772 * and \a id do not reflect a free route name.
1775 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1777 if (!definitely_add_number && route_by_name (base) == 0) {
1778 /* juse use the base */
1779 snprintf (name, name_len, "%s", base.c_str());
1784 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1786 if (route_by_name (name) == 0) {
1792 } while (id < (UINT_MAX-1));
1797 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1799 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1801 in = ChanCount::ZERO;
1802 out = ChanCount::ZERO;
1804 boost::shared_ptr<RouteList> r = routes.reader ();
1806 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1807 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1808 if (tr && !tr->is_auditioner()) {
1809 in += tr->n_inputs();
1810 out += tr->n_outputs();
1815 /** Caller must not hold process lock
1816 * @param name_template string to use for the start of the name, or "" to use "MIDI".
1817 * @param instrument plugin info for the instrument to insert pre-fader, if any
1819 list<boost::shared_ptr<MidiTrack> >
1820 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
1821 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1823 char track_name[32];
1824 uint32_t track_id = 0;
1826 RouteList new_routes;
1827 list<boost::shared_ptr<MidiTrack> > ret;
1829 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1832 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1833 error << "cannot find name for new midi track" << endmsg;
1837 boost::shared_ptr<MidiTrack> track;
1840 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1842 if (track->init ()) {
1846 track->use_new_diskstream();
1848 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1849 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1852 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1853 if (track->input()->ensure_io (input, false, this)) {
1854 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
1858 if (track->output()->ensure_io (output, false, this)) {
1859 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1864 track->non_realtime_input_change();
1867 route_group->add (track);
1870 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1872 if (Config->get_remote_model() == UserOrdered) {
1873 track->set_remote_control_id (next_control_id());
1876 new_routes.push_back (track);
1877 ret.push_back (track);
1880 catch (failed_constructor &err) {
1881 error << _("Session: could not create new midi track.") << endmsg;
1885 catch (AudioEngine::PortRegistrationFailure& pfe) {
1887 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;
1895 if (!new_routes.empty()) {
1896 StateProtector sp (this);
1897 add_routes (new_routes, true, true, true);
1900 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1901 PluginPtr plugin = instrument->load (*this);
1902 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1903 (*r)->add_processor (p, PreFader);
1913 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1915 boost::shared_ptr<Route> midi_track (wmt.lock());
1921 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1923 if (change.after.n_audio() <= change.before.n_audio()) {
1927 /* new audio ports: make sure the audio goes somewhere useful,
1928 unless the user has no-auto-connect selected.
1930 The existing ChanCounts don't matter for this call as they are only
1931 to do with matching input and output indices, and we are only changing
1937 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1941 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1942 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1943 * @param output_start As \a input_start, but for outputs.
1946 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1947 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1949 if (!IO::connecting_legal) {
1953 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1959 /* If both inputs and outputs are auto-connected to physical ports,
1960 use the max of input and output offsets to ensure auto-connected
1961 port numbers always match up (e.g. the first audio input and the
1962 first audio output of the route will have the same physical
1963 port number). Otherwise just use the lowest input or output
1967 DEBUG_TRACE (DEBUG::Graph,
1968 string_compose("Auto-connect: existing in = %1 out = %2\n",
1969 existing_inputs, existing_outputs));
1971 const bool in_out_physical =
1972 (Config->get_input_auto_connect() & AutoConnectPhysical)
1973 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1976 const ChanCount in_offset = in_out_physical
1977 ? ChanCount::max(existing_inputs, existing_outputs)
1980 const ChanCount out_offset = in_out_physical
1981 ? ChanCount::max(existing_inputs, existing_outputs)
1984 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1985 vector<string> physinputs;
1986 vector<string> physoutputs;
1988 _engine.get_physical_outputs (*t, physoutputs);
1989 _engine.get_physical_inputs (*t, physinputs);
1991 if (!physinputs.empty() && connect_inputs) {
1992 uint32_t nphysical_in = physinputs.size();
1994 DEBUG_TRACE (DEBUG::Graph,
1995 string_compose("There are %1 physical inputs of type %2\n",
1998 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2001 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2002 DEBUG_TRACE (DEBUG::Graph,
2003 string_compose("Get index %1 + %2 % %3 = %4\n",
2004 in_offset.get(*t), i, nphysical_in,
2005 (in_offset.get(*t) + i) % nphysical_in));
2006 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2009 DEBUG_TRACE (DEBUG::Graph,
2010 string_compose("Connect route %1 IN to %2\n",
2011 route->name(), port));
2013 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2017 ChanCount one_added (*t, 1);
2018 existing_inputs += one_added;
2022 if (!physoutputs.empty()) {
2023 uint32_t nphysical_out = physoutputs.size();
2024 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2027 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2028 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2029 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2030 /* master bus is audio only */
2031 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2032 port = _master_out->input()->ports().port(*t,
2033 i % _master_out->input()->n_ports().get(*t))->name();
2037 DEBUG_TRACE (DEBUG::Graph,
2038 string_compose("Connect route %1 OUT to %2\n",
2039 route->name(), port));
2041 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2045 ChanCount one_added (*t, 1);
2046 existing_outputs += one_added;
2052 /** Caller must not hold process lock
2053 * @param name_template string to use for the start of the name, or "" to use "Audio".
2055 list< boost::shared_ptr<AudioTrack> >
2056 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2057 uint32_t how_many, string name_template)
2059 char track_name[32];
2060 uint32_t track_id = 0;
2062 RouteList new_routes;
2063 list<boost::shared_ptr<AudioTrack> > ret;
2065 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2068 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2069 error << "cannot find name for new audio track" << endmsg;
2073 boost::shared_ptr<AudioTrack> track;
2076 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2078 if (track->init ()) {
2082 track->use_new_diskstream();
2084 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2085 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2088 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2090 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2091 error << string_compose (
2092 _("cannot configure %1 in/%2 out configuration for new audio track"),
2093 input_channels, output_channels)
2098 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2099 error << string_compose (
2100 _("cannot configure %1 in/%2 out configuration for new audio track"),
2101 input_channels, output_channels)
2108 route_group->add (track);
2111 track->non_realtime_input_change();
2113 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2114 if (Config->get_remote_model() == UserOrdered) {
2115 track->set_remote_control_id (next_control_id());
2118 new_routes.push_back (track);
2119 ret.push_back (track);
2122 catch (failed_constructor &err) {
2123 error << _("Session: could not create new audio track.") << endmsg;
2127 catch (AudioEngine::PortRegistrationFailure& pfe) {
2129 error << pfe.what() << endmsg;
2137 if (!new_routes.empty()) {
2138 StateProtector sp (this);
2139 add_routes (new_routes, true, true, true);
2145 /** Caller must not hold process lock.
2146 * @param name_template string to use for the start of the name, or "" to use "Bus".
2149 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2152 uint32_t bus_id = 0;
2156 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2159 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2160 error << "cannot find name for new audio bus" << endmsg;
2165 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2171 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2172 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2175 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2177 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2178 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2179 input_channels, output_channels)
2185 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2186 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2187 input_channels, output_channels)
2194 route_group->add (bus);
2196 if (Config->get_remote_model() == UserOrdered) {
2197 bus->set_remote_control_id (next_control_id());
2200 bus->add_internal_return ();
2202 ret.push_back (bus);
2208 catch (failed_constructor &err) {
2209 error << _("Session: could not create new audio route.") << endmsg;
2213 catch (AudioEngine::PortRegistrationFailure& pfe) {
2214 error << pfe.what() << endmsg;
2224 StateProtector sp (this);
2225 add_routes (ret, false, true, true); // autoconnect outputs only
2233 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2236 uint32_t control_id;
2238 uint32_t number = 0;
2239 const uint32_t being_added = how_many;
2241 if (!tree.read (template_path.c_str())) {
2245 XMLNode* node = tree.root();
2247 IO::disable_connecting ();
2249 control_id = next_control_id ();
2253 XMLNode node_copy (*node);
2255 /* Remove IDs of everything so that new ones are used */
2256 node_copy.remove_property_recursively (X_("id"));
2261 if (!name_base.empty()) {
2263 /* if we're adding more than one routes, force
2264 * all the names of the new routes to be
2265 * numbered, via the final parameter.
2268 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2269 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2275 string const route_name = node_copy.property(X_("name"))->value ();
2277 /* generate a new name by adding a number to the end of the template name */
2278 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2279 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2284 /* set this name in the XML description that we are about to use */
2285 Route::set_name_in_state (node_copy, name);
2287 /* trim bitslots from listen sends so that new ones are used */
2288 XMLNodeList children = node_copy.children ();
2289 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2290 if ((*i)->name() == X_("Processor")) {
2291 XMLProperty* role = (*i)->property (X_("role"));
2292 if (role && role->value() == X_("Listen")) {
2293 (*i)->remove_property (X_("bitslot"));
2298 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2301 error << _("Session: cannot create track/bus from template description") << endmsg;
2305 if (boost::dynamic_pointer_cast<Track>(route)) {
2306 /* force input/output change signals so that the new diskstream
2307 picks up the configuration of the route. During session
2308 loading this normally happens in a different way.
2311 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2313 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2314 change.after = route->input()->n_ports();
2315 route->input()->changed (change, this);
2316 change.after = route->output()->n_ports();
2317 route->output()->changed (change, this);
2320 route->set_remote_control_id (control_id);
2323 ret.push_back (route);
2326 catch (failed_constructor &err) {
2327 error << _("Session: could not create new route from template") << endmsg;
2331 catch (AudioEngine::PortRegistrationFailure& pfe) {
2332 error << pfe.what() << endmsg;
2341 StateProtector sp (this);
2342 add_routes (ret, true, true, true);
2343 IO::enable_connecting ();
2350 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2353 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2354 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2357 error << _("Adding new tracks/busses failed") << endmsg;
2362 update_latency (true);
2363 update_latency (false);
2368 save_state (_current_snapshot_name);
2371 reassign_track_numbers();
2373 RouteAdded (new_routes); /* EMIT SIGNAL */
2377 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2379 ChanCount existing_inputs;
2380 ChanCount existing_outputs;
2381 uint32_t order = next_control_id();
2383 if (_order_hint != 0) {
2384 order = _order_hint;
2388 count_existing_track_channels (existing_inputs, existing_outputs);
2391 RCUWriter<RouteList> writer (routes);
2392 boost::shared_ptr<RouteList> r = writer.get_copy ();
2393 r->insert (r->end(), new_routes.begin(), new_routes.end());
2395 /* if there is no control out and we're not in the middle of loading,
2396 resort the graph here. if there is a control out, we will resort
2397 toward the end of this method. if we are in the middle of loading,
2398 we will resort when done.
2401 if (!_monitor_out && IO::connecting_legal) {
2402 resort_routes_using (r);
2406 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2408 boost::weak_ptr<Route> wpr (*x);
2409 boost::shared_ptr<Route> r (*x);
2411 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2412 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2413 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2414 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2415 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2416 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2418 if (r->is_master()) {
2422 if (r->is_monitor()) {
2426 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2428 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2429 track_playlist_changed (boost::weak_ptr<Track> (tr));
2430 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2432 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2434 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2435 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2440 if (input_auto_connect || output_auto_connect) {
2441 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2444 /* order keys are a GUI responsibility but we need to set up
2445 reasonable defaults because they also affect the remote control
2446 ID in most situations.
2449 if (!r->has_order_key ()) {
2450 if (r->is_auditioner()) {
2451 /* use an arbitrarily high value */
2452 r->set_order_key (UINT_MAX);
2454 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2455 r->set_order_key (order);
2463 if (_monitor_out && IO::connecting_legal) {
2464 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2466 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2467 if ((*x)->is_monitor()) {
2469 } else if ((*x)->is_master()) {
2472 (*x)->enable_monitor_send ();
2479 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2481 boost::shared_ptr<RouteList> r = routes.reader ();
2482 boost::shared_ptr<Send> s;
2484 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2485 if ((s = (*i)->internal_send_for (dest)) != 0) {
2486 s->amp()->gain_control()->set_value (0.0);
2492 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2494 boost::shared_ptr<RouteList> r = routes.reader ();
2495 boost::shared_ptr<Send> s;
2497 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2498 if ((s = (*i)->internal_send_for (dest)) != 0) {
2499 s->amp()->gain_control()->set_value (1.0);
2505 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2507 boost::shared_ptr<RouteList> r = routes.reader ();
2508 boost::shared_ptr<Send> s;
2510 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2511 if ((s = (*i)->internal_send_for (dest)) != 0) {
2512 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2517 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2519 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2521 boost::shared_ptr<RouteList> r = routes.reader ();
2522 boost::shared_ptr<RouteList> t (new RouteList);
2524 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2525 /* no MIDI sends because there are no MIDI busses yet */
2526 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2531 add_internal_sends (dest, p, t);
2535 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2537 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2538 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2543 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2545 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2549 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2551 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2555 if (!dest->internal_return()) {
2556 dest->add_internal_return ();
2559 sender->add_aux_send (dest, before);
2565 Session::remove_route (boost::shared_ptr<Route> route)
2567 if (route == _master_out) {
2571 route->set_solo (false, this);
2574 RCUWriter<RouteList> writer (routes);
2575 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2579 /* deleting the master out seems like a dumb
2580 idea, but its more of a UI policy issue
2584 if (route == _master_out) {
2585 _master_out = boost::shared_ptr<Route> ();
2588 if (route == _monitor_out) {
2589 _monitor_out.reset ();
2592 /* writer goes out of scope, forces route list update */
2595 update_route_solo_state ();
2597 // We need to disconnect the route's inputs and outputs
2599 route->input()->disconnect (0);
2600 route->output()->disconnect (0);
2602 /* if the route had internal sends sending to it, remove them */
2603 if (route->internal_return()) {
2605 boost::shared_ptr<RouteList> r = routes.reader ();
2606 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2607 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2609 (*i)->remove_processor (s);
2614 /* if the monitoring section had a pointer to this route, remove it */
2615 if (_monitor_out && !route->is_master() && !route->is_monitor()) {
2616 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2617 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
2618 route->remove_aux_or_listen (_monitor_out);
2621 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2622 if (mt && mt->step_editing()) {
2623 if (_step_editors > 0) {
2628 update_latency_compensation ();
2631 /* Re-sort routes to remove the graph's current references to the one that is
2632 * going away, then flush old references out of the graph.
2636 if (_process_graph) {
2637 _process_graph->clear_other_chain ();
2640 /* get rid of it from the dead wood collection in the route list manager */
2642 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2646 /* try to cause everyone to drop their references */
2648 route->drop_references ();
2650 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2652 /* save the new state of the world */
2654 if (save_state (_current_snapshot_name)) {
2655 save_history (_current_snapshot_name);
2657 reassign_track_numbers();
2661 Session::route_mute_changed (void* /*src*/)
2667 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2669 boost::shared_ptr<Route> route = wpr.lock();
2671 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2675 if (route->listening_via_monitor ()) {
2677 if (Config->get_exclusive_solo()) {
2678 /* new listen: disable all other listen */
2679 boost::shared_ptr<RouteList> r = routes.reader ();
2680 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2681 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2684 (*i)->set_listen (false, this);
2690 } else if (_listen_cnt > 0) {
2695 update_route_solo_state ();
2698 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2700 boost::shared_ptr<Route> route = wpr.lock ();
2703 /* should not happen */
2704 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2708 bool send_changed = false;
2710 if (route->solo_isolated()) {
2711 if (_solo_isolated_cnt == 0) {
2712 send_changed = true;
2714 _solo_isolated_cnt++;
2715 } else if (_solo_isolated_cnt > 0) {
2716 _solo_isolated_cnt--;
2717 if (_solo_isolated_cnt == 0) {
2718 send_changed = true;
2723 IsolatedChanged (); /* EMIT SIGNAL */
2728 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2730 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2732 if (!self_solo_change) {
2733 // session doesn't care about changes to soloed-by-others
2737 if (solo_update_disabled) {
2739 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2743 boost::shared_ptr<Route> route = wpr.lock ();
2746 boost::shared_ptr<RouteList> r = routes.reader ();
2749 if (route->self_soloed()) {
2755 RouteGroup* rg = route->route_group ();
2756 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2758 if (delta == 1 && Config->get_exclusive_solo()) {
2760 /* new solo: disable all other solos, but not the group if its solo-enabled */
2762 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2763 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2764 (leave_group_alone && ((*i)->route_group() == rg))) {
2767 (*i)->set_solo (false, this);
2771 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2773 solo_update_disabled = true;
2775 RouteList uninvolved;
2777 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2779 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2780 bool via_sends_only;
2781 bool in_signal_flow;
2783 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2784 (leave_group_alone && ((*i)->route_group() == rg))) {
2788 in_signal_flow = false;
2790 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2792 if ((*i)->feeds (route, &via_sends_only)) {
2793 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2794 if (!via_sends_only) {
2795 if (!route->soloed_by_others_upstream()) {
2796 (*i)->mod_solo_by_others_downstream (delta);
2799 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2801 in_signal_flow = true;
2803 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2806 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2808 if (route->feeds (*i, &via_sends_only)) {
2809 /* propagate solo upstream only if routing other than
2810 sends is involved, but do consider the other route
2811 (*i) to be part of the signal flow even if only
2814 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2818 route->soloed_by_others_downstream(),
2819 route->soloed_by_others_upstream()));
2820 if (!via_sends_only) {
2821 if (!route->soloed_by_others_downstream()) {
2822 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2823 (*i)->mod_solo_by_others_upstream (delta);
2825 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2828 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2830 in_signal_flow = true;
2832 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2835 if (!in_signal_flow) {
2836 uninvolved.push_back (*i);
2840 solo_update_disabled = false;
2841 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2843 update_route_solo_state (r);
2845 /* now notify that the mute state of the routes not involved in the signal
2846 pathway of the just-solo-changed route may have altered.
2849 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2850 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2851 (*i)->mute_changed (this);
2854 SoloChanged (); /* EMIT SIGNAL */
2859 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2861 /* now figure out if anything that matters is soloed (or is "listening")*/
2863 bool something_soloed = false;
2864 uint32_t listeners = 0;
2865 uint32_t isolated = 0;
2868 r = routes.reader();
2871 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2872 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2873 something_soloed = true;
2876 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2877 if (Config->get_solo_control_is_listen_control()) {
2880 (*i)->set_listen (false, this);
2884 if ((*i)->solo_isolated()) {
2889 if (something_soloed != _non_soloed_outs_muted) {
2890 _non_soloed_outs_muted = something_soloed;
2891 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2894 _listen_cnt = listeners;
2896 if (isolated != _solo_isolated_cnt) {
2897 _solo_isolated_cnt = isolated;
2898 IsolatedChanged (); /* EMIT SIGNAL */
2901 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2902 something_soloed, listeners, isolated));
2905 boost::shared_ptr<RouteList>
2906 Session::get_routes_with_internal_returns() const
2908 boost::shared_ptr<RouteList> r = routes.reader ();
2909 boost::shared_ptr<RouteList> rl (new RouteList);
2911 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2912 if ((*i)->internal_return ()) {
2920 Session::io_name_is_legal (const std::string& name)
2922 boost::shared_ptr<RouteList> r = routes.reader ();
2924 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2925 if ((*i)->name() == name) {
2929 if ((*i)->has_io_processor_named (name)) {
2938 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2941 vector<string> connections;
2943 /* if we are passed only a single route and we're not told to turn
2944 * others off, then just do the simple thing.
2947 if (flip_others == false && rl->size() == 1) {
2948 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2950 mt->set_input_active (onoff);
2955 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2957 PortSet& ps ((*rt)->input()->ports());
2959 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2960 p->get_connections (connections);
2963 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2964 routes_using_input_from (*s, rl2);
2967 /* scan all relevant routes to see if others are on or off */
2969 bool others_are_already_on = false;
2971 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2973 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2979 if ((*r) != (*rt)) {
2980 if (mt->input_active()) {
2981 others_are_already_on = true;
2984 /* this one needs changing */
2985 mt->set_input_active (onoff);
2991 /* globally reverse other routes */
2993 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2994 if ((*r) != (*rt)) {
2995 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2997 mt->set_input_active (!others_are_already_on);
3006 Session::routes_using_input_from (const string& str, RouteList& rl)
3008 boost::shared_ptr<RouteList> r = routes.reader();
3010 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3011 if ((*i)->input()->connected_to (str)) {
3017 boost::shared_ptr<Route>
3018 Session::route_by_name (string name)
3020 boost::shared_ptr<RouteList> r = routes.reader ();
3022 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3023 if ((*i)->name() == name) {
3028 return boost::shared_ptr<Route> ((Route*) 0);
3031 boost::shared_ptr<Route>
3032 Session::route_by_id (PBD::ID id)
3034 boost::shared_ptr<RouteList> r = routes.reader ();
3036 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3037 if ((*i)->id() == id) {
3042 return boost::shared_ptr<Route> ((Route*) 0);
3045 boost::shared_ptr<Track>
3046 Session::track_by_diskstream_id (PBD::ID id)
3048 boost::shared_ptr<RouteList> r = routes.reader ();
3050 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3051 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3052 if (t && t->using_diskstream_id (id)) {
3057 return boost::shared_ptr<Track> ();
3060 boost::shared_ptr<Route>
3061 Session::route_by_remote_id (uint32_t id)
3063 boost::shared_ptr<RouteList> r = routes.reader ();
3065 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3066 if ((*i)->remote_control_id() == id) {
3071 return boost::shared_ptr<Route> ((Route*) 0);
3076 Session::reassign_track_numbers ()
3080 RouteList r (*(routes.reader ()));
3081 SignalOrderRouteSorter sorter;
3084 StateProtector sp (this);
3086 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3087 if (boost::dynamic_pointer_cast<Track> (*i)) {
3088 (*i)->set_track_number(++tn);
3090 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
3091 (*i)->set_track_number(--bn);
3094 const uint32_t decimals = ceilf (log10f (tn + 1));
3095 const bool decimals_changed = _track_number_decimals != decimals;
3096 _track_number_decimals = decimals;
3098 if (decimals_changed && config.get_track_name_number ()) {
3099 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3100 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3102 t->resync_track_name();
3105 // trigger GUI re-layout
3106 config.ParameterChanged("track-name-number");
3111 Session::playlist_region_added (boost::weak_ptr<Region> w)
3113 boost::shared_ptr<Region> r = w.lock ();
3118 /* These are the operations that are currently in progress... */
3119 list<GQuark> curr = _current_trans_quarks;
3122 /* ...and these are the operations during which we want to update
3123 the session range location markers.
3126 ops.push_back (Operations::capture);
3127 ops.push_back (Operations::paste);
3128 ops.push_back (Operations::duplicate_region);
3129 ops.push_back (Operations::insert_file);
3130 ops.push_back (Operations::insert_region);
3131 ops.push_back (Operations::drag_region_brush);
3132 ops.push_back (Operations::region_drag);
3133 ops.push_back (Operations::selection_grab);
3134 ops.push_back (Operations::region_fill);
3135 ops.push_back (Operations::fill_selection);
3136 ops.push_back (Operations::create_region);
3137 ops.push_back (Operations::region_copy);
3138 ops.push_back (Operations::fixed_time_region_copy);
3141 /* See if any of the current operations match the ones that we want */
3143 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3145 /* If so, update the session range markers */
3147 maybe_update_session_range (r->position (), r->last_frame ());
3151 /** Update the session range markers if a is before the current start or
3152 * b is after the current end.
3155 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3157 if (_state_of_the_state & Loading) {
3161 if (_session_range_location == 0) {
3163 add_session_range_location (a, b);
3167 if (a < _session_range_location->start()) {
3168 _session_range_location->set_start (a);
3171 if (b > _session_range_location->end()) {
3172 _session_range_location->set_end (b);
3178 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3180 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3181 maybe_update_session_range (i->to, i->to + i->length);
3186 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3188 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3189 maybe_update_session_range (i->from, i->to);
3193 /* Region management */
3195 boost::shared_ptr<Region>
3196 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3198 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3199 RegionFactory::RegionMap::const_iterator i;
3200 boost::shared_ptr<Region> region;
3202 Glib::Threads::Mutex::Lock lm (region_lock);
3204 for (i = regions.begin(); i != regions.end(); ++i) {
3208 if (region->whole_file()) {
3210 if (child->source_equivalent (region)) {
3216 return boost::shared_ptr<Region> ();
3220 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3222 set<boost::shared_ptr<Region> > relevant_regions;
3224 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3225 RegionFactory::get_regions_using_source (*s, relevant_regions);
3228 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3229 set<boost::shared_ptr<Region> >::iterator tmp;
3234 playlists->destroy_region (*r);
3235 RegionFactory::map_remove (*r);
3237 (*r)->drop_sources ();
3238 (*r)->drop_references ();
3240 relevant_regions.erase (r);
3245 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3248 Glib::Threads::Mutex::Lock ls (source_lock);
3249 /* remove from the main source list */
3250 sources.erase ((*s)->id());
3253 (*s)->mark_for_remove ();
3254 (*s)->drop_references ();
3263 Session::remove_last_capture ()
3265 list<boost::shared_ptr<Source> > srcs;
3267 boost::shared_ptr<RouteList> rl = routes.reader ();
3268 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3269 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3274 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3277 srcs.insert (srcs.end(), l.begin(), l.end());
3282 destroy_sources (srcs);
3284 save_state (_current_snapshot_name);
3289 /* Source Management */
3292 Session::add_source (boost::shared_ptr<Source> source)
3294 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3295 pair<SourceMap::iterator,bool> result;
3297 entry.first = source->id();
3298 entry.second = source;
3301 Glib::Threads::Mutex::Lock lm (source_lock);
3302 result = sources.insert (entry);
3305 if (result.second) {
3307 /* yay, new source */
3309 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3312 if (!fs->within_session()) {
3313 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3319 boost::shared_ptr<AudioFileSource> afs;
3321 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3322 if (Config->get_auto_analyse_audio()) {
3323 Analyser::queue_source_for_analysis (source, false);
3327 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3332 Session::remove_source (boost::weak_ptr<Source> src)
3334 if (_state_of_the_state & Deletion) {
3338 SourceMap::iterator i;
3339 boost::shared_ptr<Source> source = src.lock();
3346 Glib::Threads::Mutex::Lock lm (source_lock);
3348 if ((i = sources.find (source->id())) != sources.end()) {
3353 if (!(_state_of_the_state & InCleanup)) {
3355 /* save state so we don't end up with a session file
3356 referring to non-existent sources.
3359 save_state (_current_snapshot_name);
3363 boost::shared_ptr<Source>
3364 Session::source_by_id (const PBD::ID& id)
3366 Glib::Threads::Mutex::Lock lm (source_lock);
3367 SourceMap::iterator i;
3368 boost::shared_ptr<Source> source;
3370 if ((i = sources.find (id)) != sources.end()) {
3377 boost::shared_ptr<AudioFileSource>
3378 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3380 /* Restricted to audio files because only audio sources have channel
3384 Glib::Threads::Mutex::Lock lm (source_lock);
3386 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3387 boost::shared_ptr<AudioFileSource> afs
3388 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3390 if (afs && afs->path() == path && chn == afs->channel()) {
3395 return boost::shared_ptr<AudioFileSource>();
3398 boost::shared_ptr<MidiSource>
3399 Session::midi_source_by_path (const std::string& path) const
3401 /* Restricted to MIDI files because audio sources require a channel
3402 for unique identification, in addition to a path.
3405 Glib::Threads::Mutex::Lock lm (source_lock);
3407 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3408 boost::shared_ptr<MidiSource> ms
3409 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3410 boost::shared_ptr<FileSource> fs
3411 = boost::dynamic_pointer_cast<FileSource>(s->second);
3413 if (ms && fs && fs->path() == path) {
3418 return boost::shared_ptr<MidiSource>();
3422 Session::count_sources_by_origin (const string& path)
3425 Glib::Threads::Mutex::Lock lm (source_lock);
3427 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3428 boost::shared_ptr<FileSource> fs
3429 = boost::dynamic_pointer_cast<FileSource>(i->second);
3431 if (fs && fs->origin() == path) {
3440 Session::peak_path (string base) const
3442 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3445 /** Return a unique name based on \a base for a new internal audio source */
3447 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
3450 string possible_name;
3451 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
3453 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3454 bool some_related_source_name_exists = false;
3456 possible_name[0] = '\0';
3457 legalized = legalize_for_path (base);
3459 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3461 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3463 vector<space_and_path>::iterator i;
3464 uint32_t existing = 0;
3466 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3472 sstr << setfill ('0') << setw (4) << cnt;
3477 if (take_required || some_related_source_name_exists) {
3489 } else if (nchan > 2 && nchan < 26) {
3496 possible_name = sstr.str();
3497 SessionDirectory sdir((*i).path);
3498 const string spath = sdir.sound_path();
3500 /* note that we search *without* the extension so that
3501 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3502 in the event that this new name is required for
3503 a file format change.
3506 if (matching_unsuffixed_filename_exists_in (spath, possible_name)) {
3511 /* it is possible that we have the path already
3512 * assigned to a source that has not yet been written
3513 * (ie. the write source for a diskstream). we have to
3514 * check this in order to make sure that our candidate
3515 * path isn't used again, because that can lead to
3516 * two Sources point to the same file with different
3517 * notions of their removability.
3520 string possible_path = Glib::build_filename (spath, possible_name);
3522 if (audio_source_by_path_and_channel (possible_path, chan)) {
3528 if (existing == 0) {
3532 some_related_source_name_exists = true;
3535 error << string_compose(
3536 _("There are already %1 recordings for %2, which I consider too many."),
3537 limit, base) << endmsg;
3539 throw failed_constructor();
3543 /* We've established that the new name does not exist in any session
3544 * directory, so now find out which one we should use for this new
3548 SessionDirectory sdir (get_best_session_directory_for_new_audio());
3550 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
3555 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3557 Session::new_midi_source_path (const string& base)
3560 char buf[PATH_MAX+1];
3561 const uint32_t limit = 10000;
3563 string possible_path;
3564 string possible_name;
3567 legalized = legalize_for_path (base);
3569 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3571 for (cnt = 1; cnt <= limit; ++cnt) {
3573 vector<space_and_path>::iterator i;
3574 uint32_t existing = 0;
3576 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3578 SessionDirectory sdir((*i).path);
3580 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3581 possible_name = buf;
3583 possible_path = Glib::build_filename (sdir.midi_path(), possible_name);
3585 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3589 if (midi_source_by_path (possible_path)) {
3594 if (existing == 0) {
3599 error << string_compose(
3600 _("There are already %1 recordings for %2, which I consider too many."),
3601 limit, base) << endmsg;
3607 /* No need to "find best location" for software/app-based RAID, because
3608 MIDI is so small that we always put it in the same place.
3611 return possible_path;
3615 /** Create a new within-session audio source */
3616 boost::shared_ptr<AudioFileSource>
3617 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
3619 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
3621 if (!path.empty()) {
3622 return boost::dynamic_pointer_cast<AudioFileSource> (
3623 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3625 throw failed_constructor ();
3629 /** Create a new within-session MIDI source */
3630 boost::shared_ptr<MidiSource>
3631 Session::create_midi_source_for_session (string const & basic_name)
3633 const string path = new_midi_source_path (basic_name);
3635 if (!path.empty()) {
3636 return boost::dynamic_pointer_cast<SMFSource> (
3637 SourceFactory::createWritable (
3638 DataType::MIDI, *this, path, false, frame_rate()));
3640 throw failed_constructor ();
3644 /** Create a new within-session MIDI source */
3645 boost::shared_ptr<MidiSource>
3646 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3648 /* the caller passes in the track the source will be used in,
3649 so that we can keep the numbering sane.
3651 Rationale: a track with the name "Foo" that has had N
3652 captures carried out so far will ALREADY have a write source
3653 named "Foo-N+1.mid" waiting to be used for the next capture.
3655 If we call new_midi_source_name() we will get "Foo-N+2". But
3656 there is no region corresponding to "Foo-N+1", so when
3657 "Foo-N+2" appears in the track, the gap presents the user
3658 with odd behaviour - why did it skip past Foo-N+1?
3660 We could explain this to the user in some odd way, but
3661 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3664 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3667 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3669 std::string name = track->steal_write_source_name ();
3672 return boost::shared_ptr<MidiSource>();
3675 const string path = new_midi_source_path (name);
3677 return boost::dynamic_pointer_cast<SMFSource> (
3678 SourceFactory::createWritable (
3679 DataType::MIDI, *this, path, false, frame_rate()));
3684 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3686 if (playlist->hidden()) {
3690 playlists->add (playlist);
3693 playlist->release();
3700 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3702 if (_state_of_the_state & Deletion) {
3706 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3712 playlists->remove (playlist);
3718 Session::set_audition (boost::shared_ptr<Region> r)
3720 pending_audition_region = r;
3721 add_post_transport_work (PostTransportAudition);
3722 _butler->schedule_transport_work ();
3726 Session::audition_playlist ()
3728 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3729 ev->region.reset ();
3734 Session::non_realtime_set_audition ()
3736 assert (pending_audition_region);
3737 auditioner->audition_region (pending_audition_region);
3738 pending_audition_region.reset ();
3739 AuditionActive (true); /* EMIT SIGNAL */
3743 Session::audition_region (boost::shared_ptr<Region> r)
3745 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3751 Session::cancel_audition ()
3756 if (auditioner->auditioning()) {
3757 auditioner->cancel_audition ();
3758 AuditionActive (false); /* EMIT SIGNAL */
3763 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3765 if (a->is_monitor()) {
3768 if (b->is_monitor()) {
3771 return a->order_key () < b->order_key ();
3775 Session::is_auditioning () const
3777 /* can be called before we have an auditioner object */
3779 return auditioner->auditioning();
3786 Session::graph_reordered ()
3788 /* don't do this stuff if we are setting up connections
3789 from a set_state() call or creating new tracks. Ditto for deletion.
3792 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3796 /* every track/bus asked for this to be handled but it was deferred because
3797 we were connecting. do it now.
3800 request_input_change_handling ();
3804 /* force all diskstreams to update their capture offset values to
3805 reflect any changes in latencies within the graph.
3808 boost::shared_ptr<RouteList> rl = routes.reader ();
3809 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3810 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3812 tr->set_capture_offset ();
3817 /** @return Number of frames that there is disk space available to write,
3820 boost::optional<framecnt_t>
3821 Session::available_capture_duration ()
3823 Glib::Threads::Mutex::Lock lm (space_lock);
3825 if (_total_free_4k_blocks_uncertain) {
3826 return boost::optional<framecnt_t> ();
3829 float sample_bytes_on_disk = 4.0; // keep gcc happy
3831 switch (config.get_native_file_data_format()) {
3833 sample_bytes_on_disk = 4.0;
3837 sample_bytes_on_disk = 3.0;
3841 sample_bytes_on_disk = 2.0;
3845 /* impossible, but keep some gcc versions happy */
3846 fatal << string_compose (_("programming error: %1"),
3847 X_("illegal native file data format"))
3852 double scale = 4096.0 / sample_bytes_on_disk;
3854 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3855 return max_framecnt;
3858 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3862 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3865 RCUWriter<BundleList> writer (_bundles);
3866 boost::shared_ptr<BundleList> b = writer.get_copy ();
3867 b->push_back (bundle);
3870 BundleAdded (bundle); /* EMIT SIGNAL */
3876 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3878 bool removed = false;
3881 RCUWriter<BundleList> writer (_bundles);
3882 boost::shared_ptr<BundleList> b = writer.get_copy ();
3883 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3885 if (i != b->end()) {
3892 BundleRemoved (bundle); /* EMIT SIGNAL */
3898 boost::shared_ptr<Bundle>
3899 Session::bundle_by_name (string name) const
3901 boost::shared_ptr<BundleList> b = _bundles.reader ();
3903 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3904 if ((*i)->name() == name) {
3909 return boost::shared_ptr<Bundle> ();
3913 Session::tempo_map_changed (const PropertyChange&)
3917 playlists->update_after_tempo_map_change ();
3919 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3925 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3927 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3928 (*i)->recompute_frames_from_bbt ();
3932 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3933 * the given count with the current block size.
3936 Session::ensure_buffers (ChanCount howmany)
3938 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
3942 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3944 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3945 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3950 Session::next_insert_id ()
3952 /* this doesn't really loop forever. just think about it */
3955 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3956 if (!insert_bitset[n]) {
3957 insert_bitset[n] = true;
3963 /* none available, so resize and try again */
3965 insert_bitset.resize (insert_bitset.size() + 16, false);
3970 Session::next_send_id ()
3972 /* this doesn't really loop forever. just think about it */
3975 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3976 if (!send_bitset[n]) {
3977 send_bitset[n] = true;
3983 /* none available, so resize and try again */
3985 send_bitset.resize (send_bitset.size() + 16, false);
3990 Session::next_aux_send_id ()
3992 /* this doesn't really loop forever. just think about it */
3995 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
3996 if (!aux_send_bitset[n]) {
3997 aux_send_bitset[n] = true;
4003 /* none available, so resize and try again */
4005 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
4010 Session::next_return_id ()
4012 /* this doesn't really loop forever. just think about it */
4015 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
4016 if (!return_bitset[n]) {
4017 return_bitset[n] = true;
4023 /* none available, so resize and try again */
4025 return_bitset.resize (return_bitset.size() + 16, false);
4030 Session::mark_send_id (uint32_t id)
4032 if (id >= send_bitset.size()) {
4033 send_bitset.resize (id+16, false);
4035 if (send_bitset[id]) {
4036 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4038 send_bitset[id] = true;
4042 Session::mark_aux_send_id (uint32_t id)
4044 if (id >= aux_send_bitset.size()) {
4045 aux_send_bitset.resize (id+16, false);
4047 if (aux_send_bitset[id]) {
4048 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4050 aux_send_bitset[id] = true;
4054 Session::mark_return_id (uint32_t id)
4056 if (id >= return_bitset.size()) {
4057 return_bitset.resize (id+16, false);
4059 if (return_bitset[id]) {
4060 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4062 return_bitset[id] = true;
4066 Session::mark_insert_id (uint32_t id)
4068 if (id >= insert_bitset.size()) {
4069 insert_bitset.resize (id+16, false);
4071 if (insert_bitset[id]) {
4072 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4074 insert_bitset[id] = true;
4078 Session::unmark_send_id (uint32_t id)
4080 if (id < send_bitset.size()) {
4081 send_bitset[id] = false;
4086 Session::unmark_aux_send_id (uint32_t id)
4088 if (id < aux_send_bitset.size()) {
4089 aux_send_bitset[id] = false;
4094 Session::unmark_return_id (uint32_t id)
4096 if (id < return_bitset.size()) {
4097 return_bitset[id] = false;
4102 Session::unmark_insert_id (uint32_t id)
4104 if (id < insert_bitset.size()) {
4105 insert_bitset[id] = false;
4110 Session::reset_native_file_format ()
4112 boost::shared_ptr<RouteList> rl = routes.reader ();
4113 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4114 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4116 /* don't save state as we do this, there's no point
4119 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4120 tr->reset_write_sources (false);
4121 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4127 Session::route_name_unique (string n) const
4129 boost::shared_ptr<RouteList> r = routes.reader ();
4131 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4132 if ((*i)->name() == n) {
4141 Session::route_name_internal (string n) const
4143 if (auditioner && auditioner->name() == n) {
4147 if (_click_io && _click_io->name() == n) {
4155 Session::freeze_all (InterThreadInfo& itt)
4157 boost::shared_ptr<RouteList> r = routes.reader ();
4159 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4161 boost::shared_ptr<Track> t;
4163 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4164 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4174 boost::shared_ptr<Region>
4175 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4176 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4177 InterThreadInfo& itt,
4178 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4179 bool for_export, bool for_freeze)
4181 boost::shared_ptr<Region> result;
4182 boost::shared_ptr<Playlist> playlist;
4183 boost::shared_ptr<AudioFileSource> fsource;
4184 ChanCount diskstream_channels (track.n_channels());
4185 framepos_t position;
4186 framecnt_t this_chunk;
4188 framepos_t latency_skip;
4190 framepos_t len = end - start;
4191 bool need_block_size_reset = false;
4192 ChanCount const max_proc = track.max_processor_streams ();
4193 string legal_playlist_name;
4194 string possible_path;
4197 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4198 end, start) << endmsg;
4202 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
4203 include_endpoint, for_export, for_freeze);
4205 if (diskstream_channels.n_audio() < 1) {
4206 error << _("Cannot write a range with no audio.") << endmsg;
4210 // block all process callback handling
4212 block_processing ();
4215 // synchronize with AudioEngine::process_callback()
4216 // make sure processing is not currently running
4217 // and processing_blocked() is honored before
4218 // acquiring thread buffers
4219 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4222 _bounce_processing_active = true;
4224 /* call tree *MUST* hold route_lock */
4226 if ((playlist = track.playlist()) == 0) {
4230 legal_playlist_name = legalize_for_path (playlist->name());
4232 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4234 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
4235 string path = new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true);
4242 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4243 SourceFactory::createWritable (DataType::AUDIO, *this, path, false, frame_rate()));
4246 catch (failed_constructor& err) {
4247 error << string_compose (_("cannot create new audio file \"%1\" for %2"), path, track.name()) << endmsg;
4251 srcs.push_back (fsource);
4254 /* tell redirects that care that we are about to use a much larger
4255 * blocksize. this will flush all plugins too, so that they are ready
4256 * to be used for this process.
4259 need_block_size_reset = true;
4260 track.set_block_size (bounce_chunk_size);
4261 _engine.main_thread()->get_buffers ();
4265 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4267 /* create a set of reasonably-sized buffers */
4268 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4269 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4271 buffers.set_count (max_proc);
4273 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4274 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4276 afs->prepare_for_peakfile_writes ();
4279 while (to_do && !itt.cancel) {
4281 this_chunk = min (to_do, bounce_chunk_size);
4283 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
4287 start += this_chunk;
4288 to_do -= this_chunk;
4289 itt.progress = (float) (1.0 - ((double) to_do / len));
4291 if (latency_skip >= bounce_chunk_size) {
4292 latency_skip -= bounce_chunk_size;
4296 const framecnt_t current_chunk = this_chunk - latency_skip;
4299 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4300 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4303 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4311 /* post-roll, pick up delayed processor output */
4312 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4314 while (latency_skip && !itt.cancel) {
4315 this_chunk = min (latency_skip, bounce_chunk_size);
4316 latency_skip -= this_chunk;
4318 buffers.silence (this_chunk, 0);
4319 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
4322 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4323 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4326 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4338 xnow = localtime (&now);
4340 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4341 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4344 afs->update_header (position, *xnow, now);
4345 afs->flush_header ();
4349 /* construct a region to represent the bounced material */
4353 plist.add (Properties::start, 0);
4354 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4355 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4357 result = RegionFactory::create (srcs, plist);
4363 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4364 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4367 afs->mark_for_remove ();
4370 (*src)->drop_references ();
4374 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4375 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4378 afs->done_with_peakfile_writes ();
4382 _bounce_processing_active = false;
4384 if (need_block_size_reset) {
4385 _engine.main_thread()->drop_buffers ();
4386 track.set_block_size (get_block_size());
4389 unblock_processing ();
4395 Session::gain_automation_buffer() const
4397 return ProcessThread::gain_automation_buffer ();
4401 Session::send_gain_automation_buffer() const
4403 return ProcessThread::send_gain_automation_buffer ();
4407 Session::pan_automation_buffer() const
4409 return ProcessThread::pan_automation_buffer ();
4413 Session::get_silent_buffers (ChanCount count)
4415 return ProcessThread::get_silent_buffers (count);
4419 Session::get_scratch_buffers (ChanCount count, bool silence)
4421 return ProcessThread::get_scratch_buffers (count, silence);
4425 Session::get_route_buffers (ChanCount count, bool silence)
4427 return ProcessThread::get_route_buffers (count, silence);
4432 Session::get_mix_buffers (ChanCount count)
4434 return ProcessThread::get_mix_buffers (count);
4438 Session::ntracks () const
4441 boost::shared_ptr<RouteList> r = routes.reader ();
4443 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4444 if (boost::dynamic_pointer_cast<Track> (*i)) {
4453 Session::nbusses () const
4456 boost::shared_ptr<RouteList> r = routes.reader ();
4458 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4459 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4468 Session::add_automation_list(AutomationList *al)
4470 automation_lists[al->id()] = al;
4473 /** @return true if there is at least one record-enabled track, otherwise false */
4475 Session::have_rec_enabled_track () const
4477 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4480 /** Update the state of our rec-enabled tracks flag */
4482 Session::update_have_rec_enabled_track ()
4484 boost::shared_ptr<RouteList> rl = routes.reader ();
4485 RouteList::iterator i = rl->begin();
4486 while (i != rl->end ()) {
4488 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4489 if (tr && tr->record_enabled ()) {
4496 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4498 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4500 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4501 RecordStateChanged (); /* EMIT SIGNAL */
4506 Session::listen_position_changed ()
4508 boost::shared_ptr<RouteList> r = routes.reader ();
4510 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4511 (*i)->listen_position_changed ();
4516 Session::solo_control_mode_changed ()
4518 /* cancel all solo or all listen when solo control mode changes */
4521 set_solo (get_routes(), false);
4522 } else if (listening()) {
4523 set_listen (get_routes(), false);
4527 /** Called when a property of one of our route groups changes */
4529 Session::route_group_property_changed (RouteGroup* rg)
4531 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4534 /** Called when a route is added to one of our route groups */
4536 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4538 RouteAddedToRouteGroup (rg, r);
4541 /** Called when a route is removed from one of our route groups */
4543 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4545 RouteRemovedFromRouteGroup (rg, r);
4548 boost::shared_ptr<RouteList>
4549 Session::get_routes_with_regions_at (framepos_t const p) const
4551 boost::shared_ptr<RouteList> r = routes.reader ();
4552 boost::shared_ptr<RouteList> rl (new RouteList);
4554 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4555 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4560 boost::shared_ptr<Playlist> pl = tr->playlist ();
4565 if (pl->has_region_at (p)) {
4574 Session::goto_end ()
4576 if (_session_range_location) {
4577 request_locate (_session_range_location->end(), false);
4579 request_locate (0, false);
4584 Session::goto_start ()
4586 if (_session_range_location) {
4587 request_locate (_session_range_location->start(), false);
4589 request_locate (0, false);
4594 Session::current_start_frame () const
4596 return _session_range_location ? _session_range_location->start() : 0;
4600 Session::current_end_frame () const
4602 return _session_range_location ? _session_range_location->end() : 0;
4606 Session::add_session_range_location (framepos_t start, framepos_t end)
4608 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4609 _locations->add (_session_range_location);
4613 Session::step_edit_status_change (bool yn)
4619 send = (_step_editors == 0);
4624 send = (_step_editors == 1);
4627 if (_step_editors > 0) {
4633 StepEditStatusChange (val);
4639 Session::start_time_changed (framepos_t old)
4641 /* Update the auto loop range to match the session range
4642 (unless the auto loop range has been changed by the user)
4645 Location* s = _locations->session_range_location ();
4650 Location* l = _locations->auto_loop_location ();
4652 if (l && l->start() == old) {
4653 l->set_start (s->start(), true);
4658 Session::end_time_changed (framepos_t old)
4660 /* Update the auto loop range to match the session range
4661 (unless the auto loop range has been changed by the user)
4664 Location* s = _locations->session_range_location ();
4669 Location* l = _locations->auto_loop_location ();
4671 if (l && l->end() == old) {
4672 l->set_end (s->end(), true);
4676 std::vector<std::string>
4677 Session::source_search_path (DataType type) const
4681 if (session_dirs.size() == 1) {
4683 case DataType::AUDIO:
4684 sp.push_back (_session_dir->sound_path());
4686 case DataType::MIDI:
4687 sp.push_back (_session_dir->midi_path());
4691 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4692 SessionDirectory sdir (i->path);
4694 case DataType::AUDIO:
4695 sp.push_back (sdir.sound_path());
4697 case DataType::MIDI:
4698 sp.push_back (sdir.midi_path());
4704 if (type == DataType::AUDIO) {
4705 const string sound_path_2X = _session_dir->sound_path_2X();
4706 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4707 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
4708 sp.push_back (sound_path_2X);
4713 // now check the explicit (possibly user-specified) search path
4716 case DataType::AUDIO:
4717 sp += Searchpath(config.get_audio_search_path ());
4719 case DataType::MIDI:
4720 sp += Searchpath(config.get_midi_search_path ());
4728 Session::ensure_search_path_includes (const string& path, DataType type)
4737 case DataType::AUDIO:
4738 sp += Searchpath(config.get_audio_search_path ());
4740 case DataType::MIDI:
4741 sp += Searchpath (config.get_midi_search_path ());
4745 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
4746 /* No need to add this new directory if it has the same inode as
4747 an existing one; checking inode rather than name prevents duplicated
4748 directories when we are using symlinks.
4750 On Windows, I think we could just do if (*i == path) here.
4752 if (PBD::equivalent_paths (*i, path)) {
4760 case DataType::AUDIO:
4761 config.set_audio_search_path (sp.to_string());
4763 case DataType::MIDI:
4764 config.set_midi_search_path (sp.to_string());
4769 boost::shared_ptr<Speakers>
4770 Session::get_speakers()
4776 Session::unknown_processors () const
4780 boost::shared_ptr<RouteList> r = routes.reader ();
4781 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4782 list<string> t = (*i)->unknown_processors ();
4783 copy (t.begin(), t.end(), back_inserter (p));
4793 Session::update_latency (bool playback)
4795 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4797 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4801 boost::shared_ptr<RouteList> r = routes.reader ();
4802 framecnt_t max_latency = 0;
4805 /* reverse the list so that we work backwards from the last route to run to the first */
4806 RouteList* rl = routes.reader().get();
4807 r.reset (new RouteList (*rl));
4808 reverse (r->begin(), r->end());
4811 /* compute actual latency values for the given direction and store them all in per-port
4812 structures. this will also publish the same values (to JACK) so that computation of latency
4813 for routes can consistently use public latency values.
4816 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4817 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4820 /* because we latency compensate playback, our published playback latencies should
4821 be the same for all output ports - all material played back by ardour has
4822 the same latency, whether its caused by plugins or by latency compensation. since
4823 these may differ from the values computed above, reset all playback port latencies
4827 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4829 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4830 (*i)->set_public_port_latencies (max_latency, playback);
4835 post_playback_latency ();
4839 post_capture_latency ();
4842 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4846 Session::post_playback_latency ()
4848 set_worst_playback_latency ();
4850 boost::shared_ptr<RouteList> r = routes.reader ();
4852 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4853 if (!(*i)->is_auditioner() && ((*i)->active())) {
4854 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4858 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4859 (*i)->set_latency_compensation (_worst_track_latency);
4864 Session::post_capture_latency ()
4866 set_worst_capture_latency ();
4868 /* reflect any changes in capture latencies into capture offsets
4871 boost::shared_ptr<RouteList> rl = routes.reader();
4872 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4873 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4875 tr->set_capture_offset ();
4881 Session::initialize_latencies ()
4884 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4885 update_latency (false);
4886 update_latency (true);
4889 set_worst_io_latencies ();
4893 Session::set_worst_io_latencies ()
4895 set_worst_playback_latency ();
4896 set_worst_capture_latency ();
4900 Session::set_worst_playback_latency ()
4902 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4906 _worst_output_latency = 0;
4908 if (!_engine.connected()) {
4912 boost::shared_ptr<RouteList> r = routes.reader ();
4914 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4915 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4918 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4922 Session::set_worst_capture_latency ()
4924 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4928 _worst_input_latency = 0;
4930 if (!_engine.connected()) {
4934 boost::shared_ptr<RouteList> r = routes.reader ();
4936 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4937 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4940 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4944 Session::update_latency_compensation (bool force_whole_graph)
4946 bool some_track_latency_changed = false;
4948 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4952 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4954 _worst_track_latency = 0;
4956 boost::shared_ptr<RouteList> r = routes.reader ();
4958 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4959 if (!(*i)->is_auditioner() && ((*i)->active())) {
4961 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4962 some_track_latency_changed = true;
4964 _worst_track_latency = max (tl, _worst_track_latency);
4968 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4969 (some_track_latency_changed ? "yes" : "no")));
4971 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4973 if (some_track_latency_changed || force_whole_graph) {
4974 _engine.update_latencies ();
4978 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4979 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4983 tr->set_capture_offset ();
4988 Session::session_name_is_legal (const string& path)
4990 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
4992 for (int i = 0; illegal_chars[i]; ++i) {
4993 if (path.find (illegal_chars[i]) != string::npos) {
4994 return illegal_chars[i];
5002 Session::next_control_id () const
5006 /* the monitor bus remote ID is in a different
5007 * "namespace" than regular routes. its existence doesn't
5008 * affect normal (low) numbered routes.
5015 return nroutes() - subtract;
5019 Session::notify_remote_id_change ()
5021 if (deletion_in_progress()) {
5025 switch (Config->get_remote_model()) {
5027 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
5035 Session::sync_order_keys ()
5037 if (deletion_in_progress()) {
5041 /* tell everyone that something has happened to the sort keys
5042 and let them sync up with the change(s)
5043 this will give objects that manage the sort order keys the
5044 opportunity to keep them in sync if they wish to.
5047 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5049 reassign_track_numbers();
5051 Route::SyncOrderKeys (); /* EMIT SIGNAL */
5053 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5057 Session::operation_in_progress (GQuark op) const
5059 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5062 boost::shared_ptr<Port>
5063 Session::ltc_input_port () const
5065 return _ltc_input->nth (0);
5068 boost::shared_ptr<Port>
5069 Session::ltc_output_port () const
5071 return _ltc_output->nth (0);
5075 Session::reconnect_ltc_input ()
5079 string src = Config->get_ltc_source_port();
5081 _ltc_input->disconnect (this);
5083 if (src != _("None") && !src.empty()) {
5084 _ltc_input->nth (0)->connect (src);
5090 Session::reconnect_ltc_output ()
5095 string src = Config->get_ltc_sink_port();
5097 _ltc_output->disconnect (this);
5099 if (src != _("None") && !src.empty()) {
5100 _ltc_output->nth (0)->connect (src);