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/basename.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/convert.h"
42 #include "pbd/convert.h"
43 #include "pbd/error.h"
44 #include "pbd/file_utils.h"
46 #include "pbd/search_path.h"
47 #include "pbd/stacktrace.h"
48 #include "pbd/stl_delete.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/filename_extensions.h"
70 #include "ardour/graph.h"
71 #include "ardour/midiport_manager.h"
72 #include "ardour/scene_changer.h"
73 #include "ardour/midi_track.h"
74 #include "ardour/midi_ui.h"
75 #include "ardour/operations.h"
76 #include "ardour/playlist.h"
77 #include "ardour/plugin.h"
78 #include "ardour/plugin_insert.h"
79 #include "ardour/process_thread.h"
80 #include "ardour/rc_configuration.h"
81 #include "ardour/recent_sessions.h"
82 #include "ardour/region.h"
83 #include "ardour/region_factory.h"
84 #include "ardour/route_graph.h"
85 #include "ardour/route_group.h"
86 #include "ardour/route_sorters.h"
87 #include "ardour/send.h"
88 #include "ardour/session.h"
89 #include "ardour/session_directory.h"
90 #include "ardour/session_playlists.h"
91 #include "ardour/smf_source.h"
92 #include "ardour/source_factory.h"
93 #include "ardour/speakers.h"
94 #include "ardour/tempo.h"
95 #include "ardour/track.h"
96 #include "ardour/user_bundle.h"
97 #include "ardour/utils.h"
99 #include "midi++/port.h"
100 #include "midi++/mmc.h"
111 using namespace ARDOUR;
114 bool Session::_disable_all_loaded_plugins = false;
116 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
117 PBD::Signal1<void,std::string> Session::Dialog;
118 PBD::Signal0<int> Session::AskAboutPendingState;
119 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
120 PBD::Signal0<void> Session::SendFeedback;
121 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
123 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
124 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
125 PBD::Signal2<void,std::string, std::string> Session::Exported;
126 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
127 PBD::Signal0<void> Session::Quit;
128 PBD::Signal0<void> Session::FeedbackDetected;
129 PBD::Signal0<void> Session::SuccessfulGraphSort;
130 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
132 const framecnt_t Session::bounce_chunk_size = 65536;
133 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
134 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
136 /** @param snapshot_name Snapshot name, without .ardour suffix */
137 Session::Session (AudioEngine &eng,
138 const string& fullpath,
139 const string& snapshot_name,
140 BusProfile* bus_profile,
142 : playlists (new SessionPlaylists)
144 , process_function (&Session::process_with_events)
145 , _bounce_processing_active (false)
146 , waiting_for_sync_offset (false)
147 , _base_frame_rate (0)
148 , _current_frame_rate (0)
149 , _nominal_frame_rate (0)
150 , transport_sub_state (0)
151 , _record_status (Disabled)
152 , _transport_frame (0)
153 , _session_range_location (0)
156 , _transport_speed (0)
157 , _default_transport_speed (1.0)
158 , _last_transport_speed (0)
159 , _target_transport_speed (0.0)
160 , auto_play_legal (false)
161 , _last_slave_transport_frame (0)
162 , maximum_output_latency (0)
163 , _requested_return_frame (-1)
164 , current_block_size (0)
165 , _worst_output_latency (0)
166 , _worst_input_latency (0)
167 , _worst_track_latency (0)
168 , _have_captured (false)
169 , _non_soloed_outs_muted (false)
171 , _solo_isolated_cnt (0)
173 , _was_seamless (Config->get_seamless_loop ())
174 , _under_nsm_control (false)
176 , delta_accumulator_cnt (0)
177 , average_slave_delta (1800) // !!! why 1800 ???
179 , have_first_delta_accumulator (false)
180 , _slave_state (Stopped)
181 , post_export_sync (false)
182 , post_export_position (0)
184 , _export_started (false)
185 , _export_rolling (false)
186 , _pre_export_mmc_enabled (false)
187 , _name (snapshot_name)
189 , _send_qf_mtc (false)
190 , _pframes_since_last_mtc (0)
191 , session_midi_feedback (0)
193 , loop_changing (false)
195 , _session_dir (new SessionDirectory (fullpath))
196 , _current_snapshot_name (snapshot_name)
198 , state_was_pending (false)
199 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
201 , _save_queued (false)
202 , _last_roll_location (0)
203 , _last_roll_or_reversal_location (0)
204 , _last_record_location (0)
205 , pending_locate_roll (false)
206 , pending_locate_frame (0)
207 , pending_locate_flush (false)
208 , pending_abort (false)
209 , pending_auto_loop (false)
210 , _butler (new Butler (*this))
211 , _post_transport_work (0)
212 , cumulative_rf_motion (0)
214 , _locations (new Locations (*this))
215 , _ignore_skips_updates (false)
216 , _rt_thread_active (false)
217 , _rt_emit_pending (false)
219 , outbound_mtc_timecode_frame (0)
220 , next_quarter_frame_to_send (-1)
221 , _frames_per_timecode_frame (0)
222 , _frames_per_hour (0)
223 , _timecode_frames_per_hour (0)
224 , last_timecode_valid (false)
225 , last_timecode_when (0)
226 , _send_timecode_update (false)
238 , ltc_timecode_offset (0)
239 , ltc_timecode_negative_offset (false)
240 , midi_control_ui (0)
242 , _all_route_group (new RouteGroup (*this, "all"))
243 , routes (new RouteList)
244 , _adding_routes_in_progress (false)
245 , destructive_index (0)
246 , _track_number_decimals(1)
247 , solo_update_disabled (false)
248 , default_fade_steepness (0)
249 , default_fade_msecs (0)
250 , _total_free_4k_blocks (0)
251 , _total_free_4k_blocks_uncertain (false)
252 , no_questions_about_missing_files (false)
255 , _bundles (new BundleList)
256 , _bundle_xml_node (0)
260 , click_emphasis_data (0)
262 , click_emphasis_length (0)
263 , _clicks_cleared (0)
264 , _play_range (false)
266 , first_file_data_format_reset (true)
267 , first_file_header_format_reset (true)
268 , have_looped (false)
269 , _have_rec_enabled_track (false)
271 , _suspend_timecode_transmission (0)
272 , _speakers (new Speakers)
274 , ignore_route_processor_changes (false)
281 pthread_mutex_init (&_rt_emit_mutex, 0);
282 pthread_cond_init (&_rt_emit_cond, 0);
284 pre_engine_init (fullpath);
287 if (ensure_engine (sr)) {
289 throw failed_constructor ();
292 if (create (mix_template, bus_profile)) {
294 throw failed_constructor ();
297 /* if a mix template was provided, then ::create() will
298 * have copied it into the session and we need to load it
299 * so that we have the state ready for ::set_state()
300 * after the engine is started.
302 * Note that we do NOT try to get the sample rate from
303 * the template at this time, though doing so would
304 * be easy if we decided this was an appropriate part
308 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
309 throw failed_constructor ();
312 /* load default session properties - if any */
317 if (load_state (_current_snapshot_name)) {
318 throw failed_constructor ();
321 /* try to get sample rate from XML state so that we
322 * can influence the SR if we set up the audio
327 const XMLProperty* prop;
328 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
329 sr = atoi (prop->value());
333 if (ensure_engine (sr)) {
335 throw failed_constructor ();
339 if (post_engine_init ()) {
341 throw failed_constructor ();
344 store_recent_sessions (_name, _path);
346 bool was_dirty = dirty();
348 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
350 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
351 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
354 DirtyChanged (); /* EMIT SIGNAL */
357 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
358 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
362 emit_thread_start ();
364 /* hook us up to the engine since we are now completely constructed */
366 BootMessage (_("Connect to engine"));
368 _engine.set_session (this);
369 _engine.reset_timebase ();
371 BootMessage (_("Session loading complete"));
384 Session::ensure_engine (uint32_t desired_sample_rate)
386 if (_engine.current_backend() == 0) {
387 /* backend is unknown ... */
388 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
389 if (r.get_value_or (-1) != 0) {
392 } else if (_engine.setup_required()) {
393 /* backend is known, but setup is needed */
394 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
395 if (r.get_value_or (-1) != 0) {
398 } else if (!_engine.running()) {
399 if (_engine.start()) {
404 /* at this point the engine should be running
407 if (!_engine.running()) {
411 return immediately_post_engine ();
416 Session::immediately_post_engine ()
418 /* Do various initializations that should take place directly after we
419 * know that the engine is running, but before we either create a
420 * session or set state for an existing one.
423 if (how_many_dsp_threads () > 1) {
424 /* For now, only create the graph if we are using >1 DSP threads, as
425 it is a bit slower than the old code with 1 thread.
427 _process_graph.reset (new Graph (*this));
430 /* every time we reconnect, recompute worst case output latencies */
432 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
434 if (synced_to_engine()) {
435 _engine.transport_stop ();
438 if (config.get_jack_time_master()) {
439 _engine.transport_locate (_transport_frame);
443 BootMessage (_("Set up LTC"));
445 BootMessage (_("Set up Click"));
447 BootMessage (_("Set up standard connections"));
451 catch (failed_constructor& err) {
455 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
457 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
465 vector<void*> debug_pointers;
467 /* if we got to here, leaving pending capture state around
471 remove_pending_capture_state ();
473 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
475 /* disconnect from any and all signals that we are connected to */
479 _engine.remove_session ();
481 /* deregister all ports - there will be no process or any other
482 * callbacks from the engine any more.
485 Port::PortDrop (); /* EMIT SIGNAL */
489 /* clear history so that no references to objects are held any more */
493 /* clear state tree so that no references to objects are held any more */
498 /* reset dynamic state version back to default */
500 Stateful::loading_state_version = 0;
502 _butler->drop_references ();
506 delete _all_route_group;
508 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
509 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
513 if (click_data != default_click) {
514 delete [] click_data;
517 if (click_emphasis_data != default_click_emphasis) {
518 delete [] click_emphasis_data;
523 /* need to remove auditioner before monitoring section
524 * otherwise it is re-connected */
527 /* drop references to routes held by the monitoring section
528 * specifically _monitor_out aux/listen references */
529 remove_monitor_section();
531 /* clear out any pending dead wood from RCU managed objects */
536 AudioDiskstream::free_working_buffers();
538 /* tell everyone who is still standing that we're about to die */
541 /* tell everyone to drop references and delete objects as we go */
543 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
544 RegionFactory::delete_all_regions ();
546 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
548 /* reset these three references to special routes before we do the usual route delete thing */
550 _master_out.reset ();
551 _monitor_out.reset ();
554 RCUWriter<RouteList> writer (routes);
555 boost::shared_ptr<RouteList> r = writer.get_copy ();
557 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
558 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
559 (*i)->drop_references ();
563 /* writer goes out of scope and updates master */
568 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
569 Glib::Threads::Mutex::Lock lm (source_lock);
570 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
571 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
572 i->second->drop_references ();
578 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
581 emit_thread_terminate ();
583 pthread_cond_destroy (&_rt_emit_cond);
584 pthread_mutex_destroy (&_rt_emit_mutex);
586 delete _scene_changer; _scene_changer = 0;
587 delete midi_control_ui; midi_control_ui = 0;
589 delete _mmc; _mmc = 0;
590 delete _midi_ports; _midi_ports = 0;
591 delete _locations; _locations = 0;
595 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
597 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
598 boost_debug_list_ptrs ();
603 Session::setup_ltc ()
607 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
608 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
610 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
611 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
614 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
615 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
617 reconnect_ltc_input ();
620 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
621 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
624 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
625 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
627 reconnect_ltc_output ();
630 /* fix up names of LTC ports because we don't want the normal
631 * IO style of NAME/TYPE-{in,out}N
634 _ltc_input->nth (0)->set_name (X_("LTC-in"));
635 _ltc_output->nth (0)->set_name (X_("LTC-out"));
639 Session::setup_click ()
642 _click_io.reset (new ClickIO (*this, X_("Click")));
643 _click_gain.reset (new Amp (*this));
644 _click_gain->activate ();
646 setup_click_state (state_tree->root());
648 setup_click_state (0);
653 Session::setup_click_state (const XMLNode* node)
655 const XMLNode* child = 0;
657 if (node && (child = find_named_node (*node, "Click")) != 0) {
659 /* existing state for Click */
662 if (Stateful::loading_state_version < 3000) {
663 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
665 const XMLNodeList& children (child->children());
666 XMLNodeList::const_iterator i = children.begin();
667 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
669 if (i != children.end()) {
670 c = _click_gain->set_state (**i, Stateful::loading_state_version);
676 _clicking = Config->get_clicking ();
680 error << _("could not setup Click I/O") << endmsg;
687 /* default state for Click: dual-mono to first 2 physical outputs */
690 _engine.get_physical_outputs (DataType::AUDIO, outs);
692 for (uint32_t physport = 0; physport < 2; ++physport) {
693 if (outs.size() > physport) {
694 if (_click_io->add_port (outs[physport], this)) {
695 // relax, even though its an error
700 if (_click_io->n_ports () > ChanCount::ZERO) {
701 _clicking = Config->get_clicking ();
707 Session::setup_bundles ()
711 RCUWriter<BundleList> writer (_bundles);
712 boost::shared_ptr<BundleList> b = writer.get_copy ();
713 for (BundleList::iterator i = b->begin(); i != b->end();) {
714 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
722 vector<string> inputs[DataType::num_types];
723 vector<string> outputs[DataType::num_types];
724 for (uint32_t i = 0; i < DataType::num_types; ++i) {
725 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
726 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
729 /* Create a set of Bundle objects that map
730 to the physical I/O currently available. We create both
731 mono and stereo bundles, so that the common cases of mono
732 and stereo tracks get bundles to put in their mixer strip
733 in / out menus. There may be a nicer way of achieving that;
734 it doesn't really scale that well to higher channel counts
737 /* mono output bundles */
739 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
741 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
743 snprintf (buf, sizeof (buf), _("out %s"), pn.substr(0,12).c_str());
745 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
748 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
749 c->add_channel (_("mono"), DataType::AUDIO);
750 c->set_port (0, outputs[DataType::AUDIO][np]);
752 add_bundle (c, false);
755 /* stereo output bundles */
757 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
758 if (np + 1 < outputs[DataType::AUDIO].size()) {
760 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
761 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
762 c->add_channel (_("L"), DataType::AUDIO);
763 c->set_port (0, outputs[DataType::AUDIO][np]);
764 c->add_channel (_("R"), DataType::AUDIO);
765 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
767 add_bundle (c, false);
771 /* mono input bundles */
773 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
775 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
777 snprintf (buf, sizeof (buf), _("in %s"), pn.substr(0,12).c_str());
779 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
782 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
783 c->add_channel (_("mono"), DataType::AUDIO);
784 c->set_port (0, inputs[DataType::AUDIO][np]);
786 add_bundle (c, false);
789 /* stereo input bundles */
791 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
792 if (np + 1 < inputs[DataType::AUDIO].size()) {
794 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
796 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
797 c->add_channel (_("L"), DataType::AUDIO);
798 c->set_port (0, inputs[DataType::AUDIO][np]);
799 c->add_channel (_("R"), DataType::AUDIO);
800 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
802 add_bundle (c, false);
806 /* MIDI input bundles */
808 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
809 string n = inputs[DataType::MIDI][np];
810 std::string pn = _engine.get_pretty_name_by_name (n);
814 boost::erase_first (n, X_("alsa_pcm:"));
816 boost::shared_ptr<Bundle> c (new Bundle (n, false));
817 c->add_channel ("", DataType::MIDI);
818 c->set_port (0, inputs[DataType::MIDI][np]);
819 add_bundle (c, false);
822 /* MIDI output bundles */
824 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
825 string n = outputs[DataType::MIDI][np];
826 std::string pn = _engine.get_pretty_name_by_name (n);
830 boost::erase_first (n, X_("alsa_pcm:"));
832 boost::shared_ptr<Bundle> c (new Bundle (n, true));
833 c->add_channel ("", DataType::MIDI);
834 c->set_port (0, outputs[DataType::MIDI][np]);
835 add_bundle (c, false);
838 // we trust the backend to only calls us if there's a change
839 BundleAddedOrRemoved (); /* EMIT SIGNAL */
843 Session::auto_connect_master_bus ()
845 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
849 /* if requested auto-connect the outputs to the first N physical ports.
852 uint32_t limit = _master_out->n_outputs().n_total();
853 vector<string> outputs[DataType::num_types];
855 for (uint32_t i = 0; i < DataType::num_types; ++i) {
856 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
859 for (uint32_t n = 0; n < limit; ++n) {
860 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
862 if (outputs[p->type()].size() > n) {
863 connect_to = outputs[p->type()][n];
866 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
867 if (_master_out->output()->connect (p, connect_to, this)) {
868 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
877 Session::remove_monitor_section ()
883 /* force reversion to Solo-In-Place */
884 Config->set_solo_control_is_listen_control (false);
886 /* if we are auditioning, cancel it ... this is a workaround
887 to a problem (auditioning does not execute the process graph,
888 which is needed to remove routes when using >1 core for processing)
893 /* Hold process lock while doing this so that we don't hear bits and
894 * pieces of audio as we work on each route.
897 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
899 /* Connect tracks to monitor section. Note that in an
900 existing session, the internal sends will already exist, but we want the
901 routes to notice that they connect to the control out specifically.
905 boost::shared_ptr<RouteList> r = routes.reader ();
906 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
908 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
910 if ((*x)->is_monitor()) {
912 } else if ((*x)->is_master()) {
915 (*x)->remove_aux_or_listen (_monitor_out);
920 remove_route (_monitor_out);
921 auto_connect_master_bus ();
924 auditioner->connect ();
929 Session::add_monitor_section ()
933 if (_monitor_out || !_master_out) {
937 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
943 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
944 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
947 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
948 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
949 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
953 add_routes (rl, false, false, false);
955 assert (_monitor_out);
957 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
958 are undefined, at best.
961 uint32_t limit = _monitor_out->n_inputs().n_audio();
965 /* connect the inputs to the master bus outputs. this
966 * represents a separate data feed from the internal sends from
967 * each route. as of jan 2011, it allows the monitor section to
968 * conditionally ignore either the internal sends or the normal
969 * input feed, but we should really find a better way to do
973 _master_out->output()->disconnect (this);
975 for (uint32_t n = 0; n < limit; ++n) {
976 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
977 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
980 string connect_to = o->name();
981 if (_monitor_out->input()->connect (p, connect_to, this)) {
982 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
990 /* if monitor section is not connected, connect it to physical outs
993 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
995 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
997 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1000 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1002 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1003 Config->get_monitor_bus_preferred_bundle())
1009 /* Monitor bus is audio only */
1011 vector<string> outputs[DataType::num_types];
1013 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1014 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1017 uint32_t mod = outputs[DataType::AUDIO].size();
1018 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1022 for (uint32_t n = 0; n < limit; ++n) {
1024 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1026 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1027 connect_to = outputs[DataType::AUDIO][n % mod];
1030 if (!connect_to.empty()) {
1031 if (_monitor_out->output()->connect (p, connect_to, this)) {
1032 error << string_compose (
1033 _("cannot connect control output %1 to %2"),
1044 /* Hold process lock while doing this so that we don't hear bits and
1045 * pieces of audio as we work on each route.
1048 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1050 /* Connect tracks to monitor section. Note that in an
1051 existing session, the internal sends will already exist, but we want the
1052 routes to notice that they connect to the control out specifically.
1056 boost::shared_ptr<RouteList> rls = routes.reader ();
1058 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1060 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1062 if ((*x)->is_monitor()) {
1064 } else if ((*x)->is_master()) {
1067 (*x)->enable_monitor_send ();
1072 auditioner->connect ();
1077 Session::reset_monitor_section ()
1079 /* Process lock should be held by the caller.*/
1081 if (!_monitor_out) {
1085 uint32_t limit = _master_out->n_outputs().n_audio();
1087 /* connect the inputs to the master bus outputs. this
1088 * represents a separate data feed from the internal sends from
1089 * each route. as of jan 2011, it allows the monitor section to
1090 * conditionally ignore either the internal sends or the normal
1091 * input feed, but we should really find a better way to do
1095 _master_out->output()->disconnect (this);
1096 _monitor_out->output()->disconnect (this);
1098 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1099 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1101 for (uint32_t n = 0; n < limit; ++n) {
1102 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1103 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1106 string connect_to = o->name();
1107 if (_monitor_out->input()->connect (p, connect_to, this)) {
1108 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1115 /* connect monitor section to physical outs
1118 if (Config->get_auto_connect_standard_busses()) {
1120 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1122 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1125 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1127 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1128 Config->get_monitor_bus_preferred_bundle())
1134 /* Monitor bus is audio only */
1136 vector<string> outputs[DataType::num_types];
1138 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1139 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1142 uint32_t mod = outputs[DataType::AUDIO].size();
1143 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1147 for (uint32_t n = 0; n < limit; ++n) {
1149 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1151 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1152 connect_to = outputs[DataType::AUDIO][n % mod];
1155 if (!connect_to.empty()) {
1156 if (_monitor_out->output()->connect (p, connect_to, this)) {
1157 error << string_compose (
1158 _("cannot connect control output %1 to %2"),
1169 /* Connect tracks to monitor section. Note that in an
1170 existing session, the internal sends will already exist, but we want the
1171 routes to notice that they connect to the control out specifically.
1175 boost::shared_ptr<RouteList> rls = routes.reader ();
1177 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1179 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1181 if ((*x)->is_monitor()) {
1183 } else if ((*x)->is_master()) {
1186 (*x)->enable_monitor_send ();
1192 Session::hookup_io ()
1194 /* stop graph reordering notifications from
1195 causing resorts, etc.
1198 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1202 /* we delay creating the auditioner till now because
1203 it makes its own connections to ports.
1207 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1209 throw failed_constructor ();
1211 a->use_new_diskstream ();
1215 catch (failed_constructor& err) {
1216 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1220 /* load bundles, which we may have postponed earlier on */
1221 if (_bundle_xml_node) {
1222 load_bundles (*_bundle_xml_node);
1223 delete _bundle_xml_node;
1226 /* Tell all IO objects to connect themselves together */
1228 IO::enable_connecting ();
1230 /* Now tell all "floating" ports to connect to whatever
1231 they should be connected to.
1234 AudioEngine::instance()->reconnect_ports ();
1236 /* Anyone who cares about input state, wake up and do something */
1238 IOConnectionsComplete (); /* EMIT SIGNAL */
1240 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1242 /* now handle the whole enchilada as if it was one
1243 graph reorder event.
1248 /* update the full solo state, which can't be
1249 correctly determined on a per-route basis, but
1250 needs the global overview that only the session
1254 update_route_solo_state ();
1258 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1260 boost::shared_ptr<Track> track = wp.lock ();
1265 boost::shared_ptr<Playlist> playlist;
1267 if ((playlist = track->playlist()) != 0) {
1268 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1269 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1270 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1275 Session::record_enabling_legal () const
1277 /* this used to be in here, but survey says.... we don't need to restrict it */
1278 // if (record_status() == Recording) {
1282 if (Config->get_all_safe()) {
1289 Session::set_track_monitor_input_status (bool yn)
1291 boost::shared_ptr<RouteList> rl = routes.reader ();
1292 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1293 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1294 if (tr && tr->record_enabled ()) {
1295 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1296 tr->request_input_monitoring (yn);
1302 Session::auto_punch_start_changed (Location* location)
1304 replace_event (SessionEvent::PunchIn, location->start());
1306 if (get_record_enabled() && config.get_punch_in()) {
1307 /* capture start has been changed, so save new pending state */
1308 save_state ("", true);
1313 Session::auto_punch_end_changed (Location* location)
1315 framepos_t when_to_stop = location->end();
1316 // when_to_stop += _worst_output_latency + _worst_input_latency;
1317 replace_event (SessionEvent::PunchOut, when_to_stop);
1321 Session::auto_punch_changed (Location* location)
1323 framepos_t when_to_stop = location->end();
1325 replace_event (SessionEvent::PunchIn, location->start());
1326 //when_to_stop += _worst_output_latency + _worst_input_latency;
1327 replace_event (SessionEvent::PunchOut, when_to_stop);
1330 /** @param loc A loop location.
1331 * @param pos Filled in with the start time of the required fade-out (in session frames).
1332 * @param length Filled in with the length of the required fade-out.
1335 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1337 pos = max (loc->start(), loc->end() - 64);
1338 length = loc->end() - pos;
1342 Session::auto_loop_changed (Location* location)
1344 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1347 auto_loop_declick_range (location, dcp, dcl);
1348 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1350 if (transport_rolling() && play_loop) {
1353 // if (_transport_frame > location->end()) {
1355 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1356 // relocate to beginning of loop
1357 clear_events (SessionEvent::LocateRoll);
1359 request_locate (location->start(), true);
1362 else if (Config->get_seamless_loop() && !loop_changing) {
1364 // schedule a locate-roll to refill the diskstreams at the
1365 // previous loop end
1366 loop_changing = true;
1368 if (location->end() > last_loopend) {
1369 clear_events (SessionEvent::LocateRoll);
1370 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1377 last_loopend = location->end();
1382 Session::set_auto_punch_location (Location* location)
1386 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1387 punch_connections.drop_connections();
1388 existing->set_auto_punch (false, this);
1389 remove_event (existing->start(), SessionEvent::PunchIn);
1390 clear_events (SessionEvent::PunchOut);
1391 auto_punch_location_changed (0);
1396 if (location == 0) {
1400 if (location->end() <= location->start()) {
1401 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1405 punch_connections.drop_connections ();
1407 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1408 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1409 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1411 location->set_auto_punch (true, this);
1413 auto_punch_changed (location);
1415 auto_punch_location_changed (location);
1419 Session::set_session_extents (framepos_t start, framepos_t end)
1422 if ((existing = _locations->session_range_location()) == 0) {
1423 //if there is no existing session, we need to make a new session location (should never happen)
1424 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1428 error << _("Session: you can't use that location for session start/end)") << endmsg;
1432 existing->set( start, end );
1438 Session::set_auto_loop_location (Location* location)
1442 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1443 loop_connections.drop_connections ();
1444 existing->set_auto_loop (false, this);
1445 remove_event (existing->end(), SessionEvent::AutoLoop);
1448 auto_loop_declick_range (existing, dcp, dcl);
1449 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1450 auto_loop_location_changed (0);
1455 if (location == 0) {
1459 if (location->end() <= location->start()) {
1460 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1464 last_loopend = location->end();
1466 loop_connections.drop_connections ();
1468 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1469 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1470 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1472 location->set_auto_loop (true, this);
1474 /* take care of our stuff first */
1476 auto_loop_changed (location);
1478 /* now tell everyone else */
1480 auto_loop_location_changed (location);
1484 Session::update_loop (Location*)
1490 Session::update_marks (Location*)
1496 Session::update_skips (Location* loc, bool consolidate)
1498 if (_ignore_skips_updates) {
1502 Locations::LocationList skips;
1505 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1506 consolidate_skips (loc);
1509 sync_locations_to_skips ();
1515 Session::consolidate_skips (Location* loc)
1517 Locations::LocationList all_locations = _locations->list ();
1519 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1521 if (!(*l)->is_skip ()) {
1526 /* don't test against self */
1533 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1534 case Evoral::OverlapInternal:
1535 case Evoral::OverlapExternal:
1536 case Evoral::OverlapStart:
1537 case Evoral::OverlapEnd:
1538 /* adjust new location to cover existing one */
1539 loc->set_start (min (loc->start(), (*l)->start()));
1540 loc->set_end (max (loc->end(), (*l)->end()));
1541 /* we don't need this one any more */
1542 _locations->remove (*l);
1543 /* the location has been deleted, so remove reference to it in our local list */
1544 l = all_locations.erase (l);
1547 case Evoral::OverlapNone:
1555 Session::sync_locations_to_skips ()
1557 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1558 * Session::_sync_locations_to_skips() from the audioengine thread.
1560 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1564 Session::_sync_locations_to_skips ()
1566 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1568 Locations::LocationList const & locs (_locations->list());
1570 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1572 Location* location = *i;
1574 if (location->is_skip() && location->is_skipping()) {
1575 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1583 Session::location_added (Location *location)
1585 if (location->is_auto_punch()) {
1586 set_auto_punch_location (location);
1589 if (location->is_auto_loop()) {
1590 set_auto_loop_location (location);
1593 if (location->is_session_range()) {
1594 /* no need for any signal handling or event setting with the session range,
1595 because we keep a direct reference to it and use its start/end directly.
1597 _session_range_location = location;
1600 if (location->is_skip()) {
1601 /* listen for per-location signals that require us to update skip-locate events */
1603 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1604 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1605 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1606 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1608 update_skips (location, true);
1615 Session::location_removed (Location *location)
1617 if (location->is_auto_loop()) {
1618 set_auto_loop_location (0);
1619 set_track_loop (false);
1622 if (location->is_auto_punch()) {
1623 set_auto_punch_location (0);
1626 if (location->is_session_range()) {
1627 /* this is never supposed to happen */
1628 error << _("programming error: session range removed!") << endl;
1631 if (location->is_skip()) {
1633 update_skips (location, false);
1640 Session::locations_changed ()
1642 _locations->apply (*this, &Session::_locations_changed);
1646 Session::_locations_changed (const Locations::LocationList& locations)
1648 /* There was some mass-change in the Locations object.
1650 We might be re-adding a location here but it doesn't actually matter
1651 for all the locations that the Session takes an interest in.
1654 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1655 location_added (*i);
1660 Session::enable_record ()
1662 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1663 /* no recording at anything except normal speed */
1668 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1670 if (rs == Recording) {
1674 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1676 _last_record_location = _transport_frame;
1677 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1679 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1680 set_track_monitor_input_status (true);
1683 RecordStateChanged ();
1690 Session::disable_record (bool rt_context, bool force)
1694 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1696 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1697 g_atomic_int_set (&_record_status, Disabled);
1698 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1700 if (rs == Recording) {
1701 g_atomic_int_set (&_record_status, Enabled);
1705 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1706 set_track_monitor_input_status (false);
1709 RecordStateChanged (); /* emit signal */
1712 remove_pending_capture_state ();
1718 Session::step_back_from_record ()
1720 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1722 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1723 set_track_monitor_input_status (false);
1726 RecordStateChanged (); /* emit signal */
1731 Session::maybe_enable_record ()
1733 if (_step_editors > 0) {
1737 g_atomic_int_set (&_record_status, Enabled);
1739 /* This function is currently called from somewhere other than an RT thread.
1740 This save_state() call therefore doesn't impact anything. Doing it here
1741 means that we save pending state of which sources the next record will use,
1742 which gives us some chance of recovering from a crash during the record.
1745 save_state ("", true);
1747 if (_transport_speed) {
1748 if (!config.get_punch_in()) {
1752 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1753 RecordStateChanged (); /* EMIT SIGNAL */
1760 Session::audible_frame () const
1766 offset = worst_playback_latency ();
1768 if (synced_to_engine()) {
1769 /* Note: this is basically just sync-to-JACK */
1770 tf = _engine.transport_frame();
1772 tf = _transport_frame;
1777 if (!non_realtime_work_pending()) {
1781 /* Check to see if we have passed the first guaranteed
1782 audible frame past our last start position. if not,
1783 return that last start point because in terms
1784 of audible frames, we have not moved yet.
1786 `Start position' in this context means the time we last
1787 either started, located, or changed transport direction.
1790 if (_transport_speed > 0.0f) {
1792 if (!play_loop || !have_looped) {
1793 if (tf < _last_roll_or_reversal_location + offset) {
1794 return _last_roll_or_reversal_location;
1802 } else if (_transport_speed < 0.0f) {
1804 /* XXX wot? no backward looping? */
1806 if (tf > _last_roll_or_reversal_location - offset) {
1807 return _last_roll_or_reversal_location;
1819 Session::set_frame_rate (framecnt_t frames_per_second)
1821 /** \fn void Session::set_frame_size(framecnt_t)
1822 the AudioEngine object that calls this guarantees
1823 that it will not be called while we are also in
1824 ::process(). Its fine to do things that block
1828 _base_frame_rate = frames_per_second;
1829 _nominal_frame_rate = frames_per_second;
1835 // XXX we need some equivalent to this, somehow
1836 // SndFileSource::setup_standard_crossfades (frames_per_second);
1840 /* XXX need to reset/reinstantiate all LADSPA plugins */
1844 Session::set_block_size (pframes_t nframes)
1846 /* the AudioEngine guarantees
1847 that it will not be called while we are also in
1848 ::process(). It is therefore fine to do things that block
1853 current_block_size = nframes;
1857 boost::shared_ptr<RouteList> r = routes.reader ();
1859 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1860 (*i)->set_block_size (nframes);
1863 boost::shared_ptr<RouteList> rl = routes.reader ();
1864 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1865 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1867 tr->set_block_size (nframes);
1871 set_worst_io_latencies ();
1877 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1879 boost::shared_ptr<Route> r2;
1881 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1882 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1886 /* make a copy of the existing list of routes that feed r1 */
1888 Route::FedBy existing (r1->fed_by());
1890 /* for each route that feeds r1, recurse, marking it as feeding
1894 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1895 if (!(r2 = i->r.lock ())) {
1896 /* (*i) went away, ignore it */
1900 /* r2 is a route that feeds r1 which somehow feeds base. mark
1901 base as being fed by r2
1904 rbase->add_fed_by (r2, i->sends_only);
1908 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1912 if (r1->feeds (r2) && r2->feeds (r1)) {
1916 /* now recurse, so that we can mark base as being fed by
1917 all routes that feed r2
1920 trace_terminal (r2, rbase);
1927 Session::resort_routes ()
1929 /* don't do anything here with signals emitted
1930 by Routes during initial setup or while we
1931 are being destroyed.
1934 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1939 RCUWriter<RouteList> writer (routes);
1940 boost::shared_ptr<RouteList> r = writer.get_copy ();
1941 resort_routes_using (r);
1942 /* writer goes out of scope and forces update */
1946 boost::shared_ptr<RouteList> rl = routes.reader ();
1947 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1948 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1950 const Route::FedBy& fb ((*i)->fed_by());
1952 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1953 boost::shared_ptr<Route> sf = f->r.lock();
1955 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1963 /** This is called whenever we need to rebuild the graph of how we will process
1965 * @param r List of routes, in any order.
1969 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1971 /* We are going to build a directed graph of our routes;
1972 this is where the edges of that graph are put.
1977 /* Go through all routes doing two things:
1979 * 1. Collect the edges of the route graph. Each of these edges
1980 * is a pair of routes, one of which directly feeds the other
1981 * either by a JACK connection or by an internal send.
1983 * 2. Begin the process of making routes aware of which other
1984 * routes directly or indirectly feed them. This information
1985 * is used by the solo code.
1988 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1990 /* Clear out the route's list of direct or indirect feeds */
1991 (*i)->clear_fed_by ();
1993 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1995 bool via_sends_only;
1997 /* See if this *j feeds *i according to the current state of the JACK
1998 connections and internal sends.
2000 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2001 /* add the edge to the graph (part #1) */
2002 edges.add (*j, *i, via_sends_only);
2003 /* tell the route (for part #2) */
2004 (*i)->add_fed_by (*j, via_sends_only);
2009 /* Attempt a topological sort of the route graph */
2010 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2012 if (sorted_routes) {
2013 /* We got a satisfactory topological sort, so there is no feedback;
2016 Note: the process graph rechain does not require a
2017 topologically-sorted list, but hey ho.
2019 if (_process_graph) {
2020 _process_graph->rechain (sorted_routes, edges);
2023 _current_route_graph = edges;
2025 /* Complete the building of the routes' lists of what directly
2026 or indirectly feeds them.
2028 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2029 trace_terminal (*i, *i);
2032 *r = *sorted_routes;
2035 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2036 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2037 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2038 (*i)->name(), (*i)->order_key ()));
2042 SuccessfulGraphSort (); /* EMIT SIGNAL */
2045 /* The topological sort failed, so we have a problem. Tell everyone
2046 and stick to the old graph; this will continue to be processed, so
2047 until the feedback is fixed, what is played back will not quite
2048 reflect what is actually connected. Note also that we do not
2049 do trace_terminal here, as it would fail due to an endless recursion,
2050 so the solo code will think that everything is still connected
2054 FeedbackDetected (); /* EMIT SIGNAL */
2059 /** Find a route name starting with \a base, maybe followed by the
2060 * lowest \a id. \a id will always be added if \a definitely_add_number
2061 * is true on entry; otherwise it will only be added if required
2062 * to make the name unique.
2064 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2065 * The available route name with the lowest ID will be used, and \a id
2066 * will be set to the ID.
2068 * \return false if a route name could not be found, and \a track_name
2069 * and \a id do not reflect a free route name.
2072 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
2074 if (!definitely_add_number && route_by_name (base) == 0) {
2075 /* juse use the base */
2076 snprintf (name, name_len, "%s", base.c_str());
2081 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
2083 if (route_by_name (name) == 0) {
2089 } while (id < (UINT_MAX-1));
2094 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2096 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2098 in = ChanCount::ZERO;
2099 out = ChanCount::ZERO;
2101 boost::shared_ptr<RouteList> r = routes.reader ();
2103 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2104 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2105 if (tr && !tr->is_auditioner()) {
2106 in += tr->n_inputs();
2107 out += tr->n_outputs();
2112 /** Caller must not hold process lock
2113 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2114 * @param instrument plugin info for the instrument to insert pre-fader, if any
2116 list<boost::shared_ptr<MidiTrack> >
2117 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2118 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2120 char track_name[32];
2121 uint32_t track_id = 0;
2123 RouteList new_routes;
2124 list<boost::shared_ptr<MidiTrack> > ret;
2126 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
2129 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2130 error << "cannot find name for new midi track" << endmsg;
2134 boost::shared_ptr<MidiTrack> track;
2137 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2139 if (track->init ()) {
2143 track->use_new_diskstream();
2145 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2146 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2149 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2150 if (track->input()->ensure_io (input, false, this)) {
2151 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2155 if (track->output()->ensure_io (output, false, this)) {
2156 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2161 track->non_realtime_input_change();
2164 route_group->add (track);
2167 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2169 if (Config->get_remote_model() == UserOrdered) {
2170 track->set_remote_control_id (next_control_id());
2173 new_routes.push_back (track);
2174 ret.push_back (track);
2177 catch (failed_constructor &err) {
2178 error << _("Session: could not create new midi track.") << endmsg;
2182 catch (AudioEngine::PortRegistrationFailure& pfe) {
2184 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;
2192 if (!new_routes.empty()) {
2193 StateProtector sp (this);
2194 add_routes (new_routes, true, true, true);
2197 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2198 PluginPtr plugin = instrument->load (*this);
2199 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2200 (*r)->add_processor (p, PreFader);
2210 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2212 boost::shared_ptr<Route> midi_track (wmt.lock());
2218 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2220 if (change.after.n_audio() <= change.before.n_audio()) {
2224 /* new audio ports: make sure the audio goes somewhere useful,
2225 unless the user has no-auto-connect selected.
2227 The existing ChanCounts don't matter for this call as they are only
2228 to do with matching input and output indices, and we are only changing
2234 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
2238 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
2239 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
2240 * @param output_start As \a input_start, but for outputs.
2243 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
2244 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
2246 if (!IO::connecting_legal) {
2250 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2256 /* If both inputs and outputs are auto-connected to physical ports,
2257 use the max of input and output offsets to ensure auto-connected
2258 port numbers always match up (e.g. the first audio input and the
2259 first audio output of the route will have the same physical
2260 port number). Otherwise just use the lowest input or output
2264 DEBUG_TRACE (DEBUG::Graph,
2265 string_compose("Auto-connect: existing in = %1 out = %2\n",
2266 existing_inputs, existing_outputs));
2268 const bool in_out_physical =
2269 (Config->get_input_auto_connect() & AutoConnectPhysical)
2270 && (Config->get_output_auto_connect() & AutoConnectPhysical)
2273 const ChanCount in_offset = in_out_physical
2274 ? ChanCount::max(existing_inputs, existing_outputs)
2277 const ChanCount out_offset = in_out_physical
2278 ? ChanCount::max(existing_inputs, existing_outputs)
2281 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2282 vector<string> physinputs;
2283 vector<string> physoutputs;
2285 _engine.get_physical_outputs (*t, physoutputs);
2286 _engine.get_physical_inputs (*t, physinputs);
2288 if (!physinputs.empty() && connect_inputs) {
2289 uint32_t nphysical_in = physinputs.size();
2291 DEBUG_TRACE (DEBUG::Graph,
2292 string_compose("There are %1 physical inputs of type %2\n",
2295 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2298 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2299 DEBUG_TRACE (DEBUG::Graph,
2300 string_compose("Get index %1 + %2 % %3 = %4\n",
2301 in_offset.get(*t), i, nphysical_in,
2302 (in_offset.get(*t) + i) % nphysical_in));
2303 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2306 DEBUG_TRACE (DEBUG::Graph,
2307 string_compose("Connect route %1 IN to %2\n",
2308 route->name(), port));
2310 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2314 ChanCount one_added (*t, 1);
2315 existing_inputs += one_added;
2319 if (!physoutputs.empty()) {
2320 uint32_t nphysical_out = physoutputs.size();
2321 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2324 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2325 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2326 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2327 /* master bus is audio only */
2328 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2329 port = _master_out->input()->ports().port(*t,
2330 i % _master_out->input()->n_ports().get(*t))->name();
2334 DEBUG_TRACE (DEBUG::Graph,
2335 string_compose("Connect route %1 OUT to %2\n",
2336 route->name(), port));
2338 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2342 ChanCount one_added (*t, 1);
2343 existing_outputs += one_added;
2350 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2352 /* TRX does stuff here, ardour does not (but probably should). This is called after an engine reset (in particular).
2357 /** Caller must not hold process lock
2358 * @param name_template string to use for the start of the name, or "" to use "Audio".
2360 list< boost::shared_ptr<AudioTrack> >
2361 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2362 uint32_t how_many, string name_template)
2364 char track_name[32];
2365 uint32_t track_id = 0;
2367 RouteList new_routes;
2368 list<boost::shared_ptr<AudioTrack> > ret;
2370 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2373 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2374 error << "cannot find name for new audio track" << endmsg;
2378 boost::shared_ptr<AudioTrack> track;
2381 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2383 if (track->init ()) {
2387 track->use_new_diskstream();
2389 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2390 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2393 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2395 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2396 error << string_compose (
2397 _("cannot configure %1 in/%2 out configuration for new audio track"),
2398 input_channels, output_channels)
2403 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2404 error << string_compose (
2405 _("cannot configure %1 in/%2 out configuration for new audio track"),
2406 input_channels, output_channels)
2413 route_group->add (track);
2416 track->non_realtime_input_change();
2418 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2419 if (Config->get_remote_model() == UserOrdered) {
2420 track->set_remote_control_id (next_control_id());
2423 new_routes.push_back (track);
2424 ret.push_back (track);
2427 catch (failed_constructor &err) {
2428 error << _("Session: could not create new audio track.") << endmsg;
2432 catch (AudioEngine::PortRegistrationFailure& pfe) {
2434 error << pfe.what() << endmsg;
2442 if (!new_routes.empty()) {
2443 StateProtector sp (this);
2444 add_routes (new_routes, true, true, true);
2450 /** Caller must not hold process lock.
2451 * @param name_template string to use for the start of the name, or "" to use "Bus".
2454 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2457 uint32_t bus_id = 0;
2461 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2464 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2465 error << "cannot find name for new audio bus" << endmsg;
2470 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2476 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2477 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2480 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2482 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2483 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2484 input_channels, output_channels)
2490 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2491 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2492 input_channels, output_channels)
2499 route_group->add (bus);
2501 if (Config->get_remote_model() == UserOrdered) {
2502 bus->set_remote_control_id (next_control_id());
2505 bus->add_internal_return ();
2507 ret.push_back (bus);
2513 catch (failed_constructor &err) {
2514 error << _("Session: could not create new audio route.") << endmsg;
2518 catch (AudioEngine::PortRegistrationFailure& pfe) {
2519 error << pfe.what() << endmsg;
2529 StateProtector sp (this);
2530 add_routes (ret, false, true, true); // autoconnect outputs only
2538 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2541 uint32_t control_id;
2543 uint32_t number = 0;
2544 const uint32_t being_added = how_many;
2546 if (!tree.read (template_path.c_str())) {
2550 XMLNode* node = tree.root();
2552 IO::disable_connecting ();
2554 control_id = next_control_id ();
2558 XMLNode node_copy (*node);
2560 /* Remove IDs of everything so that new ones are used */
2561 node_copy.remove_property_recursively (X_("id"));
2566 if (!name_base.empty()) {
2568 /* if we're adding more than one routes, force
2569 * all the names of the new routes to be
2570 * numbered, via the final parameter.
2573 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2574 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2580 string const route_name = node_copy.property(X_("name"))->value ();
2582 /* generate a new name by adding a number to the end of the template name */
2583 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2584 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2585 abort(); /*NOTREACHED*/
2589 /* set this name in the XML description that we are about to use */
2590 Route::set_name_in_state (node_copy, name);
2592 /* trim bitslots from listen sends so that new ones are used */
2593 XMLNodeList children = node_copy.children ();
2594 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2595 if ((*i)->name() == X_("Processor")) {
2596 XMLProperty* role = (*i)->property (X_("role"));
2597 if (role && role->value() == X_("Listen")) {
2598 (*i)->remove_property (X_("bitslot"));
2603 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2606 error << _("Session: cannot create track/bus from template description") << endmsg;
2610 if (boost::dynamic_pointer_cast<Track>(route)) {
2611 /* force input/output change signals so that the new diskstream
2612 picks up the configuration of the route. During session
2613 loading this normally happens in a different way.
2616 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2618 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2619 change.after = route->input()->n_ports();
2620 route->input()->changed (change, this);
2621 change.after = route->output()->n_ports();
2622 route->output()->changed (change, this);
2625 route->set_remote_control_id (control_id);
2628 ret.push_back (route);
2631 catch (failed_constructor &err) {
2632 error << _("Session: could not create new route from template") << endmsg;
2636 catch (AudioEngine::PortRegistrationFailure& pfe) {
2637 error << pfe.what() << endmsg;
2646 StateProtector sp (this);
2647 add_routes (ret, true, true, true);
2648 IO::enable_connecting ();
2655 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2658 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2659 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2662 error << _("Adding new tracks/busses failed") << endmsg;
2667 update_latency (true);
2668 update_latency (false);
2673 save_state (_current_snapshot_name);
2676 reassign_track_numbers();
2678 RouteAdded (new_routes); /* EMIT SIGNAL */
2682 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2684 ChanCount existing_inputs;
2685 ChanCount existing_outputs;
2686 uint32_t order = next_control_id();
2688 if (_order_hint > -1) {
2689 order = _order_hint;
2693 count_existing_track_channels (existing_inputs, existing_outputs);
2696 RCUWriter<RouteList> writer (routes);
2697 boost::shared_ptr<RouteList> r = writer.get_copy ();
2698 r->insert (r->end(), new_routes.begin(), new_routes.end());
2700 /* if there is no control out and we're not in the middle of loading,
2701 resort the graph here. if there is a control out, we will resort
2702 toward the end of this method. if we are in the middle of loading,
2703 we will resort when done.
2706 if (!_monitor_out && IO::connecting_legal) {
2707 resort_routes_using (r);
2711 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2713 boost::weak_ptr<Route> wpr (*x);
2714 boost::shared_ptr<Route> r (*x);
2716 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2717 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2718 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2719 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2720 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2721 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2723 if (r->is_master()) {
2727 if (r->is_monitor()) {
2731 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2733 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2734 track_playlist_changed (boost::weak_ptr<Track> (tr));
2735 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2737 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2739 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2740 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2745 if (input_auto_connect || output_auto_connect) {
2746 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2749 /* order keys are a GUI responsibility but we need to set up
2750 reasonable defaults because they also affect the remote control
2751 ID in most situations.
2754 if (!r->has_order_key ()) {
2755 if (r->is_auditioner()) {
2756 /* use an arbitrarily high value */
2757 r->set_order_key (UINT_MAX);
2759 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2760 r->set_order_key (order);
2768 if (_monitor_out && IO::connecting_legal) {
2769 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2771 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2772 if ((*x)->is_monitor()) {
2774 } else if ((*x)->is_master()) {
2777 (*x)->enable_monitor_send ();
2784 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2786 boost::shared_ptr<RouteList> r = routes.reader ();
2787 boost::shared_ptr<Send> s;
2789 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2790 if ((s = (*i)->internal_send_for (dest)) != 0) {
2791 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO);
2797 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2799 boost::shared_ptr<RouteList> r = routes.reader ();
2800 boost::shared_ptr<Send> s;
2802 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2803 if ((s = (*i)->internal_send_for (dest)) != 0) {
2804 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY);
2810 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2812 boost::shared_ptr<RouteList> r = routes.reader ();
2813 boost::shared_ptr<Send> s;
2815 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2816 if ((s = (*i)->internal_send_for (dest)) != 0) {
2817 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2822 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2824 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2826 boost::shared_ptr<RouteList> r = routes.reader ();
2827 boost::shared_ptr<RouteList> t (new RouteList);
2829 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2830 /* no MIDI sends because there are no MIDI busses yet */
2831 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2836 add_internal_sends (dest, p, t);
2840 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2842 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2843 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2848 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2850 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2854 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2856 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2860 if (!dest->internal_return()) {
2861 dest->add_internal_return ();
2864 sender->add_aux_send (dest, before);
2870 Session::remove_route (boost::shared_ptr<Route> route)
2872 if (route == _master_out) {
2876 route->set_solo (false, this);
2879 RCUWriter<RouteList> writer (routes);
2880 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2884 /* deleting the master out seems like a dumb
2885 idea, but its more of a UI policy issue
2889 if (route == _master_out) {
2890 _master_out = boost::shared_ptr<Route> ();
2893 if (route == _monitor_out) {
2894 _monitor_out.reset ();
2897 /* writer goes out of scope, forces route list update */
2900 update_route_solo_state ();
2902 // We need to disconnect the route's inputs and outputs
2904 route->input()->disconnect (0);
2905 route->output()->disconnect (0);
2907 /* if the route had internal sends sending to it, remove them */
2908 if (route->internal_return()) {
2910 boost::shared_ptr<RouteList> r = routes.reader ();
2911 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2912 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2914 (*i)->remove_processor (s);
2919 /* if the monitoring section had a pointer to this route, remove it */
2920 if (_monitor_out && !route->is_master() && !route->is_monitor()) {
2921 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2922 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
2923 route->remove_aux_or_listen (_monitor_out);
2926 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2927 if (mt && mt->step_editing()) {
2928 if (_step_editors > 0) {
2933 update_latency_compensation ();
2936 /* Re-sort routes to remove the graph's current references to the one that is
2937 * going away, then flush old references out of the graph.
2941 if (_process_graph) {
2942 _process_graph->clear_other_chain ();
2945 /* get rid of it from the dead wood collection in the route list manager */
2947 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2951 /* try to cause everyone to drop their references */
2953 route->drop_references ();
2955 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2957 /* save the new state of the world */
2959 if (save_state (_current_snapshot_name)) {
2960 save_history (_current_snapshot_name);
2962 reassign_track_numbers();
2966 Session::route_mute_changed (void* /*src*/)
2972 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2974 boost::shared_ptr<Route> route = wpr.lock();
2976 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2980 if (route->listening_via_monitor ()) {
2982 if (Config->get_exclusive_solo()) {
2983 /* new listen: disable all other listen */
2984 boost::shared_ptr<RouteList> r = routes.reader ();
2985 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2986 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2989 (*i)->set_listen (false, this);
2995 } else if (_listen_cnt > 0) {
3000 update_route_solo_state ();
3003 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3005 boost::shared_ptr<Route> route = wpr.lock ();
3008 /* should not happen */
3009 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
3013 bool send_changed = false;
3015 if (route->solo_isolated()) {
3016 if (_solo_isolated_cnt == 0) {
3017 send_changed = true;
3019 _solo_isolated_cnt++;
3020 } else if (_solo_isolated_cnt > 0) {
3021 _solo_isolated_cnt--;
3022 if (_solo_isolated_cnt == 0) {
3023 send_changed = true;
3028 IsolatedChanged (); /* EMIT SIGNAL */
3033 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
3035 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3037 if (!self_solo_change) {
3038 // session doesn't care about changes to soloed-by-others
3042 if (solo_update_disabled) {
3044 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
3048 boost::shared_ptr<Route> route = wpr.lock ();
3051 boost::shared_ptr<RouteList> r = routes.reader ();
3054 if (route->self_soloed()) {
3060 RouteGroup* rg = route->route_group ();
3061 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
3063 if (delta == 1 && Config->get_exclusive_solo()) {
3065 /* new solo: disable all other solos, but not the group if its solo-enabled */
3067 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3068 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3069 (leave_group_alone && ((*i)->route_group() == rg))) {
3072 (*i)->set_solo (false, this);
3076 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3078 solo_update_disabled = true;
3080 RouteList uninvolved;
3082 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3084 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3085 bool via_sends_only;
3086 bool in_signal_flow;
3088 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3089 (leave_group_alone && ((*i)->route_group() == rg))) {
3093 in_signal_flow = false;
3095 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3097 if ((*i)->feeds (route, &via_sends_only)) {
3098 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3099 if (!via_sends_only) {
3100 if (!route->soloed_by_others_upstream()) {
3101 (*i)->mod_solo_by_others_downstream (delta);
3104 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3106 in_signal_flow = true;
3108 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3111 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3113 if (route->feeds (*i, &via_sends_only)) {
3114 /* propagate solo upstream only if routing other than
3115 sends is involved, but do consider the other route
3116 (*i) to be part of the signal flow even if only
3119 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3123 route->soloed_by_others_downstream(),
3124 route->soloed_by_others_upstream()));
3125 if (!via_sends_only) {
3126 if (!route->soloed_by_others_downstream()) {
3127 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3128 (*i)->mod_solo_by_others_upstream (delta);
3130 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
3133 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3135 in_signal_flow = true;
3137 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3140 if (!in_signal_flow) {
3141 uninvolved.push_back (*i);
3145 solo_update_disabled = false;
3146 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3148 update_route_solo_state (r);
3150 /* now notify that the mute state of the routes not involved in the signal
3151 pathway of the just-solo-changed route may have altered.
3154 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3155 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3156 (*i)->act_on_mute ();
3157 (*i)->mute_changed (this);
3160 SoloChanged (); /* EMIT SIGNAL */
3165 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3167 /* now figure out if anything that matters is soloed (or is "listening")*/
3169 bool something_soloed = false;
3170 uint32_t listeners = 0;
3171 uint32_t isolated = 0;
3174 r = routes.reader();
3177 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3178 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3179 something_soloed = true;
3182 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3183 if (Config->get_solo_control_is_listen_control()) {
3186 (*i)->set_listen (false, this);
3190 if ((*i)->solo_isolated()) {
3195 if (something_soloed != _non_soloed_outs_muted) {
3196 _non_soloed_outs_muted = something_soloed;
3197 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3200 _listen_cnt = listeners;
3202 if (isolated != _solo_isolated_cnt) {
3203 _solo_isolated_cnt = isolated;
3204 IsolatedChanged (); /* EMIT SIGNAL */
3207 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3208 something_soloed, listeners, isolated));
3211 boost::shared_ptr<RouteList>
3212 Session::get_routes_with_internal_returns() const
3214 boost::shared_ptr<RouteList> r = routes.reader ();
3215 boost::shared_ptr<RouteList> rl (new RouteList);
3217 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3218 if ((*i)->internal_return ()) {
3226 Session::io_name_is_legal (const std::string& name)
3228 boost::shared_ptr<RouteList> r = routes.reader ();
3230 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3231 if ((*i)->name() == name) {
3235 if ((*i)->has_io_processor_named (name)) {
3244 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3247 vector<string> connections;
3249 /* if we are passed only a single route and we're not told to turn
3250 * others off, then just do the simple thing.
3253 if (flip_others == false && rl->size() == 1) {
3254 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3256 mt->set_input_active (onoff);
3261 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3263 PortSet& ps ((*rt)->input()->ports());
3265 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3266 p->get_connections (connections);
3269 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3270 routes_using_input_from (*s, rl2);
3273 /* scan all relevant routes to see if others are on or off */
3275 bool others_are_already_on = false;
3277 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3279 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3285 if ((*r) != (*rt)) {
3286 if (mt->input_active()) {
3287 others_are_already_on = true;
3290 /* this one needs changing */
3291 mt->set_input_active (onoff);
3297 /* globally reverse other routes */
3299 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3300 if ((*r) != (*rt)) {
3301 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3303 mt->set_input_active (!others_are_already_on);
3312 Session::routes_using_input_from (const string& str, RouteList& rl)
3314 boost::shared_ptr<RouteList> r = routes.reader();
3316 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3317 if ((*i)->input()->connected_to (str)) {
3323 boost::shared_ptr<Route>
3324 Session::route_by_name (string name)
3326 boost::shared_ptr<RouteList> r = routes.reader ();
3328 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3329 if ((*i)->name() == name) {
3334 return boost::shared_ptr<Route> ((Route*) 0);
3337 boost::shared_ptr<Route>
3338 Session::route_by_id (PBD::ID id)
3340 boost::shared_ptr<RouteList> r = routes.reader ();
3342 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3343 if ((*i)->id() == id) {
3348 return boost::shared_ptr<Route> ((Route*) 0);
3351 boost::shared_ptr<Track>
3352 Session::track_by_diskstream_id (PBD::ID id)
3354 boost::shared_ptr<RouteList> r = routes.reader ();
3356 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3357 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3358 if (t && t->using_diskstream_id (id)) {
3363 return boost::shared_ptr<Track> ();
3366 boost::shared_ptr<Route>
3367 Session::route_by_remote_id (uint32_t id)
3369 boost::shared_ptr<RouteList> r = routes.reader ();
3371 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3372 if ((*i)->remote_control_id() == id) {
3377 return boost::shared_ptr<Route> ((Route*) 0);
3382 Session::reassign_track_numbers ()
3386 RouteList r (*(routes.reader ()));
3387 SignalOrderRouteSorter sorter;
3390 StateProtector sp (this);
3392 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3393 if (boost::dynamic_pointer_cast<Track> (*i)) {
3394 (*i)->set_track_number(++tn);
3396 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
3397 (*i)->set_track_number(--bn);
3400 const uint32_t decimals = ceilf (log10f (tn + 1));
3401 const bool decimals_changed = _track_number_decimals != decimals;
3402 _track_number_decimals = decimals;
3404 if (decimals_changed && config.get_track_name_number ()) {
3405 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3406 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3408 t->resync_track_name();
3411 // trigger GUI re-layout
3412 config.ParameterChanged("track-name-number");
3417 Session::playlist_region_added (boost::weak_ptr<Region> w)
3419 boost::shared_ptr<Region> r = w.lock ();
3424 /* These are the operations that are currently in progress... */
3425 list<GQuark> curr = _current_trans_quarks;
3428 /* ...and these are the operations during which we want to update
3429 the session range location markers.
3432 ops.push_back (Operations::capture);
3433 ops.push_back (Operations::paste);
3434 ops.push_back (Operations::duplicate_region);
3435 ops.push_back (Operations::insert_file);
3436 ops.push_back (Operations::insert_region);
3437 ops.push_back (Operations::drag_region_brush);
3438 ops.push_back (Operations::region_drag);
3439 ops.push_back (Operations::selection_grab);
3440 ops.push_back (Operations::region_fill);
3441 ops.push_back (Operations::fill_selection);
3442 ops.push_back (Operations::create_region);
3443 ops.push_back (Operations::region_copy);
3444 ops.push_back (Operations::fixed_time_region_copy);
3447 /* See if any of the current operations match the ones that we want */
3449 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3451 /* If so, update the session range markers */
3453 maybe_update_session_range (r->position (), r->last_frame ());
3457 /** Update the session range markers if a is before the current start or
3458 * b is after the current end.
3461 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3463 if (_state_of_the_state & Loading) {
3467 if (_session_range_location == 0) {
3469 add_session_range_location (a, b);
3473 if (a < _session_range_location->start()) {
3474 _session_range_location->set_start (a);
3477 if (b > _session_range_location->end()) {
3478 _session_range_location->set_end (b);
3484 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3486 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3487 maybe_update_session_range (i->to, i->to + i->length);
3492 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3494 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3495 maybe_update_session_range (i->from, i->to);
3499 /* Region management */
3501 boost::shared_ptr<Region>
3502 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3504 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3505 RegionFactory::RegionMap::const_iterator i;
3506 boost::shared_ptr<Region> region;
3508 Glib::Threads::Mutex::Lock lm (region_lock);
3510 for (i = regions.begin(); i != regions.end(); ++i) {
3514 if (region->whole_file()) {
3516 if (child->source_equivalent (region)) {
3522 return boost::shared_ptr<Region> ();
3526 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3528 set<boost::shared_ptr<Region> > relevant_regions;
3530 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3531 RegionFactory::get_regions_using_source (*s, relevant_regions);
3534 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3535 set<boost::shared_ptr<Region> >::iterator tmp;
3540 playlists->destroy_region (*r);
3541 RegionFactory::map_remove (*r);
3543 (*r)->drop_sources ();
3544 (*r)->drop_references ();
3546 relevant_regions.erase (r);
3551 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3554 Glib::Threads::Mutex::Lock ls (source_lock);
3555 /* remove from the main source list */
3556 sources.erase ((*s)->id());
3559 (*s)->mark_for_remove ();
3560 (*s)->drop_references ();
3569 Session::remove_last_capture ()
3571 list<boost::shared_ptr<Source> > srcs;
3573 boost::shared_ptr<RouteList> rl = routes.reader ();
3574 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3575 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3580 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3583 srcs.insert (srcs.end(), l.begin(), l.end());
3588 destroy_sources (srcs);
3590 save_state (_current_snapshot_name);
3595 /* Source Management */
3598 Session::add_source (boost::shared_ptr<Source> source)
3600 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3601 pair<SourceMap::iterator,bool> result;
3603 entry.first = source->id();
3604 entry.second = source;
3607 Glib::Threads::Mutex::Lock lm (source_lock);
3608 result = sources.insert (entry);
3611 if (result.second) {
3613 /* yay, new source */
3615 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3618 if (!fs->within_session()) {
3619 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3625 boost::shared_ptr<AudioFileSource> afs;
3627 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3628 if (Config->get_auto_analyse_audio()) {
3629 Analyser::queue_source_for_analysis (source, false);
3633 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3638 Session::remove_source (boost::weak_ptr<Source> src)
3640 if (_state_of_the_state & Deletion) {
3644 SourceMap::iterator i;
3645 boost::shared_ptr<Source> source = src.lock();
3652 Glib::Threads::Mutex::Lock lm (source_lock);
3654 if ((i = sources.find (source->id())) != sources.end()) {
3659 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
3661 /* save state so we don't end up with a session file
3662 referring to non-existent sources.
3665 save_state (_current_snapshot_name);
3669 boost::shared_ptr<Source>
3670 Session::source_by_id (const PBD::ID& id)
3672 Glib::Threads::Mutex::Lock lm (source_lock);
3673 SourceMap::iterator i;
3674 boost::shared_ptr<Source> source;
3676 if ((i = sources.find (id)) != sources.end()) {
3683 boost::shared_ptr<AudioFileSource>
3684 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3686 /* Restricted to audio files because only audio sources have channel
3690 Glib::Threads::Mutex::Lock lm (source_lock);
3692 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3693 boost::shared_ptr<AudioFileSource> afs
3694 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3696 if (afs && afs->path() == path && chn == afs->channel()) {
3701 return boost::shared_ptr<AudioFileSource>();
3704 boost::shared_ptr<MidiSource>
3705 Session::midi_source_by_path (const std::string& path) const
3707 /* Restricted to MIDI files because audio sources require a channel
3708 for unique identification, in addition to a path.
3711 Glib::Threads::Mutex::Lock lm (source_lock);
3713 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3714 boost::shared_ptr<MidiSource> ms
3715 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3716 boost::shared_ptr<FileSource> fs
3717 = boost::dynamic_pointer_cast<FileSource>(s->second);
3719 if (ms && fs && fs->path() == path) {
3724 return boost::shared_ptr<MidiSource>();
3728 Session::count_sources_by_origin (const string& path)
3731 Glib::Threads::Mutex::Lock lm (source_lock);
3733 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3734 boost::shared_ptr<FileSource> fs
3735 = boost::dynamic_pointer_cast<FileSource>(i->second);
3737 if (fs && fs->origin() == path) {
3746 Session::peak_path (string base) const
3748 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3752 Session::new_audio_source_path_for_embedded (const std::string& path)
3756 * we know that the filename is already unique because it exists
3757 * out in the filesystem.
3759 * However, when we bring it into the session, we could get a
3762 * Eg. two embedded files:
3767 * When merged into session, these collide.
3769 * There will not be a conflict with in-memory sources
3770 * because when the source was created we already picked
3771 * a unique name for it.
3773 * This collision is not likely to be common, but we have to guard
3774 * against it. So, if there is a collision, take the md5 hash of the
3775 * the path, and use that as the filename instead.
3778 SessionDirectory sdir (get_best_session_directory_for_new_audio());
3779 string base = Glib::path_get_basename (path);
3780 string newpath = Glib::build_filename (sdir.sound_path(), base);
3782 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
3786 md5.digestString (path.c_str());
3787 md5.writeToString ();
3788 base = md5.digestChars;
3790 string ext = get_suffix (path);
3797 newpath = Glib::build_filename (sdir.sound_path(), base);
3799 /* if this collides, we're screwed */
3801 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
3802 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
3811 /** Return true if there are no audio file sources that use @param name as
3812 * the filename component of their path.
3814 * Return false otherwise.
3816 * This method MUST ONLY be used to check in-session, mono files since it
3817 * hard-codes the channel of the audio file source we are looking for as zero.
3819 * If/when Ardour supports native files in non-mono formats, the logic here
3820 * will need to be revisited.
3823 Session::audio_source_name_is_unique (const string& name)
3825 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
3826 vector<space_and_path>::iterator i;
3827 uint32_t existing = 0;
3829 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
3831 /* note that we search *without* the extension so that
3832 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3833 in the event that this new name is required for
3834 a file format change.
3837 const string spath = *i;
3839 if (matching_unsuffixed_filename_exists_in (spath, name)) {
3844 /* it is possible that we have the path already
3845 * assigned to a source that has not yet been written
3846 * (ie. the write source for a diskstream). we have to
3847 * check this in order to make sure that our candidate
3848 * path isn't used again, because that can lead to
3849 * two Sources point to the same file with different
3850 * notions of their removability.
3854 string possible_path = Glib::build_filename (spath, name);
3856 if (audio_source_by_path_and_channel (possible_path, 0)) {
3862 return (existing == 0);
3866 Session::format_audio_source_name (const string& legalized_base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required, uint32_t cnt, bool related_exists)
3869 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3873 sstr << setfill ('0') << setw (4) << cnt;
3874 sstr << legalized_base;
3876 sstr << legalized_base;
3878 if (take_required || related_exists) {
3890 } else if (nchan > 2) {
3895 /* XXX what? more than 26 channels! */
3906 /** Return a unique name based on \a base for a new internal audio source */
3908 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
3911 string possible_name;
3912 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
3914 bool some_related_source_name_exists = false;
3916 legalized = legalize_for_path (base);
3918 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3920 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3922 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
3924 if (audio_source_name_is_unique (possible_name)) {
3928 some_related_source_name_exists = true;
3931 error << string_compose(
3932 _("There are already %1 recordings for %2, which I consider too many."),
3933 limit, base) << endmsg;
3935 throw failed_constructor();
3939 /* We've established that the new name does not exist in any session
3940 * directory, so now find out which one we should use for this new
3944 SessionDirectory sdir (get_best_session_directory_for_new_audio());
3946 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
3951 /** Return a unique name based on `base` for a new internal MIDI source */
3953 Session::new_midi_source_path (const string& base)
3956 char buf[PATH_MAX+1];
3957 const uint32_t limit = 10000;
3959 string possible_path;
3960 string possible_name;
3963 legalized = legalize_for_path (base);
3965 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3966 std::vector<string> sdirs = source_search_path(DataType::MIDI);
3968 /* - the main session folder is the first in the vector.
3969 * - after checking all locations for file-name uniqueness,
3970 * we keep the one from the last iteration as new file name
3971 * - midi files are small and should just be kept in the main session-folder
3973 * -> reverse the array, check main session folder last and use that as location
3976 std::reverse(sdirs.begin(), sdirs.end());
3978 for (cnt = 1; cnt <= limit; ++cnt) {
3980 vector<space_and_path>::iterator i;
3981 uint32_t existing = 0;
3983 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
3985 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3986 possible_name = buf;
3988 possible_path = Glib::build_filename (*i, possible_name);
3990 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3994 if (midi_source_by_path (possible_path)) {
3999 if (existing == 0) {
4004 error << string_compose(
4005 _("There are already %1 recordings for %2, which I consider too many."),
4006 limit, base) << endmsg;
4012 /* No need to "find best location" for software/app-based RAID, because
4013 MIDI is so small that we always put it in the same place.
4016 return possible_path;
4020 /** Create a new within-session audio source */
4021 boost::shared_ptr<AudioFileSource>
4022 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4024 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4026 if (!path.empty()) {
4027 return boost::dynamic_pointer_cast<AudioFileSource> (
4028 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
4030 throw failed_constructor ();
4034 /** Create a new within-session MIDI source */
4035 boost::shared_ptr<MidiSource>
4036 Session::create_midi_source_for_session (string const & basic_name)
4038 const string path = new_midi_source_path (basic_name);
4040 if (!path.empty()) {
4041 return boost::dynamic_pointer_cast<SMFSource> (
4042 SourceFactory::createWritable (
4043 DataType::MIDI, *this, path, false, frame_rate()));
4045 throw failed_constructor ();
4049 /** Create a new within-session MIDI source */
4050 boost::shared_ptr<MidiSource>
4051 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4053 /* the caller passes in the track the source will be used in,
4054 so that we can keep the numbering sane.
4056 Rationale: a track with the name "Foo" that has had N
4057 captures carried out so far will ALREADY have a write source
4058 named "Foo-N+1.mid" waiting to be used for the next capture.
4060 If we call new_midi_source_name() we will get "Foo-N+2". But
4061 there is no region corresponding to "Foo-N+1", so when
4062 "Foo-N+2" appears in the track, the gap presents the user
4063 with odd behaviour - why did it skip past Foo-N+1?
4065 We could explain this to the user in some odd way, but
4066 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4069 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4072 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4074 std::string name = track->steal_write_source_name ();
4077 return boost::shared_ptr<MidiSource>();
4080 /* MIDI files are small, just put them in the first location of the
4081 session source search path.
4084 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4086 return boost::dynamic_pointer_cast<SMFSource> (
4087 SourceFactory::createWritable (
4088 DataType::MIDI, *this, path, false, frame_rate()));
4093 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4095 if (playlist->hidden()) {
4099 playlists->add (playlist);
4102 playlist->release();
4109 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4111 if (_state_of_the_state & Deletion) {
4115 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4121 playlists->remove (playlist);
4127 Session::set_audition (boost::shared_ptr<Region> r)
4129 pending_audition_region = r;
4130 add_post_transport_work (PostTransportAudition);
4131 _butler->schedule_transport_work ();
4135 Session::audition_playlist ()
4137 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4138 ev->region.reset ();
4143 Session::non_realtime_set_audition ()
4145 assert (pending_audition_region);
4146 auditioner->audition_region (pending_audition_region);
4147 pending_audition_region.reset ();
4148 AuditionActive (true); /* EMIT SIGNAL */
4152 Session::audition_region (boost::shared_ptr<Region> r)
4154 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4160 Session::cancel_audition ()
4165 if (auditioner->auditioning()) {
4166 auditioner->cancel_audition ();
4167 AuditionActive (false); /* EMIT SIGNAL */
4172 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
4174 if (a->is_monitor()) {
4177 if (b->is_monitor()) {
4180 return a->order_key () < b->order_key ();
4184 Session::is_auditioning () const
4186 /* can be called before we have an auditioner object */
4188 return auditioner->auditioning();
4195 Session::graph_reordered ()
4197 /* don't do this stuff if we are setting up connections
4198 from a set_state() call or creating new tracks. Ditto for deletion.
4201 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4205 /* every track/bus asked for this to be handled but it was deferred because
4206 we were connecting. do it now.
4209 request_input_change_handling ();
4213 /* force all diskstreams to update their capture offset values to
4214 reflect any changes in latencies within the graph.
4217 boost::shared_ptr<RouteList> rl = routes.reader ();
4218 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4219 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4221 tr->set_capture_offset ();
4226 /** @return Number of frames that there is disk space available to write,
4229 boost::optional<framecnt_t>
4230 Session::available_capture_duration ()
4232 Glib::Threads::Mutex::Lock lm (space_lock);
4234 if (_total_free_4k_blocks_uncertain) {
4235 return boost::optional<framecnt_t> ();
4238 float sample_bytes_on_disk = 4.0; // keep gcc happy
4240 switch (config.get_native_file_data_format()) {
4242 sample_bytes_on_disk = 4.0;
4246 sample_bytes_on_disk = 3.0;
4250 sample_bytes_on_disk = 2.0;
4254 /* impossible, but keep some gcc versions happy */
4255 fatal << string_compose (_("programming error: %1"),
4256 X_("illegal native file data format"))
4258 abort(); /*NOTREACHED*/
4261 double scale = 4096.0 / sample_bytes_on_disk;
4263 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
4264 return max_framecnt;
4267 return (framecnt_t) floor (_total_free_4k_blocks * scale);
4271 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
4274 RCUWriter<BundleList> writer (_bundles);
4275 boost::shared_ptr<BundleList> b = writer.get_copy ();
4276 b->push_back (bundle);
4280 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4287 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
4289 bool removed = false;
4292 RCUWriter<BundleList> writer (_bundles);
4293 boost::shared_ptr<BundleList> b = writer.get_copy ();
4294 BundleList::iterator i = find (b->begin(), b->end(), bundle);
4296 if (i != b->end()) {
4303 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4309 boost::shared_ptr<Bundle>
4310 Session::bundle_by_name (string name) const
4312 boost::shared_ptr<BundleList> b = _bundles.reader ();
4314 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
4315 if ((*i)->name() == name) {
4320 return boost::shared_ptr<Bundle> ();
4324 Session::tempo_map_changed (const PropertyChange&)
4328 playlists->update_after_tempo_map_change ();
4330 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
4336 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
4338 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
4339 (*i)->recompute_frames_from_bbt ();
4343 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
4344 * the given count with the current block size.
4347 Session::ensure_buffers (ChanCount howmany)
4349 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
4353 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
4355 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4356 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
4361 Session::next_insert_id ()
4363 /* this doesn't really loop forever. just think about it */
4366 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
4367 if (!insert_bitset[n]) {
4368 insert_bitset[n] = true;
4374 /* none available, so resize and try again */
4376 insert_bitset.resize (insert_bitset.size() + 16, false);
4381 Session::next_send_id ()
4383 /* this doesn't really loop forever. just think about it */
4386 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
4387 if (!send_bitset[n]) {
4388 send_bitset[n] = true;
4394 /* none available, so resize and try again */
4396 send_bitset.resize (send_bitset.size() + 16, false);
4401 Session::next_aux_send_id ()
4403 /* this doesn't really loop forever. just think about it */
4406 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
4407 if (!aux_send_bitset[n]) {
4408 aux_send_bitset[n] = true;
4414 /* none available, so resize and try again */
4416 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
4421 Session::next_return_id ()
4423 /* this doesn't really loop forever. just think about it */
4426 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
4427 if (!return_bitset[n]) {
4428 return_bitset[n] = true;
4434 /* none available, so resize and try again */
4436 return_bitset.resize (return_bitset.size() + 16, false);
4441 Session::mark_send_id (uint32_t id)
4443 if (id >= send_bitset.size()) {
4444 send_bitset.resize (id+16, false);
4446 if (send_bitset[id]) {
4447 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4449 send_bitset[id] = true;
4453 Session::mark_aux_send_id (uint32_t id)
4455 if (id >= aux_send_bitset.size()) {
4456 aux_send_bitset.resize (id+16, false);
4458 if (aux_send_bitset[id]) {
4459 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4461 aux_send_bitset[id] = true;
4465 Session::mark_return_id (uint32_t id)
4467 if (id >= return_bitset.size()) {
4468 return_bitset.resize (id+16, false);
4470 if (return_bitset[id]) {
4471 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4473 return_bitset[id] = true;
4477 Session::mark_insert_id (uint32_t id)
4479 if (id >= insert_bitset.size()) {
4480 insert_bitset.resize (id+16, false);
4482 if (insert_bitset[id]) {
4483 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4485 insert_bitset[id] = true;
4489 Session::unmark_send_id (uint32_t id)
4491 if (id < send_bitset.size()) {
4492 send_bitset[id] = false;
4497 Session::unmark_aux_send_id (uint32_t id)
4499 if (id < aux_send_bitset.size()) {
4500 aux_send_bitset[id] = false;
4505 Session::unmark_return_id (uint32_t id)
4507 if (id < return_bitset.size()) {
4508 return_bitset[id] = false;
4513 Session::unmark_insert_id (uint32_t id)
4515 if (id < insert_bitset.size()) {
4516 insert_bitset[id] = false;
4521 Session::reset_native_file_format ()
4523 boost::shared_ptr<RouteList> rl = routes.reader ();
4524 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4525 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4527 /* don't save state as we do this, there's no point
4530 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4531 tr->reset_write_sources (false);
4532 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4538 Session::route_name_unique (string n) const
4540 boost::shared_ptr<RouteList> r = routes.reader ();
4542 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4543 if ((*i)->name() == n) {
4552 Session::route_name_internal (string n) const
4554 if (auditioner && auditioner->name() == n) {
4558 if (_click_io && _click_io->name() == n) {
4566 Session::freeze_all (InterThreadInfo& itt)
4568 boost::shared_ptr<RouteList> r = routes.reader ();
4570 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4572 boost::shared_ptr<Track> t;
4574 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4575 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4585 boost::shared_ptr<Region>
4586 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
4587 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4588 InterThreadInfo& itt,
4589 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4590 bool for_export, bool for_freeze)
4592 boost::shared_ptr<Region> result;
4593 boost::shared_ptr<Playlist> playlist;
4594 boost::shared_ptr<Source> source;
4595 ChanCount diskstream_channels (track.n_channels());
4596 framepos_t position;
4597 framecnt_t this_chunk;
4599 framepos_t latency_skip;
4601 framepos_t len = end - start;
4602 bool need_block_size_reset = false;
4603 ChanCount const max_proc = track.max_processor_streams ();
4604 string legal_playlist_name;
4605 string possible_path;
4608 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4609 end, start) << endmsg;
4613 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
4614 include_endpoint, for_export, for_freeze);
4616 if (diskstream_channels.n(track.data_type()) < 1) {
4617 error << _("Cannot write a range with no data.") << endmsg;
4621 // block all process callback handling
4623 block_processing ();
4626 // synchronize with AudioEngine::process_callback()
4627 // make sure processing is not currently running
4628 // and processing_blocked() is honored before
4629 // acquiring thread buffers
4630 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4633 _bounce_processing_active = true;
4635 /* call tree *MUST* hold route_lock */
4637 if ((playlist = track.playlist()) == 0) {
4641 legal_playlist_name = legalize_for_path (playlist->name());
4643 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
4645 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
4646 string path = ((track.data_type() == DataType::AUDIO)
4647 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
4648 : new_midi_source_path (legal_playlist_name));
4655 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
4658 catch (failed_constructor& err) {
4659 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
4663 srcs.push_back (source);
4666 /* tell redirects that care that we are about to use a much larger
4667 * blocksize. this will flush all plugins too, so that they are ready
4668 * to be used for this process.
4671 need_block_size_reset = true;
4672 track.set_block_size (bounce_chunk_size);
4673 _engine.main_thread()->get_buffers ();
4677 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4679 /* create a set of reasonably-sized buffers */
4680 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4681 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4683 buffers.set_count (max_proc);
4685 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4686 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4687 boost::shared_ptr<MidiSource> ms;
4689 afs->prepare_for_peakfile_writes ();
4690 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4691 Source::Lock lock(ms->mutex());
4692 ms->mark_streaming_write_started(lock);
4696 while (to_do && !itt.cancel) {
4698 this_chunk = min (to_do, bounce_chunk_size);
4700 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
4704 start += this_chunk;
4705 to_do -= this_chunk;
4706 itt.progress = (float) (1.0 - ((double) to_do / len));
4708 if (latency_skip >= bounce_chunk_size) {
4709 latency_skip -= bounce_chunk_size;
4713 const framecnt_t current_chunk = this_chunk - latency_skip;
4716 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4717 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4718 boost::shared_ptr<MidiSource> ms;
4721 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4724 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4725 Source::Lock lock(ms->mutex());
4727 const MidiBuffer& buf = buffers.get_midi(0);
4728 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
4729 Evoral::Event<framepos_t> ev = *i;
4730 ev.set_time(ev.time() - position);
4731 ms->append_event_frames(lock, ev, ms->timeline_position());
4738 /* post-roll, pick up delayed processor output */
4739 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4741 while (latency_skip && !itt.cancel) {
4742 this_chunk = min (latency_skip, bounce_chunk_size);
4743 latency_skip -= this_chunk;
4745 buffers.silence (this_chunk, 0);
4746 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
4749 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4750 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4753 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4765 xnow = localtime (&now);
4767 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4768 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4769 boost::shared_ptr<MidiSource> ms;
4772 afs->update_header (position, *xnow, now);
4773 afs->flush_header ();
4774 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4775 Source::Lock lock(ms->mutex());
4776 ms->mark_streaming_write_completed(lock);
4780 /* construct a region to represent the bounced material */
4784 plist.add (Properties::start, 0);
4785 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4786 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4788 result = RegionFactory::create (srcs, plist);
4794 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4795 (*src)->mark_for_remove ();
4796 (*src)->drop_references ();
4800 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4801 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4804 afs->done_with_peakfile_writes ();
4808 _bounce_processing_active = false;
4810 if (need_block_size_reset) {
4811 _engine.main_thread()->drop_buffers ();
4812 track.set_block_size (get_block_size());
4815 unblock_processing ();
4821 Session::gain_automation_buffer() const
4823 return ProcessThread::gain_automation_buffer ();
4827 Session::trim_automation_buffer() const
4829 return ProcessThread::trim_automation_buffer ();
4833 Session::send_gain_automation_buffer() const
4835 return ProcessThread::send_gain_automation_buffer ();
4839 Session::pan_automation_buffer() const
4841 return ProcessThread::pan_automation_buffer ();
4845 Session::get_silent_buffers (ChanCount count)
4847 return ProcessThread::get_silent_buffers (count);
4851 Session::get_scratch_buffers (ChanCount count, bool silence)
4853 return ProcessThread::get_scratch_buffers (count, silence);
4857 Session::get_route_buffers (ChanCount count, bool silence)
4859 return ProcessThread::get_route_buffers (count, silence);
4864 Session::get_mix_buffers (ChanCount count)
4866 return ProcessThread::get_mix_buffers (count);
4870 Session::ntracks () const
4873 boost::shared_ptr<RouteList> r = routes.reader ();
4875 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4876 if (boost::dynamic_pointer_cast<Track> (*i)) {
4885 Session::nbusses () const
4888 boost::shared_ptr<RouteList> r = routes.reader ();
4890 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4891 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4900 Session::add_automation_list(AutomationList *al)
4902 automation_lists[al->id()] = al;
4905 /** @return true if there is at least one record-enabled track, otherwise false */
4907 Session::have_rec_enabled_track () const
4909 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4912 /** Update the state of our rec-enabled tracks flag */
4914 Session::update_have_rec_enabled_track ()
4916 boost::shared_ptr<RouteList> rl = routes.reader ();
4917 RouteList::iterator i = rl->begin();
4918 while (i != rl->end ()) {
4920 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4921 if (tr && tr->record_enabled ()) {
4928 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4930 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4932 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4933 RecordStateChanged (); /* EMIT SIGNAL */
4938 Session::listen_position_changed ()
4940 boost::shared_ptr<RouteList> r = routes.reader ();
4942 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4943 (*i)->listen_position_changed ();
4948 Session::solo_control_mode_changed ()
4950 /* cancel all solo or all listen when solo control mode changes */
4953 set_solo (get_routes(), false);
4954 } else if (listening()) {
4955 set_listen (get_routes(), false);
4959 /** Called when a property of one of our route groups changes */
4961 Session::route_group_property_changed (RouteGroup* rg)
4963 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4966 /** Called when a route is added to one of our route groups */
4968 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4970 RouteAddedToRouteGroup (rg, r);
4973 /** Called when a route is removed from one of our route groups */
4975 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4977 RouteRemovedFromRouteGroup (rg, r);
4980 boost::shared_ptr<RouteList>
4981 Session::get_tracks () const
4983 boost::shared_ptr<RouteList> rl = routes.reader ();
4984 boost::shared_ptr<RouteList> tl (new RouteList);
4986 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
4987 if (boost::dynamic_pointer_cast<Track> (*r)) {
4988 if (!(*r)->is_auditioner()) {
4996 boost::shared_ptr<RouteList>
4997 Session::get_routes_with_regions_at (framepos_t const p) const
4999 boost::shared_ptr<RouteList> r = routes.reader ();
5000 boost::shared_ptr<RouteList> rl (new RouteList);
5002 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5003 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5008 boost::shared_ptr<Playlist> pl = tr->playlist ();
5013 if (pl->has_region_at (p)) {
5022 Session::goto_end ()
5024 if (_session_range_location) {
5025 request_locate (_session_range_location->end(), false);
5027 request_locate (0, false);
5032 Session::goto_start ()
5034 if (_session_range_location) {
5035 request_locate (_session_range_location->start(), false);
5037 request_locate (0, false);
5042 Session::current_start_frame () const
5044 return _session_range_location ? _session_range_location->start() : 0;
5048 Session::current_end_frame () const
5050 return _session_range_location ? _session_range_location->end() : 0;
5054 Session::add_session_range_location (framepos_t start, framepos_t end)
5056 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
5057 _locations->add (_session_range_location);
5061 Session::step_edit_status_change (bool yn)
5067 send = (_step_editors == 0);
5072 send = (_step_editors == 1);
5075 if (_step_editors > 0) {
5081 StepEditStatusChange (val);
5087 Session::start_time_changed (framepos_t old)
5089 /* Update the auto loop range to match the session range
5090 (unless the auto loop range has been changed by the user)
5093 Location* s = _locations->session_range_location ();
5098 Location* l = _locations->auto_loop_location ();
5100 if (l && l->start() == old) {
5101 l->set_start (s->start(), true);
5106 Session::end_time_changed (framepos_t old)
5108 /* Update the auto loop range to match the session range
5109 (unless the auto loop range has been changed by the user)
5112 Location* s = _locations->session_range_location ();
5117 Location* l = _locations->auto_loop_location ();
5119 if (l && l->end() == old) {
5120 l->set_end (s->end(), true);
5124 std::vector<std::string>
5125 Session::source_search_path (DataType type) const
5129 if (session_dirs.size() == 1) {
5131 case DataType::AUDIO:
5132 sp.push_back (_session_dir->sound_path());
5134 case DataType::MIDI:
5135 sp.push_back (_session_dir->midi_path());
5139 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5140 SessionDirectory sdir (i->path);
5142 case DataType::AUDIO:
5143 sp.push_back (sdir.sound_path());
5145 case DataType::MIDI:
5146 sp.push_back (sdir.midi_path());
5152 if (type == DataType::AUDIO) {
5153 const string sound_path_2X = _session_dir->sound_path_2X();
5154 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
5155 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
5156 sp.push_back (sound_path_2X);
5161 // now check the explicit (possibly user-specified) search path
5164 case DataType::AUDIO:
5165 sp += Searchpath(config.get_audio_search_path ());
5167 case DataType::MIDI:
5168 sp += Searchpath(config.get_midi_search_path ());
5176 Session::ensure_search_path_includes (const string& path, DataType type)
5185 case DataType::AUDIO:
5186 sp += Searchpath(config.get_audio_search_path ());
5188 case DataType::MIDI:
5189 sp += Searchpath (config.get_midi_search_path ());
5193 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
5194 /* No need to add this new directory if it has the same inode as
5195 an existing one; checking inode rather than name prevents duplicated
5196 directories when we are using symlinks.
5198 On Windows, I think we could just do if (*i == path) here.
5200 if (PBD::equivalent_paths (*i, path)) {
5208 case DataType::AUDIO:
5209 config.set_audio_search_path (sp.to_string());
5211 case DataType::MIDI:
5212 config.set_midi_search_path (sp.to_string());
5218 Session::remove_dir_from_search_path (const string& dir, DataType type)
5223 case DataType::AUDIO:
5224 sp = Searchpath(config.get_audio_search_path ());
5226 case DataType::MIDI:
5227 sp = Searchpath (config.get_midi_search_path ());
5234 case DataType::AUDIO:
5235 config.set_audio_search_path (sp.to_string());
5237 case DataType::MIDI:
5238 config.set_midi_search_path (sp.to_string());
5244 boost::shared_ptr<Speakers>
5245 Session::get_speakers()
5251 Session::unknown_processors () const
5255 boost::shared_ptr<RouteList> r = routes.reader ();
5256 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5257 list<string> t = (*i)->unknown_processors ();
5258 copy (t.begin(), t.end(), back_inserter (p));
5268 Session::update_latency (bool playback)
5270 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
5272 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
5276 boost::shared_ptr<RouteList> r = routes.reader ();
5277 framecnt_t max_latency = 0;
5280 /* reverse the list so that we work backwards from the last route to run to the first */
5281 RouteList* rl = routes.reader().get();
5282 r.reset (new RouteList (*rl));
5283 reverse (r->begin(), r->end());
5286 /* compute actual latency values for the given direction and store them all in per-port
5287 structures. this will also publish the same values (to JACK) so that computation of latency
5288 for routes can consistently use public latency values.
5291 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5292 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
5295 /* because we latency compensate playback, our published playback latencies should
5296 be the same for all output ports - all material played back by ardour has
5297 the same latency, whether its caused by plugins or by latency compensation. since
5298 these may differ from the values computed above, reset all playback port latencies
5302 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
5304 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5305 (*i)->set_public_port_latencies (max_latency, playback);
5310 post_playback_latency ();
5314 post_capture_latency ();
5317 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
5321 Session::post_playback_latency ()
5323 set_worst_playback_latency ();
5325 boost::shared_ptr<RouteList> r = routes.reader ();
5327 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5328 if (!(*i)->is_auditioner() && ((*i)->active())) {
5329 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
5333 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5334 (*i)->set_latency_compensation (_worst_track_latency);
5339 Session::post_capture_latency ()
5341 set_worst_capture_latency ();
5343 /* reflect any changes in capture latencies into capture offsets
5346 boost::shared_ptr<RouteList> rl = routes.reader();
5347 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5348 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5350 tr->set_capture_offset ();
5356 Session::initialize_latencies ()
5359 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5360 update_latency (false);
5361 update_latency (true);
5364 set_worst_io_latencies ();
5368 Session::set_worst_io_latencies ()
5370 set_worst_playback_latency ();
5371 set_worst_capture_latency ();
5375 Session::set_worst_playback_latency ()
5377 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5381 _worst_output_latency = 0;
5383 if (!_engine.connected()) {
5387 boost::shared_ptr<RouteList> r = routes.reader ();
5389 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5390 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
5393 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
5397 Session::set_worst_capture_latency ()
5399 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5403 _worst_input_latency = 0;
5405 if (!_engine.connected()) {
5409 boost::shared_ptr<RouteList> r = routes.reader ();
5411 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5412 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
5415 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
5419 Session::update_latency_compensation (bool force_whole_graph)
5421 bool some_track_latency_changed = false;
5423 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5427 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
5429 _worst_track_latency = 0;
5431 boost::shared_ptr<RouteList> r = routes.reader ();
5433 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5434 if (!(*i)->is_auditioner() && ((*i)->active())) {
5436 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
5437 some_track_latency_changed = true;
5439 _worst_track_latency = max (tl, _worst_track_latency);
5443 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
5444 (some_track_latency_changed ? "yes" : "no")));
5446 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
5448 if (some_track_latency_changed || force_whole_graph) {
5449 _engine.update_latencies ();
5453 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5454 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5458 tr->set_capture_offset ();
5463 Session::session_name_is_legal (const string& path)
5465 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
5467 for (int i = 0; illegal_chars[i]; ++i) {
5468 if (path.find (illegal_chars[i]) != string::npos) {
5469 return illegal_chars[i];
5477 Session::next_control_id () const
5481 /* the monitor bus remote ID is in a different
5482 * "namespace" than regular routes. its existence doesn't
5483 * affect normal (low) numbered routes.
5490 return nroutes() - subtract;
5494 Session::notify_remote_id_change ()
5496 if (deletion_in_progress()) {
5500 switch (Config->get_remote_model()) {
5502 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
5510 Session::sync_order_keys ()
5512 if (deletion_in_progress()) {
5516 /* tell everyone that something has happened to the sort keys
5517 and let them sync up with the change(s)
5518 this will give objects that manage the sort order keys the
5519 opportunity to keep them in sync if they wish to.
5522 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5524 reassign_track_numbers();
5526 Route::SyncOrderKeys (); /* EMIT SIGNAL */
5528 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5532 Session::operation_in_progress (GQuark op) const
5534 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5537 boost::shared_ptr<Port>
5538 Session::ltc_input_port () const
5540 return _ltc_input->nth (0);
5543 boost::shared_ptr<Port>
5544 Session::ltc_output_port () const
5546 return _ltc_output->nth (0);
5550 Session::reconnect_ltc_input ()
5554 string src = Config->get_ltc_source_port();
5556 _ltc_input->disconnect (this);
5558 if (src != _("None") && !src.empty()) {
5559 _ltc_input->nth (0)->connect (src);
5565 Session::reconnect_ltc_output ()
5570 string src = Config->get_ltc_sink_port();
5572 _ltc_output->disconnect (this);
5574 if (src != _("None") && !src.empty()) {
5575 _ltc_output->nth (0)->connect (src);