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/directory_names.h"
70 #include "ardour/filename_extensions.h"
71 #include "ardour/graph.h"
72 #include "ardour/midiport_manager.h"
73 #include "ardour/scene_changer.h"
74 #include "ardour/midi_track.h"
75 #include "ardour/midi_ui.h"
76 #include "ardour/operations.h"
77 #include "ardour/playlist.h"
78 #include "ardour/plugin.h"
79 #include "ardour/plugin_insert.h"
80 #include "ardour/process_thread.h"
81 #include "ardour/profile.h"
82 #include "ardour/rc_configuration.h"
83 #include "ardour/recent_sessions.h"
84 #include "ardour/region.h"
85 #include "ardour/region_factory.h"
86 #include "ardour/route_graph.h"
87 #include "ardour/route_group.h"
88 #include "ardour/route_sorters.h"
89 #include "ardour/send.h"
90 #include "ardour/session.h"
91 #include "ardour/session_directory.h"
92 #include "ardour/session_playlists.h"
93 #include "ardour/smf_source.h"
94 #include "ardour/source_factory.h"
95 #include "ardour/speakers.h"
96 #include "ardour/tempo.h"
97 #include "ardour/track.h"
98 #include "ardour/user_bundle.h"
99 #include "ardour/utils.h"
101 #include "midi++/port.h"
102 #include "midi++/mmc.h"
113 using namespace ARDOUR;
116 bool Session::_disable_all_loaded_plugins = false;
118 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
119 PBD::Signal1<void,std::string> Session::Dialog;
120 PBD::Signal0<int> Session::AskAboutPendingState;
121 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
122 PBD::Signal0<void> Session::SendFeedback;
123 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
125 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
126 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
127 PBD::Signal2<void,std::string, std::string> Session::Exported;
128 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
129 PBD::Signal0<void> Session::Quit;
130 PBD::Signal0<void> Session::FeedbackDetected;
131 PBD::Signal0<void> Session::SuccessfulGraphSort;
132 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
134 const framecnt_t Session::bounce_chunk_size = 65536;
135 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
136 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
138 /** @param snapshot_name Snapshot name, without .ardour suffix */
139 Session::Session (AudioEngine &eng,
140 const string& fullpath,
141 const string& snapshot_name,
142 BusProfile* bus_profile,
144 : playlists (new SessionPlaylists)
146 , process_function (&Session::process_with_events)
147 , _bounce_processing_active (false)
148 , waiting_for_sync_offset (false)
149 , _base_frame_rate (0)
150 , _current_frame_rate (0)
151 , _nominal_frame_rate (0)
152 , transport_sub_state (0)
153 , _record_status (Disabled)
154 , _transport_frame (0)
155 , _session_range_location (0)
158 , _transport_speed (0)
159 , _default_transport_speed (1.0)
160 , _last_transport_speed (0)
161 , _target_transport_speed (0.0)
162 , auto_play_legal (false)
163 , _last_slave_transport_frame (0)
164 , maximum_output_latency (0)
165 , _requested_return_frame (-1)
166 , current_block_size (0)
167 , _worst_output_latency (0)
168 , _worst_input_latency (0)
169 , _worst_track_latency (0)
170 , _have_captured (false)
171 , _non_soloed_outs_muted (false)
173 , _solo_isolated_cnt (0)
175 , _was_seamless (Config->get_seamless_loop ())
176 , _under_nsm_control (false)
178 , delta_accumulator_cnt (0)
179 , average_slave_delta (1800) // !!! why 1800 ???
181 , have_first_delta_accumulator (false)
182 , _slave_state (Stopped)
183 , post_export_sync (false)
184 , post_export_position (0)
186 , _export_started (false)
187 , _export_rolling (false)
188 , _pre_export_mmc_enabled (false)
189 , _name (snapshot_name)
191 , _send_qf_mtc (false)
192 , _pframes_since_last_mtc (0)
193 , session_midi_feedback (0)
195 , loop_changing (false)
197 , _session_dir (new SessionDirectory (fullpath))
198 , _current_snapshot_name (snapshot_name)
200 , state_was_pending (false)
201 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
203 , _save_queued (false)
204 , _last_roll_location (0)
205 , _last_roll_or_reversal_location (0)
206 , _last_record_location (0)
207 , pending_locate_roll (false)
208 , pending_locate_frame (0)
209 , pending_locate_flush (false)
210 , pending_abort (false)
211 , pending_auto_loop (false)
212 , _butler (new Butler (*this))
213 , _post_transport_work (0)
214 , cumulative_rf_motion (0)
216 , _locations (new Locations (*this))
217 , _ignore_skips_updates (false)
218 , _rt_thread_active (false)
219 , _rt_emit_pending (false)
221 , outbound_mtc_timecode_frame (0)
222 , next_quarter_frame_to_send (-1)
223 , _frames_per_timecode_frame (0)
224 , _frames_per_hour (0)
225 , _timecode_frames_per_hour (0)
226 , last_timecode_valid (false)
227 , last_timecode_when (0)
228 , _send_timecode_update (false)
240 , ltc_timecode_offset (0)
241 , ltc_timecode_negative_offset (false)
242 , midi_control_ui (0)
244 , _all_route_group (new RouteGroup (*this, "all"))
245 , routes (new RouteList)
246 , _adding_routes_in_progress (false)
247 , destructive_index (0)
248 , _track_number_decimals(1)
249 , solo_update_disabled (false)
250 , default_fade_steepness (0)
251 , default_fade_msecs (0)
252 , _total_free_4k_blocks (0)
253 , _total_free_4k_blocks_uncertain (false)
254 , no_questions_about_missing_files (false)
257 , _bundles (new BundleList)
258 , _bundle_xml_node (0)
262 , click_emphasis_data (0)
264 , click_emphasis_length (0)
265 , _clicks_cleared (0)
266 , _play_range (false)
268 , first_file_data_format_reset (true)
269 , first_file_header_format_reset (true)
270 , have_looped (false)
271 , _have_rec_enabled_track (false)
273 , _suspend_timecode_transmission (0)
274 , _speakers (new Speakers)
276 , ignore_route_processor_changes (false)
283 pthread_mutex_init (&_rt_emit_mutex, 0);
284 pthread_cond_init (&_rt_emit_cond, 0);
286 pre_engine_init (fullpath);
289 if (ensure_engine (sr)) {
291 throw failed_constructor ();
294 if (create (mix_template, bus_profile)) {
296 throw failed_constructor ();
299 /* if a mix template was provided, then ::create() will
300 * have copied it into the session and we need to load it
301 * so that we have the state ready for ::set_state()
302 * after the engine is started.
304 * Note that we do NOT try to get the sample rate from
305 * the template at this time, though doing so would
306 * be easy if we decided this was an appropriate part
310 if (!mix_template.empty()) {
311 if (load_state (_current_snapshot_name)) {
312 throw failed_constructor ();
314 store_recent_templates (mix_template);
317 /* load default session properties - if any */
322 if (load_state (_current_snapshot_name)) {
323 throw failed_constructor ();
326 /* try to get sample rate from XML state so that we
327 * can influence the SR if we set up the audio
332 const XMLProperty* prop;
333 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
334 sr = atoi (prop->value());
338 if (ensure_engine (sr)) {
340 throw failed_constructor ();
344 if (post_engine_init ()) {
346 throw failed_constructor ();
349 store_recent_sessions (_name, _path);
351 bool was_dirty = dirty();
353 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
355 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
356 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
359 DirtyChanged (); /* EMIT SIGNAL */
362 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
363 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
367 emit_thread_start ();
369 /* hook us up to the engine since we are now completely constructed */
371 BootMessage (_("Connect to engine"));
373 _engine.set_session (this);
374 _engine.reset_timebase ();
376 BootMessage (_("Session loading complete"));
389 Session::ensure_engine (uint32_t desired_sample_rate)
391 if (_engine.current_backend() == 0) {
392 /* backend is unknown ... */
393 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
394 if (r.get_value_or (-1) != 0) {
397 } else if (_engine.setup_required()) {
398 /* backend is known, but setup is needed */
399 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
400 if (r.get_value_or (-1) != 0) {
403 } else if (!_engine.running()) {
404 if (_engine.start()) {
409 /* at this point the engine should be running
412 if (!_engine.running()) {
416 return immediately_post_engine ();
421 Session::immediately_post_engine ()
423 /* Do various initializations that should take place directly after we
424 * know that the engine is running, but before we either create a
425 * session or set state for an existing one.
428 if (how_many_dsp_threads () > 1) {
429 /* For now, only create the graph if we are using >1 DSP threads, as
430 it is a bit slower than the old code with 1 thread.
432 _process_graph.reset (new Graph (*this));
435 /* every time we reconnect, recompute worst case output latencies */
437 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
439 if (synced_to_engine()) {
440 _engine.transport_stop ();
443 if (config.get_jack_time_master()) {
444 _engine.transport_locate (_transport_frame);
448 BootMessage (_("Set up LTC"));
450 BootMessage (_("Set up Click"));
452 BootMessage (_("Set up standard connections"));
456 catch (failed_constructor& err) {
460 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
462 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
470 vector<void*> debug_pointers;
472 /* if we got to here, leaving pending capture state around
476 remove_pending_capture_state ();
478 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
480 /* disconnect from any and all signals that we are connected to */
484 _engine.remove_session ();
486 /* deregister all ports - there will be no process or any other
487 * callbacks from the engine any more.
490 Port::PortDrop (); /* EMIT SIGNAL */
494 /* clear history so that no references to objects are held any more */
498 /* clear state tree so that no references to objects are held any more */
503 /* reset dynamic state version back to default */
505 Stateful::loading_state_version = 0;
507 _butler->drop_references ();
511 delete _all_route_group;
513 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
514 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
518 if (click_data != default_click) {
519 delete [] click_data;
522 if (click_emphasis_data != default_click_emphasis) {
523 delete [] click_emphasis_data;
528 /* need to remove auditioner before monitoring section
529 * otherwise it is re-connected */
532 /* drop references to routes held by the monitoring section
533 * specifically _monitor_out aux/listen references */
534 remove_monitor_section();
536 /* clear out any pending dead wood from RCU managed objects */
541 AudioDiskstream::free_working_buffers();
543 /* tell everyone who is still standing that we're about to die */
546 /* tell everyone to drop references and delete objects as we go */
548 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
549 RegionFactory::delete_all_regions ();
551 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
553 /* reset these three references to special routes before we do the usual route delete thing */
555 _master_out.reset ();
556 _monitor_out.reset ();
559 RCUWriter<RouteList> writer (routes);
560 boost::shared_ptr<RouteList> r = writer.get_copy ();
562 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
563 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
564 (*i)->drop_references ();
568 /* writer goes out of scope and updates master */
573 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
574 Glib::Threads::Mutex::Lock lm (source_lock);
575 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
576 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
577 i->second->drop_references ();
583 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
586 emit_thread_terminate ();
588 pthread_cond_destroy (&_rt_emit_cond);
589 pthread_mutex_destroy (&_rt_emit_mutex);
591 delete _scene_changer; _scene_changer = 0;
592 delete midi_control_ui; midi_control_ui = 0;
594 delete _mmc; _mmc = 0;
595 delete _midi_ports; _midi_ports = 0;
596 delete _locations; _locations = 0;
600 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
602 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
603 boost_debug_list_ptrs ();
608 Session::setup_ltc ()
612 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
613 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
615 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
616 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
619 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
620 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
622 reconnect_ltc_input ();
625 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
626 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
629 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
630 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
632 reconnect_ltc_output ();
635 /* fix up names of LTC ports because we don't want the normal
636 * IO style of NAME/TYPE-{in,out}N
639 _ltc_input->nth (0)->set_name (X_("LTC-in"));
640 _ltc_output->nth (0)->set_name (X_("LTC-out"));
644 Session::setup_click ()
647 _click_io.reset (new ClickIO (*this, X_("Click")));
648 _click_gain.reset (new Amp (*this));
649 _click_gain->activate ();
651 setup_click_state (state_tree->root());
653 setup_click_state (0);
658 Session::setup_click_state (const XMLNode* node)
660 const XMLNode* child = 0;
662 if (node && (child = find_named_node (*node, "Click")) != 0) {
664 /* existing state for Click */
667 if (Stateful::loading_state_version < 3000) {
668 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
670 const XMLNodeList& children (child->children());
671 XMLNodeList::const_iterator i = children.begin();
672 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
674 if (i != children.end()) {
675 c = _click_gain->set_state (**i, Stateful::loading_state_version);
681 _clicking = Config->get_clicking ();
685 error << _("could not setup Click I/O") << endmsg;
692 /* default state for Click: dual-mono to first 2 physical outputs */
695 _engine.get_physical_outputs (DataType::AUDIO, outs);
697 for (uint32_t physport = 0; physport < 2; ++physport) {
698 if (outs.size() > physport) {
699 if (_click_io->add_port (outs[physport], this)) {
700 // relax, even though its an error
705 if (_click_io->n_ports () > ChanCount::ZERO) {
706 _clicking = Config->get_clicking ();
712 Session::setup_bundles ()
716 RCUWriter<BundleList> writer (_bundles);
717 boost::shared_ptr<BundleList> b = writer.get_copy ();
718 for (BundleList::iterator i = b->begin(); i != b->end();) {
719 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
727 vector<string> inputs[DataType::num_types];
728 vector<string> outputs[DataType::num_types];
729 for (uint32_t i = 0; i < DataType::num_types; ++i) {
730 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
731 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
734 /* Create a set of Bundle objects that map
735 to the physical I/O currently available. We create both
736 mono and stereo bundles, so that the common cases of mono
737 and stereo tracks get bundles to put in their mixer strip
738 in / out menus. There may be a nicer way of achieving that;
739 it doesn't really scale that well to higher channel counts
742 /* mono output bundles */
744 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
746 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
748 snprintf (buf, sizeof (buf), _("out %s"), pn.substr(0,12).c_str());
750 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
753 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
754 c->add_channel (_("mono"), DataType::AUDIO);
755 c->set_port (0, outputs[DataType::AUDIO][np]);
757 add_bundle (c, false);
760 /* stereo output bundles */
762 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
763 if (np + 1 < outputs[DataType::AUDIO].size()) {
765 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
766 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
767 c->add_channel (_("L"), DataType::AUDIO);
768 c->set_port (0, outputs[DataType::AUDIO][np]);
769 c->add_channel (_("R"), DataType::AUDIO);
770 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
772 add_bundle (c, false);
776 /* mono input bundles */
778 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
780 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
782 snprintf (buf, sizeof (buf), _("in %s"), pn.substr(0,12).c_str());
784 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
787 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
788 c->add_channel (_("mono"), DataType::AUDIO);
789 c->set_port (0, inputs[DataType::AUDIO][np]);
791 add_bundle (c, false);
794 /* stereo input bundles */
796 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
797 if (np + 1 < inputs[DataType::AUDIO].size()) {
799 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
801 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
802 c->add_channel (_("L"), DataType::AUDIO);
803 c->set_port (0, inputs[DataType::AUDIO][np]);
804 c->add_channel (_("R"), DataType::AUDIO);
805 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
807 add_bundle (c, false);
811 /* MIDI input bundles */
813 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
814 string n = inputs[DataType::MIDI][np];
815 std::string pn = _engine.get_pretty_name_by_name (n);
819 boost::erase_first (n, X_("alsa_pcm:"));
821 boost::shared_ptr<Bundle> c (new Bundle (n, false));
822 c->add_channel ("", DataType::MIDI);
823 c->set_port (0, inputs[DataType::MIDI][np]);
824 add_bundle (c, false);
827 /* MIDI output bundles */
829 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
830 string n = outputs[DataType::MIDI][np];
831 std::string pn = _engine.get_pretty_name_by_name (n);
835 boost::erase_first (n, X_("alsa_pcm:"));
837 boost::shared_ptr<Bundle> c (new Bundle (n, true));
838 c->add_channel ("", DataType::MIDI);
839 c->set_port (0, outputs[DataType::MIDI][np]);
840 add_bundle (c, false);
843 // we trust the backend to only calls us if there's a change
844 BundleAddedOrRemoved (); /* EMIT SIGNAL */
848 Session::auto_connect_master_bus ()
850 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
854 /* if requested auto-connect the outputs to the first N physical ports.
857 uint32_t limit = _master_out->n_outputs().n_total();
858 vector<string> outputs[DataType::num_types];
860 for (uint32_t i = 0; i < DataType::num_types; ++i) {
861 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
864 for (uint32_t n = 0; n < limit; ++n) {
865 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
867 if (outputs[p->type()].size() > n) {
868 connect_to = outputs[p->type()][n];
871 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
872 if (_master_out->output()->connect (p, connect_to, this)) {
873 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
882 Session::remove_monitor_section ()
888 /* force reversion to Solo-In-Place */
889 Config->set_solo_control_is_listen_control (false);
891 /* if we are auditioning, cancel it ... this is a workaround
892 to a problem (auditioning does not execute the process graph,
893 which is needed to remove routes when using >1 core for processing)
898 /* Hold process lock while doing this so that we don't hear bits and
899 * pieces of audio as we work on each route.
902 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
904 /* Connect tracks to monitor section. Note that in an
905 existing session, the internal sends will already exist, but we want the
906 routes to notice that they connect to the control out specifically.
910 boost::shared_ptr<RouteList> r = routes.reader ();
911 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
913 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
915 if ((*x)->is_monitor()) {
917 } else if ((*x)->is_master()) {
920 (*x)->remove_aux_or_listen (_monitor_out);
925 remove_route (_monitor_out);
926 auto_connect_master_bus ();
929 auditioner->connect ();
934 Session::add_monitor_section ()
938 if (_monitor_out || !_master_out) {
942 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
948 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
949 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
952 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
953 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
954 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
958 add_routes (rl, false, false, false);
960 assert (_monitor_out);
962 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
963 are undefined, at best.
966 uint32_t limit = _monitor_out->n_inputs().n_audio();
970 /* connect the inputs to the master bus outputs. this
971 * represents a separate data feed from the internal sends from
972 * each route. as of jan 2011, it allows the monitor section to
973 * conditionally ignore either the internal sends or the normal
974 * input feed, but we should really find a better way to do
978 _master_out->output()->disconnect (this);
980 for (uint32_t n = 0; n < limit; ++n) {
981 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
982 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
985 string connect_to = o->name();
986 if (_monitor_out->input()->connect (p, connect_to, this)) {
987 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
995 /* if monitor section is not connected, connect it to physical outs
998 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
1000 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1002 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1005 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1007 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1008 Config->get_monitor_bus_preferred_bundle())
1014 /* Monitor bus is audio only */
1016 vector<string> outputs[DataType::num_types];
1018 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1019 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1022 uint32_t mod = outputs[DataType::AUDIO].size();
1023 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1027 for (uint32_t n = 0; n < limit; ++n) {
1029 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1031 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1032 connect_to = outputs[DataType::AUDIO][n % mod];
1035 if (!connect_to.empty()) {
1036 if (_monitor_out->output()->connect (p, connect_to, this)) {
1037 error << string_compose (
1038 _("cannot connect control output %1 to %2"),
1049 /* Hold process lock while doing this so that we don't hear bits and
1050 * pieces of audio as we work on each route.
1053 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1055 /* Connect tracks to monitor section. Note that in an
1056 existing session, the internal sends will already exist, but we want the
1057 routes to notice that they connect to the control out specifically.
1061 boost::shared_ptr<RouteList> rls = routes.reader ();
1063 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1065 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1067 if ((*x)->is_monitor()) {
1069 } else if ((*x)->is_master()) {
1072 (*x)->enable_monitor_send ();
1077 auditioner->connect ();
1082 Session::reset_monitor_section ()
1084 /* Process lock should be held by the caller.*/
1086 if (!_monitor_out) {
1090 uint32_t limit = _master_out->n_outputs().n_audio();
1092 /* connect the inputs to the master bus outputs. this
1093 * represents a separate data feed from the internal sends from
1094 * each route. as of jan 2011, it allows the monitor section to
1095 * conditionally ignore either the internal sends or the normal
1096 * input feed, but we should really find a better way to do
1100 _master_out->output()->disconnect (this);
1101 _monitor_out->output()->disconnect (this);
1103 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1104 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1106 for (uint32_t n = 0; n < limit; ++n) {
1107 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1108 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1111 string connect_to = o->name();
1112 if (_monitor_out->input()->connect (p, connect_to, this)) {
1113 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1120 /* connect monitor section to physical outs
1123 if (Config->get_auto_connect_standard_busses()) {
1125 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1127 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1130 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1132 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1133 Config->get_monitor_bus_preferred_bundle())
1139 /* Monitor bus is audio only */
1141 vector<string> outputs[DataType::num_types];
1143 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1144 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1147 uint32_t mod = outputs[DataType::AUDIO].size();
1148 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1152 for (uint32_t n = 0; n < limit; ++n) {
1154 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1156 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1157 connect_to = outputs[DataType::AUDIO][n % mod];
1160 if (!connect_to.empty()) {
1161 if (_monitor_out->output()->connect (p, connect_to, this)) {
1162 error << string_compose (
1163 _("cannot connect control output %1 to %2"),
1174 /* Connect tracks to monitor section. Note that in an
1175 existing session, the internal sends will already exist, but we want the
1176 routes to notice that they connect to the control out specifically.
1180 boost::shared_ptr<RouteList> rls = routes.reader ();
1182 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1184 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1186 if ((*x)->is_monitor()) {
1188 } else if ((*x)->is_master()) {
1191 (*x)->enable_monitor_send ();
1197 Session::hookup_io ()
1199 /* stop graph reordering notifications from
1200 causing resorts, etc.
1203 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1207 /* we delay creating the auditioner till now because
1208 it makes its own connections to ports.
1212 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1214 throw failed_constructor ();
1216 a->use_new_diskstream ();
1220 catch (failed_constructor& err) {
1221 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1225 /* load bundles, which we may have postponed earlier on */
1226 if (_bundle_xml_node) {
1227 load_bundles (*_bundle_xml_node);
1228 delete _bundle_xml_node;
1231 /* Tell all IO objects to connect themselves together */
1233 IO::enable_connecting ();
1235 /* Now tell all "floating" ports to connect to whatever
1236 they should be connected to.
1239 AudioEngine::instance()->reconnect_ports ();
1241 /* Anyone who cares about input state, wake up and do something */
1243 IOConnectionsComplete (); /* EMIT SIGNAL */
1245 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1247 /* now handle the whole enchilada as if it was one
1248 graph reorder event.
1253 /* update the full solo state, which can't be
1254 correctly determined on a per-route basis, but
1255 needs the global overview that only the session
1259 update_route_solo_state ();
1263 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1265 boost::shared_ptr<Track> track = wp.lock ();
1270 boost::shared_ptr<Playlist> playlist;
1272 if ((playlist = track->playlist()) != 0) {
1273 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1274 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1275 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1280 Session::record_enabling_legal () const
1282 /* this used to be in here, but survey says.... we don't need to restrict it */
1283 // if (record_status() == Recording) {
1287 if (Config->get_all_safe()) {
1294 Session::set_track_monitor_input_status (bool yn)
1296 boost::shared_ptr<RouteList> rl = routes.reader ();
1297 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1298 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1299 if (tr && tr->record_enabled ()) {
1300 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1301 tr->request_input_monitoring (yn);
1307 Session::auto_punch_start_changed (Location* location)
1309 replace_event (SessionEvent::PunchIn, location->start());
1311 if (get_record_enabled() && config.get_punch_in()) {
1312 /* capture start has been changed, so save new pending state */
1313 save_state ("", true);
1318 Session::auto_punch_end_changed (Location* location)
1320 framepos_t when_to_stop = location->end();
1321 // when_to_stop += _worst_output_latency + _worst_input_latency;
1322 replace_event (SessionEvent::PunchOut, when_to_stop);
1326 Session::auto_punch_changed (Location* location)
1328 framepos_t when_to_stop = location->end();
1330 replace_event (SessionEvent::PunchIn, location->start());
1331 //when_to_stop += _worst_output_latency + _worst_input_latency;
1332 replace_event (SessionEvent::PunchOut, when_to_stop);
1335 /** @param loc A loop location.
1336 * @param pos Filled in with the start time of the required fade-out (in session frames).
1337 * @param length Filled in with the length of the required fade-out.
1340 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1342 pos = max (loc->start(), loc->end() - 64);
1343 length = loc->end() - pos;
1347 Session::auto_loop_changed (Location* location)
1349 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1352 auto_loop_declick_range (location, dcp, dcl);
1354 if (transport_rolling() && play_loop) {
1356 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1358 // if (_transport_frame > location->end()) {
1360 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1361 // relocate to beginning of loop
1362 clear_events (SessionEvent::LocateRoll);
1364 request_locate (location->start(), true);
1367 else if (Config->get_seamless_loop() && !loop_changing) {
1369 // schedule a locate-roll to refill the diskstreams at the
1370 // previous loop end
1371 loop_changing = true;
1373 if (location->end() > last_loopend) {
1374 clear_events (SessionEvent::LocateRoll);
1375 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1381 clear_events (SessionEvent::AutoLoopDeclick);
1382 clear_events (SessionEvent::AutoLoop);
1385 last_loopend = location->end();
1390 Session::set_auto_punch_location (Location* location)
1394 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1395 punch_connections.drop_connections();
1396 existing->set_auto_punch (false, this);
1397 remove_event (existing->start(), SessionEvent::PunchIn);
1398 clear_events (SessionEvent::PunchOut);
1399 auto_punch_location_changed (0);
1404 if (location == 0) {
1408 if (location->end() <= location->start()) {
1409 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1413 punch_connections.drop_connections ();
1415 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1416 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1417 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1419 location->set_auto_punch (true, this);
1421 auto_punch_changed (location);
1423 auto_punch_location_changed (location);
1427 Session::set_session_extents (framepos_t start, framepos_t end)
1430 if ((existing = _locations->session_range_location()) == 0) {
1431 //if there is no existing session, we need to make a new session location (should never happen)
1432 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1436 error << _("Session: you can't use that location for session start/end)") << endmsg;
1440 existing->set( start, end );
1446 Session::set_auto_loop_location (Location* location)
1450 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1451 loop_connections.drop_connections ();
1452 existing->set_auto_loop (false, this);
1453 remove_event (existing->end(), SessionEvent::AutoLoop);
1456 auto_loop_declick_range (existing, dcp, dcl);
1457 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1458 auto_loop_location_changed (0);
1463 if (location == 0) {
1467 if (location->end() <= location->start()) {
1468 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1472 last_loopend = location->end();
1474 loop_connections.drop_connections ();
1476 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1477 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1478 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1480 location->set_auto_loop (true, this);
1482 /* take care of our stuff first */
1484 auto_loop_changed (location);
1486 /* now tell everyone else */
1488 auto_loop_location_changed (location);
1492 Session::update_loop (Location*)
1498 Session::update_marks (Location*)
1504 Session::update_skips (Location* loc, bool consolidate)
1506 if (_ignore_skips_updates) {
1510 Locations::LocationList skips;
1513 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1514 consolidate_skips (loc);
1517 sync_locations_to_skips ();
1523 Session::consolidate_skips (Location* loc)
1525 Locations::LocationList all_locations = _locations->list ();
1527 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1529 if (!(*l)->is_skip ()) {
1534 /* don't test against self */
1541 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1542 case Evoral::OverlapInternal:
1543 case Evoral::OverlapExternal:
1544 case Evoral::OverlapStart:
1545 case Evoral::OverlapEnd:
1546 /* adjust new location to cover existing one */
1547 loc->set_start (min (loc->start(), (*l)->start()));
1548 loc->set_end (max (loc->end(), (*l)->end()));
1549 /* we don't need this one any more */
1550 _locations->remove (*l);
1551 /* the location has been deleted, so remove reference to it in our local list */
1552 l = all_locations.erase (l);
1555 case Evoral::OverlapNone:
1563 Session::sync_locations_to_skips ()
1565 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1566 * Session::_sync_locations_to_skips() from the audioengine thread.
1568 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1572 Session::_sync_locations_to_skips ()
1574 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1576 Locations::LocationList const & locs (_locations->list());
1578 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1580 Location* location = *i;
1582 if (location->is_skip() && location->is_skipping()) {
1583 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1591 Session::location_added (Location *location)
1593 if (location->is_auto_punch()) {
1594 set_auto_punch_location (location);
1597 if (location->is_auto_loop()) {
1598 set_auto_loop_location (location);
1601 if (location->is_session_range()) {
1602 /* no need for any signal handling or event setting with the session range,
1603 because we keep a direct reference to it and use its start/end directly.
1605 _session_range_location = location;
1608 if (location->is_mark()) {
1609 /* listen for per-location signals that require us to do any * global updates for marks */
1611 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1612 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1613 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1614 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1617 if (location->is_skip()) {
1618 /* listen for per-location signals that require us to update skip-locate events */
1620 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1621 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1622 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1623 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1625 update_skips (location, true);
1632 Session::location_removed (Location *location)
1634 if (location->is_auto_loop()) {
1635 set_auto_loop_location (0);
1636 set_track_loop (false);
1639 if (location->is_auto_punch()) {
1640 set_auto_punch_location (0);
1643 if (location->is_session_range()) {
1644 /* this is never supposed to happen */
1645 error << _("programming error: session range removed!") << endl;
1648 if (location->is_skip()) {
1650 update_skips (location, false);
1657 Session::locations_changed ()
1659 _locations->apply (*this, &Session::_locations_changed);
1663 Session::_locations_changed (const Locations::LocationList& locations)
1665 /* There was some mass-change in the Locations object.
1667 We might be re-adding a location here but it doesn't actually matter
1668 for all the locations that the Session takes an interest in.
1671 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1672 location_added (*i);
1677 Session::enable_record ()
1679 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1680 /* no recording at anything except normal speed */
1685 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1687 if (rs == Recording) {
1691 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1693 _last_record_location = _transport_frame;
1694 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1696 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1697 set_track_monitor_input_status (true);
1700 RecordStateChanged ();
1707 Session::disable_record (bool rt_context, bool force)
1711 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1713 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1714 g_atomic_int_set (&_record_status, Disabled);
1715 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1717 if (rs == Recording) {
1718 g_atomic_int_set (&_record_status, Enabled);
1722 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1723 set_track_monitor_input_status (false);
1726 RecordStateChanged (); /* emit signal */
1729 remove_pending_capture_state ();
1735 Session::step_back_from_record ()
1737 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1739 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1740 set_track_monitor_input_status (false);
1743 RecordStateChanged (); /* emit signal */
1748 Session::maybe_enable_record ()
1750 if (_step_editors > 0) {
1754 g_atomic_int_set (&_record_status, Enabled);
1756 /* This function is currently called from somewhere other than an RT thread.
1757 This save_state() call therefore doesn't impact anything. Doing it here
1758 means that we save pending state of which sources the next record will use,
1759 which gives us some chance of recovering from a crash during the record.
1762 save_state ("", true);
1764 if (_transport_speed) {
1765 if (!config.get_punch_in()) {
1769 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1770 RecordStateChanged (); /* EMIT SIGNAL */
1777 Session::audible_frame () const
1783 offset = worst_playback_latency ();
1785 if (synced_to_engine()) {
1786 /* Note: this is basically just sync-to-JACK */
1787 tf = _engine.transport_frame();
1789 tf = _transport_frame;
1794 if (!non_realtime_work_pending()) {
1798 /* Check to see if we have passed the first guaranteed
1799 audible frame past our last start position. if not,
1800 return that last start point because in terms
1801 of audible frames, we have not moved yet.
1803 `Start position' in this context means the time we last
1804 either started, located, or changed transport direction.
1807 if (_transport_speed > 0.0f) {
1809 if (!play_loop || !have_looped) {
1810 if (tf < _last_roll_or_reversal_location + offset) {
1811 return _last_roll_or_reversal_location;
1819 } else if (_transport_speed < 0.0f) {
1821 /* XXX wot? no backward looping? */
1823 if (tf > _last_roll_or_reversal_location - offset) {
1824 return _last_roll_or_reversal_location;
1836 Session::set_frame_rate (framecnt_t frames_per_second)
1838 /** \fn void Session::set_frame_size(framecnt_t)
1839 the AudioEngine object that calls this guarantees
1840 that it will not be called while we are also in
1841 ::process(). Its fine to do things that block
1845 _base_frame_rate = frames_per_second;
1846 _nominal_frame_rate = frames_per_second;
1852 // XXX we need some equivalent to this, somehow
1853 // SndFileSource::setup_standard_crossfades (frames_per_second);
1857 /* XXX need to reset/reinstantiate all LADSPA plugins */
1861 Session::set_block_size (pframes_t nframes)
1863 /* the AudioEngine guarantees
1864 that it will not be called while we are also in
1865 ::process(). It is therefore fine to do things that block
1870 current_block_size = nframes;
1874 boost::shared_ptr<RouteList> r = routes.reader ();
1876 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1877 (*i)->set_block_size (nframes);
1880 boost::shared_ptr<RouteList> rl = routes.reader ();
1881 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1882 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1884 tr->set_block_size (nframes);
1888 set_worst_io_latencies ();
1894 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1896 boost::shared_ptr<Route> r2;
1898 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1899 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1903 /* make a copy of the existing list of routes that feed r1 */
1905 Route::FedBy existing (r1->fed_by());
1907 /* for each route that feeds r1, recurse, marking it as feeding
1911 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1912 if (!(r2 = i->r.lock ())) {
1913 /* (*i) went away, ignore it */
1917 /* r2 is a route that feeds r1 which somehow feeds base. mark
1918 base as being fed by r2
1921 rbase->add_fed_by (r2, i->sends_only);
1925 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1929 if (r1->feeds (r2) && r2->feeds (r1)) {
1933 /* now recurse, so that we can mark base as being fed by
1934 all routes that feed r2
1937 trace_terminal (r2, rbase);
1944 Session::resort_routes ()
1946 /* don't do anything here with signals emitted
1947 by Routes during initial setup or while we
1948 are being destroyed.
1951 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1956 RCUWriter<RouteList> writer (routes);
1957 boost::shared_ptr<RouteList> r = writer.get_copy ();
1958 resort_routes_using (r);
1959 /* writer goes out of scope and forces update */
1963 boost::shared_ptr<RouteList> rl = routes.reader ();
1964 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1965 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1967 const Route::FedBy& fb ((*i)->fed_by());
1969 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1970 boost::shared_ptr<Route> sf = f->r.lock();
1972 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1980 /** This is called whenever we need to rebuild the graph of how we will process
1982 * @param r List of routes, in any order.
1986 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1988 /* We are going to build a directed graph of our routes;
1989 this is where the edges of that graph are put.
1994 /* Go through all routes doing two things:
1996 * 1. Collect the edges of the route graph. Each of these edges
1997 * is a pair of routes, one of which directly feeds the other
1998 * either by a JACK connection or by an internal send.
2000 * 2. Begin the process of making routes aware of which other
2001 * routes directly or indirectly feed them. This information
2002 * is used by the solo code.
2005 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2007 /* Clear out the route's list of direct or indirect feeds */
2008 (*i)->clear_fed_by ();
2010 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2012 bool via_sends_only;
2014 /* See if this *j feeds *i according to the current state of the JACK
2015 connections and internal sends.
2017 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2018 /* add the edge to the graph (part #1) */
2019 edges.add (*j, *i, via_sends_only);
2020 /* tell the route (for part #2) */
2021 (*i)->add_fed_by (*j, via_sends_only);
2026 /* Attempt a topological sort of the route graph */
2027 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2029 if (sorted_routes) {
2030 /* We got a satisfactory topological sort, so there is no feedback;
2033 Note: the process graph rechain does not require a
2034 topologically-sorted list, but hey ho.
2036 if (_process_graph) {
2037 _process_graph->rechain (sorted_routes, edges);
2040 _current_route_graph = edges;
2042 /* Complete the building of the routes' lists of what directly
2043 or indirectly feeds them.
2045 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2046 trace_terminal (*i, *i);
2049 *r = *sorted_routes;
2052 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2053 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2054 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2055 (*i)->name(), (*i)->order_key ()));
2059 SuccessfulGraphSort (); /* EMIT SIGNAL */
2062 /* The topological sort failed, so we have a problem. Tell everyone
2063 and stick to the old graph; this will continue to be processed, so
2064 until the feedback is fixed, what is played back will not quite
2065 reflect what is actually connected. Note also that we do not
2066 do trace_terminal here, as it would fail due to an endless recursion,
2067 so the solo code will think that everything is still connected
2071 FeedbackDetected (); /* EMIT SIGNAL */
2076 /** Find a route name starting with \a base, maybe followed by the
2077 * lowest \a id. \a id will always be added if \a definitely_add_number
2078 * is true on entry; otherwise it will only be added if required
2079 * to make the name unique.
2081 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2082 * The available route name with the lowest ID will be used, and \a id
2083 * will be set to the ID.
2085 * \return false if a route name could not be found, and \a track_name
2086 * and \a id do not reflect a free route name.
2089 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
2091 if (!definitely_add_number && route_by_name (base) == 0) {
2092 /* juse use the base */
2093 snprintf (name, name_len, "%s", base.c_str());
2098 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
2100 if (route_by_name (name) == 0) {
2106 } while (id < (UINT_MAX-1));
2111 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2113 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2115 in = ChanCount::ZERO;
2116 out = ChanCount::ZERO;
2118 boost::shared_ptr<RouteList> r = routes.reader ();
2120 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2121 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2122 if (tr && !tr->is_auditioner()) {
2123 in += tr->n_inputs();
2124 out += tr->n_outputs();
2129 /** Caller must not hold process lock
2130 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2131 * @param instrument plugin info for the instrument to insert pre-fader, if any
2133 list<boost::shared_ptr<MidiTrack> >
2134 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2135 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2137 char track_name[32];
2138 uint32_t track_id = 0;
2140 RouteList new_routes;
2141 list<boost::shared_ptr<MidiTrack> > ret;
2143 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
2146 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2147 error << "cannot find name for new midi track" << endmsg;
2151 boost::shared_ptr<MidiTrack> track;
2154 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2156 if (track->init ()) {
2160 track->use_new_diskstream();
2162 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2163 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2166 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2167 if (track->input()->ensure_io (input, false, this)) {
2168 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2172 if (track->output()->ensure_io (output, false, this)) {
2173 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2178 track->non_realtime_input_change();
2181 route_group->add (track);
2184 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2186 if (Config->get_remote_model() == UserOrdered) {
2187 track->set_remote_control_id (next_control_id());
2190 new_routes.push_back (track);
2191 ret.push_back (track);
2194 catch (failed_constructor &err) {
2195 error << _("Session: could not create new midi track.") << endmsg;
2199 catch (AudioEngine::PortRegistrationFailure& pfe) {
2201 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;
2209 if (!new_routes.empty()) {
2210 StateProtector sp (this);
2211 if (Profile->get_trx()) {
2212 add_routes (new_routes, false, false, false);
2214 add_routes (new_routes, true, true, false);
2218 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2219 PluginPtr plugin = instrument->load (*this);
2220 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2221 (*r)->add_processor (p, PreFader);
2231 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2233 boost::shared_ptr<Route> midi_track (wmt.lock());
2239 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2241 if (change.after.n_audio() <= change.before.n_audio()) {
2245 /* new audio ports: make sure the audio goes somewhere useful,
2246 unless the user has no-auto-connect selected.
2248 The existing ChanCounts don't matter for this call as they are only
2249 to do with matching input and output indices, and we are only changing
2255 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
2259 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
2260 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
2261 * @param output_start As \a input_start, but for outputs.
2264 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
2265 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
2267 if (!IO::connecting_legal) {
2271 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2277 /* If both inputs and outputs are auto-connected to physical ports,
2278 use the max of input and output offsets to ensure auto-connected
2279 port numbers always match up (e.g. the first audio input and the
2280 first audio output of the route will have the same physical
2281 port number). Otherwise just use the lowest input or output
2285 DEBUG_TRACE (DEBUG::Graph,
2286 string_compose("Auto-connect: existing in = %1 out = %2\n",
2287 existing_inputs, existing_outputs));
2289 const bool in_out_physical =
2290 (Config->get_input_auto_connect() & AutoConnectPhysical)
2291 && (Config->get_output_auto_connect() & AutoConnectPhysical)
2294 const ChanCount in_offset = in_out_physical
2295 ? ChanCount::max(existing_inputs, existing_outputs)
2298 const ChanCount out_offset = in_out_physical
2299 ? ChanCount::max(existing_inputs, existing_outputs)
2302 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2303 vector<string> physinputs;
2304 vector<string> physoutputs;
2306 _engine.get_physical_outputs (*t, physoutputs);
2307 _engine.get_physical_inputs (*t, physinputs);
2309 if (!physinputs.empty() && connect_inputs) {
2310 uint32_t nphysical_in = physinputs.size();
2312 DEBUG_TRACE (DEBUG::Graph,
2313 string_compose("There are %1 physical inputs of type %2\n",
2316 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2319 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2320 DEBUG_TRACE (DEBUG::Graph,
2321 string_compose("Get index %1 + %2 % %3 = %4\n",
2322 in_offset.get(*t), i, nphysical_in,
2323 (in_offset.get(*t) + i) % nphysical_in));
2324 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2327 DEBUG_TRACE (DEBUG::Graph,
2328 string_compose("Connect route %1 IN to %2\n",
2329 route->name(), port));
2331 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2335 ChanCount one_added (*t, 1);
2336 existing_inputs += one_added;
2340 if (!physoutputs.empty()) {
2341 uint32_t nphysical_out = physoutputs.size();
2342 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2345 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2346 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2347 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2348 /* master bus is audio only */
2349 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2350 port = _master_out->input()->ports().port(*t,
2351 i % _master_out->input()->n_ports().get(*t))->name();
2355 DEBUG_TRACE (DEBUG::Graph,
2356 string_compose("Connect route %1 OUT to %2\n",
2357 route->name(), port));
2359 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2363 ChanCount one_added (*t, 1);
2364 existing_outputs += one_added;
2371 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2373 /* TRX does stuff here, ardour does not (but probably should). This is called after an engine reset (in particular).
2378 /** Caller must not hold process lock
2379 * @param name_template string to use for the start of the name, or "" to use "Audio".
2381 list< boost::shared_ptr<AudioTrack> >
2382 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2383 uint32_t how_many, string name_template)
2385 char track_name[32];
2386 uint32_t track_id = 0;
2388 RouteList new_routes;
2389 list<boost::shared_ptr<AudioTrack> > ret;
2391 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2394 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2395 error << "cannot find name for new audio track" << endmsg;
2399 boost::shared_ptr<AudioTrack> track;
2402 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2404 if (track->init ()) {
2408 track->use_new_diskstream();
2410 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2411 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2414 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2416 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2417 error << string_compose (
2418 _("cannot configure %1 in/%2 out configuration for new audio track"),
2419 input_channels, output_channels)
2424 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2425 error << string_compose (
2426 _("cannot configure %1 in/%2 out configuration for new audio track"),
2427 input_channels, output_channels)
2434 route_group->add (track);
2437 track->non_realtime_input_change();
2439 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2440 if (Config->get_remote_model() == UserOrdered) {
2441 track->set_remote_control_id (next_control_id());
2444 new_routes.push_back (track);
2445 ret.push_back (track);
2448 catch (failed_constructor &err) {
2449 error << _("Session: could not create new audio track.") << endmsg;
2453 catch (AudioEngine::PortRegistrationFailure& pfe) {
2455 error << pfe.what() << endmsg;
2463 if (!new_routes.empty()) {
2464 StateProtector sp (this);
2465 if (Profile->get_trx()) {
2466 add_routes (new_routes, false, false, false);
2468 add_routes (new_routes, true, true, false);
2475 /** Caller must not hold process lock.
2476 * @param name_template string to use for the start of the name, or "" to use "Bus".
2479 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2482 uint32_t bus_id = 0;
2486 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2489 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2490 error << "cannot find name for new audio bus" << endmsg;
2495 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2501 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2502 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2505 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2507 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2508 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2509 input_channels, output_channels)
2515 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2516 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2517 input_channels, output_channels)
2524 route_group->add (bus);
2526 if (Config->get_remote_model() == UserOrdered) {
2527 bus->set_remote_control_id (next_control_id());
2530 bus->add_internal_return ();
2532 ret.push_back (bus);
2538 catch (failed_constructor &err) {
2539 error << _("Session: could not create new audio route.") << endmsg;
2543 catch (AudioEngine::PortRegistrationFailure& pfe) {
2544 error << pfe.what() << endmsg;
2554 StateProtector sp (this);
2555 if (Profile->get_trx()) {
2556 add_routes (ret, false, false, false);
2558 add_routes (ret, false, true, true); // autoconnect // outputs only
2567 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2570 uint32_t control_id;
2572 uint32_t number = 0;
2573 const uint32_t being_added = how_many;
2575 if (!tree.read (template_path.c_str())) {
2579 XMLNode* node = tree.root();
2581 IO::disable_connecting ();
2583 control_id = next_control_id ();
2587 XMLNode node_copy (*node);
2589 /* Remove IDs of everything so that new ones are used */
2590 node_copy.remove_property_recursively (X_("id"));
2595 if (!name_base.empty()) {
2597 /* if we're adding more than one routes, force
2598 * all the names of the new routes to be
2599 * numbered, via the final parameter.
2602 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2603 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2609 string const route_name = node_copy.property(X_("name"))->value ();
2611 /* generate a new name by adding a number to the end of the template name */
2612 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2613 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2614 abort(); /*NOTREACHED*/
2618 /* set this name in the XML description that we are about to use */
2619 Route::set_name_in_state (node_copy, name);
2621 /* trim bitslots from listen sends so that new ones are used */
2622 XMLNodeList children = node_copy.children ();
2623 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2624 if ((*i)->name() == X_("Processor")) {
2625 XMLProperty* role = (*i)->property (X_("role"));
2626 if (role && role->value() == X_("Listen")) {
2627 (*i)->remove_property (X_("bitslot"));
2632 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2635 error << _("Session: cannot create track/bus from template description") << endmsg;
2639 if (boost::dynamic_pointer_cast<Track>(route)) {
2640 /* force input/output change signals so that the new diskstream
2641 picks up the configuration of the route. During session
2642 loading this normally happens in a different way.
2645 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2647 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2648 change.after = route->input()->n_ports();
2649 route->input()->changed (change, this);
2650 change.after = route->output()->n_ports();
2651 route->output()->changed (change, this);
2654 route->set_remote_control_id (control_id);
2657 ret.push_back (route);
2660 catch (failed_constructor &err) {
2661 error << _("Session: could not create new route from template") << endmsg;
2665 catch (AudioEngine::PortRegistrationFailure& pfe) {
2666 error << pfe.what() << endmsg;
2675 StateProtector sp (this);
2676 if (Profile->get_trx()) {
2677 add_routes (ret, false, false, false);
2679 add_routes (ret, true, true, false);
2681 IO::enable_connecting ();
2688 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2691 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2692 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2695 error << _("Adding new tracks/busses failed") << endmsg;
2700 update_latency (true);
2701 update_latency (false);
2706 save_state (_current_snapshot_name);
2709 reassign_track_numbers();
2711 RouteAdded (new_routes); /* EMIT SIGNAL */
2715 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2717 ChanCount existing_inputs;
2718 ChanCount existing_outputs;
2719 uint32_t order = next_control_id();
2721 if (_order_hint > -1) {
2722 order = _order_hint;
2726 count_existing_track_channels (existing_inputs, existing_outputs);
2729 RCUWriter<RouteList> writer (routes);
2730 boost::shared_ptr<RouteList> r = writer.get_copy ();
2731 r->insert (r->end(), new_routes.begin(), new_routes.end());
2733 /* if there is no control out and we're not in the middle of loading,
2734 resort the graph here. if there is a control out, we will resort
2735 toward the end of this method. if we are in the middle of loading,
2736 we will resort when done.
2739 if (!_monitor_out && IO::connecting_legal) {
2740 resort_routes_using (r);
2744 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2746 boost::weak_ptr<Route> wpr (*x);
2747 boost::shared_ptr<Route> r (*x);
2749 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2750 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2751 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2752 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2753 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2754 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2756 if (r->is_master()) {
2760 if (r->is_monitor()) {
2764 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2766 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2767 track_playlist_changed (boost::weak_ptr<Track> (tr));
2768 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2770 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2772 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2773 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2778 if (input_auto_connect || output_auto_connect) {
2779 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2782 /* order keys are a GUI responsibility but we need to set up
2783 reasonable defaults because they also affect the remote control
2784 ID in most situations.
2787 if (!r->has_order_key ()) {
2788 if (r->is_auditioner()) {
2789 /* use an arbitrarily high value */
2790 r->set_order_key (UINT_MAX);
2792 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2793 r->set_order_key (order);
2801 if (_monitor_out && IO::connecting_legal) {
2802 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
2804 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2805 if ((*x)->is_monitor()) {
2807 } else if ((*x)->is_master()) {
2810 (*x)->enable_monitor_send ();
2817 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2819 boost::shared_ptr<RouteList> r = routes.reader ();
2820 boost::shared_ptr<Send> s;
2822 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2823 if ((s = (*i)->internal_send_for (dest)) != 0) {
2824 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO);
2830 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2832 boost::shared_ptr<RouteList> r = routes.reader ();
2833 boost::shared_ptr<Send> s;
2835 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2836 if ((s = (*i)->internal_send_for (dest)) != 0) {
2837 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY);
2843 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2845 boost::shared_ptr<RouteList> r = routes.reader ();
2846 boost::shared_ptr<Send> s;
2848 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2849 if ((s = (*i)->internal_send_for (dest)) != 0) {
2850 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2855 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2857 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2859 boost::shared_ptr<RouteList> r = routes.reader ();
2860 boost::shared_ptr<RouteList> t (new RouteList);
2862 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2863 /* no MIDI sends because there are no MIDI busses yet */
2864 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2869 add_internal_sends (dest, p, t);
2873 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2875 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2876 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2881 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2883 add_internal_send (dest, sender->before_processor_for_index (index), sender);
2887 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2889 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2893 if (!dest->internal_return()) {
2894 dest->add_internal_return ();
2897 sender->add_aux_send (dest, before);
2903 Session::remove_route (boost::shared_ptr<Route> route)
2905 if (route == _master_out) {
2909 route->set_solo (false, this);
2912 RCUWriter<RouteList> writer (routes);
2913 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2917 /* deleting the master out seems like a dumb
2918 idea, but its more of a UI policy issue
2922 if (route == _master_out) {
2923 _master_out = boost::shared_ptr<Route> ();
2926 if (route == _monitor_out) {
2927 _monitor_out.reset ();
2930 /* writer goes out of scope, forces route list update */
2933 update_route_solo_state ();
2935 // We need to disconnect the route's inputs and outputs
2937 route->input()->disconnect (0);
2938 route->output()->disconnect (0);
2940 /* if the route had internal sends sending to it, remove them */
2941 if (route->internal_return()) {
2943 boost::shared_ptr<RouteList> r = routes.reader ();
2944 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2945 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2947 (*i)->remove_processor (s);
2952 /* if the monitoring section had a pointer to this route, remove it */
2953 if (_monitor_out && !route->is_master() && !route->is_monitor()) {
2954 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2955 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
2956 route->remove_aux_or_listen (_monitor_out);
2959 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2960 if (mt && mt->step_editing()) {
2961 if (_step_editors > 0) {
2966 update_latency_compensation ();
2969 /* Re-sort routes to remove the graph's current references to the one that is
2970 * going away, then flush old references out of the graph.
2974 if (_process_graph) {
2975 _process_graph->clear_other_chain ();
2978 /* get rid of it from the dead wood collection in the route list manager */
2980 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2984 /* try to cause everyone to drop their references */
2986 route->drop_references ();
2988 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2990 /* save the new state of the world */
2992 if (save_state (_current_snapshot_name)) {
2993 save_history (_current_snapshot_name);
2995 reassign_track_numbers();
2999 Session::route_mute_changed (void* /*src*/)
3005 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3007 boost::shared_ptr<Route> route = wpr.lock();
3009 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
3013 if (route->listening_via_monitor ()) {
3015 if (Config->get_exclusive_solo()) {
3016 /* new listen: disable all other listen */
3017 boost::shared_ptr<RouteList> r = routes.reader ();
3018 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3019 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3022 (*i)->set_listen (false, this);
3028 } else if (_listen_cnt > 0) {
3033 update_route_solo_state ();
3036 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3038 boost::shared_ptr<Route> route = wpr.lock ();
3041 /* should not happen */
3042 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
3046 bool send_changed = false;
3048 if (route->solo_isolated()) {
3049 if (_solo_isolated_cnt == 0) {
3050 send_changed = true;
3052 _solo_isolated_cnt++;
3053 } else if (_solo_isolated_cnt > 0) {
3054 _solo_isolated_cnt--;
3055 if (_solo_isolated_cnt == 0) {
3056 send_changed = true;
3061 IsolatedChanged (); /* EMIT SIGNAL */
3066 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
3068 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3070 if (!self_solo_change) {
3071 // session doesn't care about changes to soloed-by-others
3075 if (solo_update_disabled) {
3077 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
3081 boost::shared_ptr<Route> route = wpr.lock ();
3084 boost::shared_ptr<RouteList> r = routes.reader ();
3087 if (route->self_soloed()) {
3093 RouteGroup* rg = route->route_group ();
3094 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
3096 if (delta == 1 && Config->get_exclusive_solo()) {
3098 /* new solo: disable all other solos, but not the group if its solo-enabled */
3100 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3101 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3102 (leave_group_alone && ((*i)->route_group() == rg))) {
3105 (*i)->set_solo (false, this);
3109 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3111 solo_update_disabled = true;
3113 RouteList uninvolved;
3115 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3117 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3118 bool via_sends_only;
3119 bool in_signal_flow;
3121 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3122 (leave_group_alone && ((*i)->route_group() == rg))) {
3126 in_signal_flow = false;
3128 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3130 if ((*i)->feeds (route, &via_sends_only)) {
3131 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3132 if (!via_sends_only) {
3133 if (!route->soloed_by_others_upstream()) {
3134 (*i)->mod_solo_by_others_downstream (delta);
3137 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3139 in_signal_flow = true;
3141 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3144 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3146 if (route->feeds (*i, &via_sends_only)) {
3147 /* propagate solo upstream only if routing other than
3148 sends is involved, but do consider the other route
3149 (*i) to be part of the signal flow even if only
3152 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3156 route->soloed_by_others_downstream(),
3157 route->soloed_by_others_upstream()));
3158 if (!via_sends_only) {
3159 if (!route->soloed_by_others_downstream()) {
3160 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3161 (*i)->mod_solo_by_others_upstream (delta);
3163 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
3166 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3168 in_signal_flow = true;
3170 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3173 if (!in_signal_flow) {
3174 uninvolved.push_back (*i);
3178 solo_update_disabled = false;
3179 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3181 update_route_solo_state (r);
3183 /* now notify that the mute state of the routes not involved in the signal
3184 pathway of the just-solo-changed route may have altered.
3187 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3188 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3189 (*i)->act_on_mute ();
3190 (*i)->mute_changed (this);
3193 SoloChanged (); /* EMIT SIGNAL */
3198 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3200 /* now figure out if anything that matters is soloed (or is "listening")*/
3202 bool something_soloed = false;
3203 uint32_t listeners = 0;
3204 uint32_t isolated = 0;
3207 r = routes.reader();
3210 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3211 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3212 something_soloed = true;
3215 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3216 if (Config->get_solo_control_is_listen_control()) {
3219 (*i)->set_listen (false, this);
3223 if ((*i)->solo_isolated()) {
3228 if (something_soloed != _non_soloed_outs_muted) {
3229 _non_soloed_outs_muted = something_soloed;
3230 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3233 _listen_cnt = listeners;
3235 if (isolated != _solo_isolated_cnt) {
3236 _solo_isolated_cnt = isolated;
3237 IsolatedChanged (); /* EMIT SIGNAL */
3240 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3241 something_soloed, listeners, isolated));
3244 boost::shared_ptr<RouteList>
3245 Session::get_routes_with_internal_returns() const
3247 boost::shared_ptr<RouteList> r = routes.reader ();
3248 boost::shared_ptr<RouteList> rl (new RouteList);
3250 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3251 if ((*i)->internal_return ()) {
3259 Session::io_name_is_legal (const std::string& name)
3261 boost::shared_ptr<RouteList> r = routes.reader ();
3263 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3264 if ((*i)->name() == name) {
3268 if ((*i)->has_io_processor_named (name)) {
3277 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3280 vector<string> connections;
3282 /* if we are passed only a single route and we're not told to turn
3283 * others off, then just do the simple thing.
3286 if (flip_others == false && rl->size() == 1) {
3287 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3289 mt->set_input_active (onoff);
3294 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3296 PortSet& ps ((*rt)->input()->ports());
3298 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3299 p->get_connections (connections);
3302 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3303 routes_using_input_from (*s, rl2);
3306 /* scan all relevant routes to see if others are on or off */
3308 bool others_are_already_on = false;
3310 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3312 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3318 if ((*r) != (*rt)) {
3319 if (mt->input_active()) {
3320 others_are_already_on = true;
3323 /* this one needs changing */
3324 mt->set_input_active (onoff);
3330 /* globally reverse other routes */
3332 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3333 if ((*r) != (*rt)) {
3334 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3336 mt->set_input_active (!others_are_already_on);
3345 Session::routes_using_input_from (const string& str, RouteList& rl)
3347 boost::shared_ptr<RouteList> r = routes.reader();
3349 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3350 if ((*i)->input()->connected_to (str)) {
3356 boost::shared_ptr<Route>
3357 Session::route_by_name (string name)
3359 boost::shared_ptr<RouteList> r = routes.reader ();
3361 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3362 if ((*i)->name() == name) {
3367 return boost::shared_ptr<Route> ((Route*) 0);
3370 boost::shared_ptr<Route>
3371 Session::route_by_id (PBD::ID id)
3373 boost::shared_ptr<RouteList> r = routes.reader ();
3375 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3376 if ((*i)->id() == id) {
3381 return boost::shared_ptr<Route> ((Route*) 0);
3384 boost::shared_ptr<Track>
3385 Session::track_by_diskstream_id (PBD::ID id)
3387 boost::shared_ptr<RouteList> r = routes.reader ();
3389 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3390 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3391 if (t && t->using_diskstream_id (id)) {
3396 return boost::shared_ptr<Track> ();
3399 boost::shared_ptr<Route>
3400 Session::route_by_remote_id (uint32_t id)
3402 boost::shared_ptr<RouteList> r = routes.reader ();
3404 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3405 if ((*i)->remote_control_id() == id) {
3410 return boost::shared_ptr<Route> ((Route*) 0);
3415 Session::reassign_track_numbers ()
3419 RouteList r (*(routes.reader ()));
3420 SignalOrderRouteSorter sorter;
3423 StateProtector sp (this);
3425 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3426 if (boost::dynamic_pointer_cast<Track> (*i)) {
3427 (*i)->set_track_number(++tn);
3429 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
3430 (*i)->set_track_number(--bn);
3433 const uint32_t decimals = ceilf (log10f (tn + 1));
3434 const bool decimals_changed = _track_number_decimals != decimals;
3435 _track_number_decimals = decimals;
3437 if (decimals_changed && config.get_track_name_number ()) {
3438 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3439 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3441 t->resync_track_name();
3444 // trigger GUI re-layout
3445 config.ParameterChanged("track-name-number");
3450 Session::playlist_region_added (boost::weak_ptr<Region> w)
3452 boost::shared_ptr<Region> r = w.lock ();
3457 /* These are the operations that are currently in progress... */
3458 list<GQuark> curr = _current_trans_quarks;
3461 /* ...and these are the operations during which we want to update
3462 the session range location markers.
3465 ops.push_back (Operations::capture);
3466 ops.push_back (Operations::paste);
3467 ops.push_back (Operations::duplicate_region);
3468 ops.push_back (Operations::insert_file);
3469 ops.push_back (Operations::insert_region);
3470 ops.push_back (Operations::drag_region_brush);
3471 ops.push_back (Operations::region_drag);
3472 ops.push_back (Operations::selection_grab);
3473 ops.push_back (Operations::region_fill);
3474 ops.push_back (Operations::fill_selection);
3475 ops.push_back (Operations::create_region);
3476 ops.push_back (Operations::region_copy);
3477 ops.push_back (Operations::fixed_time_region_copy);
3480 /* See if any of the current operations match the ones that we want */
3482 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3484 /* If so, update the session range markers */
3486 maybe_update_session_range (r->position (), r->last_frame ());
3490 /** Update the session range markers if a is before the current start or
3491 * b is after the current end.
3494 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3496 if (_state_of_the_state & Loading) {
3500 if (_session_range_location == 0) {
3502 add_session_range_location (a, b);
3506 if (a < _session_range_location->start()) {
3507 _session_range_location->set_start (a);
3510 if (b > _session_range_location->end()) {
3511 _session_range_location->set_end (b);
3517 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3519 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3520 maybe_update_session_range (i->to, i->to + i->length);
3525 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3527 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3528 maybe_update_session_range (i->from, i->to);
3532 /* Region management */
3534 boost::shared_ptr<Region>
3535 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3537 const RegionFactory::RegionMap& regions (RegionFactory::regions());
3538 RegionFactory::RegionMap::const_iterator i;
3539 boost::shared_ptr<Region> region;
3541 Glib::Threads::Mutex::Lock lm (region_lock);
3543 for (i = regions.begin(); i != regions.end(); ++i) {
3547 if (region->whole_file()) {
3549 if (child->source_equivalent (region)) {
3555 return boost::shared_ptr<Region> ();
3559 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3561 set<boost::shared_ptr<Region> > relevant_regions;
3563 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3564 RegionFactory::get_regions_using_source (*s, relevant_regions);
3567 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3568 set<boost::shared_ptr<Region> >::iterator tmp;
3573 playlists->destroy_region (*r);
3574 RegionFactory::map_remove (*r);
3576 (*r)->drop_sources ();
3577 (*r)->drop_references ();
3579 relevant_regions.erase (r);
3584 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3587 Glib::Threads::Mutex::Lock ls (source_lock);
3588 /* remove from the main source list */
3589 sources.erase ((*s)->id());
3592 (*s)->mark_for_remove ();
3593 (*s)->drop_references ();
3602 Session::remove_last_capture ()
3604 list<boost::shared_ptr<Source> > srcs;
3606 boost::shared_ptr<RouteList> rl = routes.reader ();
3607 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3608 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3613 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3616 srcs.insert (srcs.end(), l.begin(), l.end());
3621 destroy_sources (srcs);
3623 save_state (_current_snapshot_name);
3628 /* Source Management */
3631 Session::add_source (boost::shared_ptr<Source> source)
3633 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3634 pair<SourceMap::iterator,bool> result;
3636 entry.first = source->id();
3637 entry.second = source;
3640 Glib::Threads::Mutex::Lock lm (source_lock);
3641 result = sources.insert (entry);
3644 if (result.second) {
3646 /* yay, new source */
3648 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3651 if (!fs->within_session()) {
3652 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3658 boost::shared_ptr<AudioFileSource> afs;
3660 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3661 if (Config->get_auto_analyse_audio()) {
3662 Analyser::queue_source_for_analysis (source, false);
3666 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3671 Session::remove_source (boost::weak_ptr<Source> src)
3673 if (_state_of_the_state & Deletion) {
3677 SourceMap::iterator i;
3678 boost::shared_ptr<Source> source = src.lock();
3685 Glib::Threads::Mutex::Lock lm (source_lock);
3687 if ((i = sources.find (source->id())) != sources.end()) {
3692 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
3694 /* save state so we don't end up with a session file
3695 referring to non-existent sources.
3698 save_state (_current_snapshot_name);
3702 boost::shared_ptr<Source>
3703 Session::source_by_id (const PBD::ID& id)
3705 Glib::Threads::Mutex::Lock lm (source_lock);
3706 SourceMap::iterator i;
3707 boost::shared_ptr<Source> source;
3709 if ((i = sources.find (id)) != sources.end()) {
3716 boost::shared_ptr<AudioFileSource>
3717 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3719 /* Restricted to audio files because only audio sources have channel
3723 Glib::Threads::Mutex::Lock lm (source_lock);
3725 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3726 boost::shared_ptr<AudioFileSource> afs
3727 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3729 if (afs && afs->path() == path && chn == afs->channel()) {
3734 return boost::shared_ptr<AudioFileSource>();
3737 boost::shared_ptr<MidiSource>
3738 Session::midi_source_by_path (const std::string& path) const
3740 /* Restricted to MIDI files because audio sources require a channel
3741 for unique identification, in addition to a path.
3744 Glib::Threads::Mutex::Lock lm (source_lock);
3746 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3747 boost::shared_ptr<MidiSource> ms
3748 = boost::dynamic_pointer_cast<MidiSource>(s->second);
3749 boost::shared_ptr<FileSource> fs
3750 = boost::dynamic_pointer_cast<FileSource>(s->second);
3752 if (ms && fs && fs->path() == path) {
3757 return boost::shared_ptr<MidiSource>();
3761 Session::count_sources_by_origin (const string& path)
3764 Glib::Threads::Mutex::Lock lm (source_lock);
3766 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3767 boost::shared_ptr<FileSource> fs
3768 = boost::dynamic_pointer_cast<FileSource>(i->second);
3770 if (fs && fs->origin() == path) {
3779 Session::peak_path (string base) const
3781 if (Glib::path_is_absolute (base)) {
3783 /* rip the session dir from the audiofile source */
3785 string session_path;
3786 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
3787 bool in_another_session = true;
3789 if (base.find (interchange_dir_string) != string::npos) {
3791 session_path = Glib::path_get_dirname (base); /* now ends in audiofiles */
3792 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
3793 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
3794 session_path = Glib::path_get_dirname (session_path); /* now has session path */
3796 /* see if it is within our session */
3798 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3799 if (i->path == session_path) {
3800 in_another_session = false;
3805 in_another_session = false;
3809 if (in_another_session) {
3810 SessionDirectory sd (session_path);
3811 return Glib::build_filename (sd.peak_path(), Glib::path_get_basename (base) + peakfile_suffix);
3815 base = Glib::path_get_basename (base);
3816 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3820 Session::new_audio_source_path_for_embedded (const std::string& path)
3824 * we know that the filename is already unique because it exists
3825 * out in the filesystem.
3827 * However, when we bring it into the session, we could get a
3830 * Eg. two embedded files:
3835 * When merged into session, these collide.
3837 * There will not be a conflict with in-memory sources
3838 * because when the source was created we already picked
3839 * a unique name for it.
3841 * This collision is not likely to be common, but we have to guard
3842 * against it. So, if there is a collision, take the md5 hash of the
3843 * the path, and use that as the filename instead.
3846 SessionDirectory sdir (get_best_session_directory_for_new_audio());
3847 string base = Glib::path_get_basename (path);
3848 string newpath = Glib::build_filename (sdir.sound_path(), base);
3850 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
3854 md5.digestString (path.c_str());
3855 md5.writeToString ();
3856 base = md5.digestChars;
3858 string ext = get_suffix (path);
3865 newpath = Glib::build_filename (sdir.sound_path(), base);
3867 /* if this collides, we're screwed */
3869 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
3870 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
3879 /** Return true if there are no audio file sources that use @param name as
3880 * the filename component of their path.
3882 * Return false otherwise.
3884 * This method MUST ONLY be used to check in-session, mono files since it
3885 * hard-codes the channel of the audio file source we are looking for as zero.
3887 * If/when Ardour supports native files in non-mono formats, the logic here
3888 * will need to be revisited.
3891 Session::audio_source_name_is_unique (const string& name)
3893 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
3894 vector<space_and_path>::iterator i;
3895 uint32_t existing = 0;
3897 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
3899 /* note that we search *without* the extension so that
3900 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3901 in the event that this new name is required for
3902 a file format change.
3905 const string spath = *i;
3907 if (matching_unsuffixed_filename_exists_in (spath, name)) {
3912 /* it is possible that we have the path already
3913 * assigned to a source that has not yet been written
3914 * (ie. the write source for a diskstream). we have to
3915 * check this in order to make sure that our candidate
3916 * path isn't used again, because that can lead to
3917 * two Sources point to the same file with different
3918 * notions of their removability.
3922 string possible_path = Glib::build_filename (spath, name);
3924 if (audio_source_by_path_and_channel (possible_path, 0)) {
3930 return (existing == 0);
3934 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)
3937 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3941 sstr << setfill ('0') << setw (4) << cnt;
3942 sstr << legalized_base;
3944 sstr << legalized_base;
3946 if (take_required || related_exists) {
3958 } else if (nchan > 2) {
3963 /* XXX what? more than 26 channels! */
3974 /** Return a unique name based on \a base for a new internal audio source */
3976 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
3979 string possible_name;
3980 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
3982 bool some_related_source_name_exists = false;
3984 legalized = legalize_for_path (base);
3986 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3988 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3990 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
3992 if (audio_source_name_is_unique (possible_name)) {
3996 some_related_source_name_exists = true;
3999 error << string_compose(
4000 _("There are already %1 recordings for %2, which I consider too many."),
4001 limit, base) << endmsg;
4003 throw failed_constructor();
4007 /* We've established that the new name does not exist in any session
4008 * directory, so now find out which one we should use for this new
4012 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4014 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4019 /** Return a unique name based on `base` for a new internal MIDI source */
4021 Session::new_midi_source_path (const string& base)
4024 char buf[PATH_MAX+1];
4025 const uint32_t limit = 10000;
4027 string possible_path;
4028 string possible_name;
4031 legalized = legalize_for_path (base);
4033 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4034 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4036 /* - the main session folder is the first in the vector.
4037 * - after checking all locations for file-name uniqueness,
4038 * we keep the one from the last iteration as new file name
4039 * - midi files are small and should just be kept in the main session-folder
4041 * -> reverse the array, check main session folder last and use that as location
4044 std::reverse(sdirs.begin(), sdirs.end());
4046 for (cnt = 1; cnt <= limit; ++cnt) {
4048 vector<space_and_path>::iterator i;
4049 uint32_t existing = 0;
4051 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4053 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4054 possible_name = buf;
4056 possible_path = Glib::build_filename (*i, possible_name);
4058 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4062 if (midi_source_by_path (possible_path)) {
4067 if (existing == 0) {
4072 error << string_compose(
4073 _("There are already %1 recordings for %2, which I consider too many."),
4074 limit, base) << endmsg;
4080 /* No need to "find best location" for software/app-based RAID, because
4081 MIDI is so small that we always put it in the same place.
4084 return possible_path;
4088 /** Create a new within-session audio source */
4089 boost::shared_ptr<AudioFileSource>
4090 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4092 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4094 if (!path.empty()) {
4095 return boost::dynamic_pointer_cast<AudioFileSource> (
4096 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
4098 throw failed_constructor ();
4102 /** Create a new within-session MIDI source */
4103 boost::shared_ptr<MidiSource>
4104 Session::create_midi_source_for_session (string const & basic_name)
4106 const string path = new_midi_source_path (basic_name);
4108 if (!path.empty()) {
4109 return boost::dynamic_pointer_cast<SMFSource> (
4110 SourceFactory::createWritable (
4111 DataType::MIDI, *this, path, false, frame_rate()));
4113 throw failed_constructor ();
4117 /** Create a new within-session MIDI source */
4118 boost::shared_ptr<MidiSource>
4119 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4121 /* the caller passes in the track the source will be used in,
4122 so that we can keep the numbering sane.
4124 Rationale: a track with the name "Foo" that has had N
4125 captures carried out so far will ALREADY have a write source
4126 named "Foo-N+1.mid" waiting to be used for the next capture.
4128 If we call new_midi_source_name() we will get "Foo-N+2". But
4129 there is no region corresponding to "Foo-N+1", so when
4130 "Foo-N+2" appears in the track, the gap presents the user
4131 with odd behaviour - why did it skip past Foo-N+1?
4133 We could explain this to the user in some odd way, but
4134 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4137 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4140 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4142 std::string name = track->steal_write_source_name ();
4145 return boost::shared_ptr<MidiSource>();
4148 /* MIDI files are small, just put them in the first location of the
4149 session source search path.
4152 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4154 return boost::dynamic_pointer_cast<SMFSource> (
4155 SourceFactory::createWritable (
4156 DataType::MIDI, *this, path, false, frame_rate()));
4161 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4163 if (playlist->hidden()) {
4167 playlists->add (playlist);
4170 playlist->release();
4177 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4179 if (_state_of_the_state & Deletion) {
4183 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4189 playlists->remove (playlist);
4195 Session::set_audition (boost::shared_ptr<Region> r)
4197 pending_audition_region = r;
4198 add_post_transport_work (PostTransportAudition);
4199 _butler->schedule_transport_work ();
4203 Session::audition_playlist ()
4205 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4206 ev->region.reset ();
4211 Session::non_realtime_set_audition ()
4213 assert (pending_audition_region);
4214 auditioner->audition_region (pending_audition_region);
4215 pending_audition_region.reset ();
4216 AuditionActive (true); /* EMIT SIGNAL */
4220 Session::audition_region (boost::shared_ptr<Region> r)
4222 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4228 Session::cancel_audition ()
4233 if (auditioner->auditioning()) {
4234 auditioner->cancel_audition ();
4235 AuditionActive (false); /* EMIT SIGNAL */
4240 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
4242 if (a->is_monitor()) {
4245 if (b->is_monitor()) {
4248 return a->order_key () < b->order_key ();
4252 Session::is_auditioning () const
4254 /* can be called before we have an auditioner object */
4256 return auditioner->auditioning();
4263 Session::graph_reordered ()
4265 /* don't do this stuff if we are setting up connections
4266 from a set_state() call or creating new tracks. Ditto for deletion.
4269 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4273 /* every track/bus asked for this to be handled but it was deferred because
4274 we were connecting. do it now.
4277 request_input_change_handling ();
4281 /* force all diskstreams to update their capture offset values to
4282 reflect any changes in latencies within the graph.
4285 boost::shared_ptr<RouteList> rl = routes.reader ();
4286 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4287 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4289 tr->set_capture_offset ();
4294 /** @return Number of frames that there is disk space available to write,
4297 boost::optional<framecnt_t>
4298 Session::available_capture_duration ()
4300 Glib::Threads::Mutex::Lock lm (space_lock);
4302 if (_total_free_4k_blocks_uncertain) {
4303 return boost::optional<framecnt_t> ();
4306 float sample_bytes_on_disk = 4.0; // keep gcc happy
4308 switch (config.get_native_file_data_format()) {
4310 sample_bytes_on_disk = 4.0;
4314 sample_bytes_on_disk = 3.0;
4318 sample_bytes_on_disk = 2.0;
4322 /* impossible, but keep some gcc versions happy */
4323 fatal << string_compose (_("programming error: %1"),
4324 X_("illegal native file data format"))
4326 abort(); /*NOTREACHED*/
4329 double scale = 4096.0 / sample_bytes_on_disk;
4331 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
4332 return max_framecnt;
4335 return (framecnt_t) floor (_total_free_4k_blocks * scale);
4339 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
4342 RCUWriter<BundleList> writer (_bundles);
4343 boost::shared_ptr<BundleList> b = writer.get_copy ();
4344 b->push_back (bundle);
4348 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4355 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
4357 bool removed = false;
4360 RCUWriter<BundleList> writer (_bundles);
4361 boost::shared_ptr<BundleList> b = writer.get_copy ();
4362 BundleList::iterator i = find (b->begin(), b->end(), bundle);
4364 if (i != b->end()) {
4371 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4377 boost::shared_ptr<Bundle>
4378 Session::bundle_by_name (string name) const
4380 boost::shared_ptr<BundleList> b = _bundles.reader ();
4382 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
4383 if ((*i)->name() == name) {
4388 return boost::shared_ptr<Bundle> ();
4392 Session::tempo_map_changed (const PropertyChange&)
4396 playlists->update_after_tempo_map_change ();
4398 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
4404 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
4406 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
4407 (*i)->recompute_frames_from_bbt ();
4411 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
4412 * the given count with the current block size.
4415 Session::ensure_buffers (ChanCount howmany)
4417 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
4421 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
4423 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4424 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
4429 Session::next_insert_id ()
4431 /* this doesn't really loop forever. just think about it */
4434 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
4435 if (!insert_bitset[n]) {
4436 insert_bitset[n] = true;
4442 /* none available, so resize and try again */
4444 insert_bitset.resize (insert_bitset.size() + 16, false);
4449 Session::next_send_id ()
4451 /* this doesn't really loop forever. just think about it */
4454 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
4455 if (!send_bitset[n]) {
4456 send_bitset[n] = true;
4462 /* none available, so resize and try again */
4464 send_bitset.resize (send_bitset.size() + 16, false);
4469 Session::next_aux_send_id ()
4471 /* this doesn't really loop forever. just think about it */
4474 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
4475 if (!aux_send_bitset[n]) {
4476 aux_send_bitset[n] = true;
4482 /* none available, so resize and try again */
4484 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
4489 Session::next_return_id ()
4491 /* this doesn't really loop forever. just think about it */
4494 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
4495 if (!return_bitset[n]) {
4496 return_bitset[n] = true;
4502 /* none available, so resize and try again */
4504 return_bitset.resize (return_bitset.size() + 16, false);
4509 Session::mark_send_id (uint32_t id)
4511 if (id >= send_bitset.size()) {
4512 send_bitset.resize (id+16, false);
4514 if (send_bitset[id]) {
4515 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4517 send_bitset[id] = true;
4521 Session::mark_aux_send_id (uint32_t id)
4523 if (id >= aux_send_bitset.size()) {
4524 aux_send_bitset.resize (id+16, false);
4526 if (aux_send_bitset[id]) {
4527 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4529 aux_send_bitset[id] = true;
4533 Session::mark_return_id (uint32_t id)
4535 if (id >= return_bitset.size()) {
4536 return_bitset.resize (id+16, false);
4538 if (return_bitset[id]) {
4539 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4541 return_bitset[id] = true;
4545 Session::mark_insert_id (uint32_t id)
4547 if (id >= insert_bitset.size()) {
4548 insert_bitset.resize (id+16, false);
4550 if (insert_bitset[id]) {
4551 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4553 insert_bitset[id] = true;
4557 Session::unmark_send_id (uint32_t id)
4559 if (id < send_bitset.size()) {
4560 send_bitset[id] = false;
4565 Session::unmark_aux_send_id (uint32_t id)
4567 if (id < aux_send_bitset.size()) {
4568 aux_send_bitset[id] = false;
4573 Session::unmark_return_id (uint32_t id)
4575 if (id < return_bitset.size()) {
4576 return_bitset[id] = false;
4581 Session::unmark_insert_id (uint32_t id)
4583 if (id < insert_bitset.size()) {
4584 insert_bitset[id] = false;
4589 Session::reset_native_file_format ()
4591 boost::shared_ptr<RouteList> rl = routes.reader ();
4592 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4593 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4595 /* don't save state as we do this, there's no point
4598 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4599 tr->reset_write_sources (false);
4600 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4606 Session::route_name_unique (string n) const
4608 boost::shared_ptr<RouteList> r = routes.reader ();
4610 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4611 if ((*i)->name() == n) {
4620 Session::route_name_internal (string n) const
4622 if (auditioner && auditioner->name() == n) {
4626 if (_click_io && _click_io->name() == n) {
4634 Session::freeze_all (InterThreadInfo& itt)
4636 boost::shared_ptr<RouteList> r = routes.reader ();
4638 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4640 boost::shared_ptr<Track> t;
4642 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4643 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4653 boost::shared_ptr<Region>
4654 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
4655 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4656 InterThreadInfo& itt,
4657 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4658 bool for_export, bool for_freeze)
4660 boost::shared_ptr<Region> result;
4661 boost::shared_ptr<Playlist> playlist;
4662 boost::shared_ptr<Source> source;
4663 ChanCount diskstream_channels (track.n_channels());
4664 framepos_t position;
4665 framecnt_t this_chunk;
4667 framepos_t latency_skip;
4669 framepos_t len = end - start;
4670 bool need_block_size_reset = false;
4671 ChanCount const max_proc = track.max_processor_streams ();
4672 string legal_playlist_name;
4673 string possible_path;
4676 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4677 end, start) << endmsg;
4681 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
4682 include_endpoint, for_export, for_freeze);
4684 if (diskstream_channels.n(track.data_type()) < 1) {
4685 error << _("Cannot write a range with no data.") << endmsg;
4689 // block all process callback handling
4691 block_processing ();
4694 // synchronize with AudioEngine::process_callback()
4695 // make sure processing is not currently running
4696 // and processing_blocked() is honored before
4697 // acquiring thread buffers
4698 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4701 _bounce_processing_active = true;
4703 /* call tree *MUST* hold route_lock */
4705 if ((playlist = track.playlist()) == 0) {
4709 legal_playlist_name = legalize_for_path (playlist->name());
4711 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
4713 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
4714 string path = ((track.data_type() == DataType::AUDIO)
4715 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
4716 : new_midi_source_path (legal_playlist_name));
4723 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
4726 catch (failed_constructor& err) {
4727 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
4731 srcs.push_back (source);
4734 /* tell redirects that care that we are about to use a much larger
4735 * blocksize. this will flush all plugins too, so that they are ready
4736 * to be used for this process.
4739 need_block_size_reset = true;
4740 track.set_block_size (bounce_chunk_size);
4741 _engine.main_thread()->get_buffers ();
4745 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4747 /* create a set of reasonably-sized buffers */
4748 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4749 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4751 buffers.set_count (max_proc);
4753 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4754 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4755 boost::shared_ptr<MidiSource> ms;
4757 afs->prepare_for_peakfile_writes ();
4758 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4759 Source::Lock lock(ms->mutex());
4760 ms->mark_streaming_write_started(lock);
4764 while (to_do && !itt.cancel) {
4766 this_chunk = min (to_do, bounce_chunk_size);
4768 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
4772 start += this_chunk;
4773 to_do -= this_chunk;
4774 itt.progress = (float) (1.0 - ((double) to_do / len));
4776 if (latency_skip >= bounce_chunk_size) {
4777 latency_skip -= bounce_chunk_size;
4781 const framecnt_t current_chunk = this_chunk - latency_skip;
4784 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4785 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4786 boost::shared_ptr<MidiSource> ms;
4789 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4792 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4793 Source::Lock lock(ms->mutex());
4795 const MidiBuffer& buf = buffers.get_midi(0);
4796 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
4797 Evoral::Event<framepos_t> ev = *i;
4798 ev.set_time(ev.time() - position);
4799 ms->append_event_frames(lock, ev, ms->timeline_position());
4806 /* post-roll, pick up delayed processor output */
4807 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4809 while (latency_skip && !itt.cancel) {
4810 this_chunk = min (latency_skip, bounce_chunk_size);
4811 latency_skip -= this_chunk;
4813 buffers.silence (this_chunk, 0);
4814 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
4817 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4818 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4821 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4833 xnow = localtime (&now);
4835 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4836 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4837 boost::shared_ptr<MidiSource> ms;
4840 afs->update_header (position, *xnow, now);
4841 afs->flush_header ();
4842 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
4843 Source::Lock lock(ms->mutex());
4844 ms->mark_streaming_write_completed(lock);
4848 /* construct a region to represent the bounced material */
4852 plist.add (Properties::start, 0);
4853 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4854 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4856 result = RegionFactory::create (srcs, plist);
4862 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4863 (*src)->mark_for_remove ();
4864 (*src)->drop_references ();
4868 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4869 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4872 afs->done_with_peakfile_writes ();
4876 _bounce_processing_active = false;
4878 if (need_block_size_reset) {
4879 _engine.main_thread()->drop_buffers ();
4880 track.set_block_size (get_block_size());
4883 unblock_processing ();
4889 Session::gain_automation_buffer() const
4891 return ProcessThread::gain_automation_buffer ();
4895 Session::trim_automation_buffer() const
4897 return ProcessThread::trim_automation_buffer ();
4901 Session::send_gain_automation_buffer() const
4903 return ProcessThread::send_gain_automation_buffer ();
4907 Session::pan_automation_buffer() const
4909 return ProcessThread::pan_automation_buffer ();
4913 Session::get_silent_buffers (ChanCount count)
4915 return ProcessThread::get_silent_buffers (count);
4919 Session::get_scratch_buffers (ChanCount count, bool silence)
4921 return ProcessThread::get_scratch_buffers (count, silence);
4925 Session::get_route_buffers (ChanCount count, bool silence)
4927 return ProcessThread::get_route_buffers (count, silence);
4932 Session::get_mix_buffers (ChanCount count)
4934 return ProcessThread::get_mix_buffers (count);
4938 Session::ntracks () const
4941 boost::shared_ptr<RouteList> r = routes.reader ();
4943 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4944 if (boost::dynamic_pointer_cast<Track> (*i)) {
4953 Session::nbusses () const
4956 boost::shared_ptr<RouteList> r = routes.reader ();
4958 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4959 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4968 Session::add_automation_list(AutomationList *al)
4970 automation_lists[al->id()] = al;
4973 /** @return true if there is at least one record-enabled track, otherwise false */
4975 Session::have_rec_enabled_track () const
4977 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4980 /** Update the state of our rec-enabled tracks flag */
4982 Session::update_have_rec_enabled_track ()
4984 boost::shared_ptr<RouteList> rl = routes.reader ();
4985 RouteList::iterator i = rl->begin();
4986 while (i != rl->end ()) {
4988 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4989 if (tr && tr->record_enabled ()) {
4996 int const old = g_atomic_int_get (&_have_rec_enabled_track);
4998 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5000 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5001 RecordStateChanged (); /* EMIT SIGNAL */
5006 Session::listen_position_changed ()
5008 boost::shared_ptr<RouteList> r = routes.reader ();
5010 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5011 (*i)->listen_position_changed ();
5016 Session::solo_control_mode_changed ()
5018 /* cancel all solo or all listen when solo control mode changes */
5021 set_solo (get_routes(), false);
5022 } else if (listening()) {
5023 set_listen (get_routes(), false);
5027 /** Called when a property of one of our route groups changes */
5029 Session::route_group_property_changed (RouteGroup* rg)
5031 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
5034 /** Called when a route is added to one of our route groups */
5036 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5038 RouteAddedToRouteGroup (rg, r);
5041 /** Called when a route is removed from one of our route groups */
5043 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5045 RouteRemovedFromRouteGroup (rg, r);
5048 boost::shared_ptr<RouteList>
5049 Session::get_tracks () const
5051 boost::shared_ptr<RouteList> rl = routes.reader ();
5052 boost::shared_ptr<RouteList> tl (new RouteList);
5054 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
5055 if (boost::dynamic_pointer_cast<Track> (*r)) {
5056 if (!(*r)->is_auditioner()) {
5064 boost::shared_ptr<RouteList>
5065 Session::get_routes_with_regions_at (framepos_t const p) const
5067 boost::shared_ptr<RouteList> r = routes.reader ();
5068 boost::shared_ptr<RouteList> rl (new RouteList);
5070 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5071 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5076 boost::shared_ptr<Playlist> pl = tr->playlist ();
5081 if (pl->has_region_at (p)) {
5090 Session::goto_end ()
5092 if (_session_range_location) {
5093 request_locate (_session_range_location->end(), false);
5095 request_locate (0, false);
5100 Session::goto_start ()
5102 if (_session_range_location) {
5103 request_locate (_session_range_location->start(), false);
5105 request_locate (0, false);
5110 Session::current_start_frame () const
5112 return _session_range_location ? _session_range_location->start() : 0;
5116 Session::current_end_frame () const
5118 return _session_range_location ? _session_range_location->end() : 0;
5122 Session::add_session_range_location (framepos_t start, framepos_t end)
5124 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
5125 _locations->add (_session_range_location);
5129 Session::step_edit_status_change (bool yn)
5135 send = (_step_editors == 0);
5140 send = (_step_editors == 1);
5143 if (_step_editors > 0) {
5149 StepEditStatusChange (val);
5155 Session::start_time_changed (framepos_t old)
5157 /* Update the auto loop range to match the session range
5158 (unless the auto loop range has been changed by the user)
5161 Location* s = _locations->session_range_location ();
5166 Location* l = _locations->auto_loop_location ();
5168 if (l && l->start() == old) {
5169 l->set_start (s->start(), true);
5174 Session::end_time_changed (framepos_t old)
5176 /* Update the auto loop range to match the session range
5177 (unless the auto loop range has been changed by the user)
5180 Location* s = _locations->session_range_location ();
5185 Location* l = _locations->auto_loop_location ();
5187 if (l && l->end() == old) {
5188 l->set_end (s->end(), true);
5192 std::vector<std::string>
5193 Session::source_search_path (DataType type) const
5197 if (session_dirs.size() == 1) {
5199 case DataType::AUDIO:
5200 sp.push_back (_session_dir->sound_path());
5202 case DataType::MIDI:
5203 sp.push_back (_session_dir->midi_path());
5207 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5208 SessionDirectory sdir (i->path);
5210 case DataType::AUDIO:
5211 sp.push_back (sdir.sound_path());
5213 case DataType::MIDI:
5214 sp.push_back (sdir.midi_path());
5220 if (type == DataType::AUDIO) {
5221 const string sound_path_2X = _session_dir->sound_path_2X();
5222 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
5223 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
5224 sp.push_back (sound_path_2X);
5229 // now check the explicit (possibly user-specified) search path
5232 case DataType::AUDIO:
5233 sp += Searchpath(config.get_audio_search_path ());
5235 case DataType::MIDI:
5236 sp += Searchpath(config.get_midi_search_path ());
5244 Session::ensure_search_path_includes (const string& path, DataType type)
5253 case DataType::AUDIO:
5254 sp += Searchpath(config.get_audio_search_path ());
5256 case DataType::MIDI:
5257 sp += Searchpath (config.get_midi_search_path ());
5261 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
5262 /* No need to add this new directory if it has the same inode as
5263 an existing one; checking inode rather than name prevents duplicated
5264 directories when we are using symlinks.
5266 On Windows, I think we could just do if (*i == path) here.
5268 if (PBD::equivalent_paths (*i, path)) {
5276 case DataType::AUDIO:
5277 config.set_audio_search_path (sp.to_string());
5279 case DataType::MIDI:
5280 config.set_midi_search_path (sp.to_string());
5286 Session::remove_dir_from_search_path (const string& dir, DataType type)
5291 case DataType::AUDIO:
5292 sp = Searchpath(config.get_audio_search_path ());
5294 case DataType::MIDI:
5295 sp = Searchpath (config.get_midi_search_path ());
5302 case DataType::AUDIO:
5303 config.set_audio_search_path (sp.to_string());
5305 case DataType::MIDI:
5306 config.set_midi_search_path (sp.to_string());
5312 boost::shared_ptr<Speakers>
5313 Session::get_speakers()
5319 Session::unknown_processors () const
5323 boost::shared_ptr<RouteList> r = routes.reader ();
5324 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5325 list<string> t = (*i)->unknown_processors ();
5326 copy (t.begin(), t.end(), back_inserter (p));
5336 Session::update_latency (bool playback)
5338 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
5340 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
5344 boost::shared_ptr<RouteList> r = routes.reader ();
5345 framecnt_t max_latency = 0;
5348 /* reverse the list so that we work backwards from the last route to run to the first */
5349 RouteList* rl = routes.reader().get();
5350 r.reset (new RouteList (*rl));
5351 reverse (r->begin(), r->end());
5354 /* compute actual latency values for the given direction and store them all in per-port
5355 structures. this will also publish the same values (to JACK) so that computation of latency
5356 for routes can consistently use public latency values.
5359 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5360 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
5363 /* because we latency compensate playback, our published playback latencies should
5364 be the same for all output ports - all material played back by ardour has
5365 the same latency, whether its caused by plugins or by latency compensation. since
5366 these may differ from the values computed above, reset all playback port latencies
5370 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
5372 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5373 (*i)->set_public_port_latencies (max_latency, playback);
5378 post_playback_latency ();
5382 post_capture_latency ();
5385 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
5389 Session::post_playback_latency ()
5391 set_worst_playback_latency ();
5393 boost::shared_ptr<RouteList> r = routes.reader ();
5395 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5396 if (!(*i)->is_auditioner() && ((*i)->active())) {
5397 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
5401 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5402 (*i)->set_latency_compensation (_worst_track_latency);
5407 Session::post_capture_latency ()
5409 set_worst_capture_latency ();
5411 /* reflect any changes in capture latencies into capture offsets
5414 boost::shared_ptr<RouteList> rl = routes.reader();
5415 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5416 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5418 tr->set_capture_offset ();
5424 Session::initialize_latencies ()
5427 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5428 update_latency (false);
5429 update_latency (true);
5432 set_worst_io_latencies ();
5436 Session::set_worst_io_latencies ()
5438 set_worst_playback_latency ();
5439 set_worst_capture_latency ();
5443 Session::set_worst_playback_latency ()
5445 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5449 _worst_output_latency = 0;
5451 if (!_engine.connected()) {
5455 boost::shared_ptr<RouteList> r = routes.reader ();
5457 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5458 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
5461 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
5465 Session::set_worst_capture_latency ()
5467 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5471 _worst_input_latency = 0;
5473 if (!_engine.connected()) {
5477 boost::shared_ptr<RouteList> r = routes.reader ();
5479 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5480 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
5483 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
5487 Session::update_latency_compensation (bool force_whole_graph)
5489 bool some_track_latency_changed = false;
5491 if (_state_of_the_state & (InitialConnecting|Deletion)) {
5495 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
5497 _worst_track_latency = 0;
5499 boost::shared_ptr<RouteList> r = routes.reader ();
5501 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5502 if (!(*i)->is_auditioner() && ((*i)->active())) {
5504 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
5505 some_track_latency_changed = true;
5507 _worst_track_latency = max (tl, _worst_track_latency);
5511 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
5512 (some_track_latency_changed ? "yes" : "no")));
5514 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
5516 if (some_track_latency_changed || force_whole_graph) {
5517 _engine.update_latencies ();
5521 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5522 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5526 tr->set_capture_offset ();
5531 Session::session_name_is_legal (const string& path)
5533 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
5535 for (int i = 0; illegal_chars[i]; ++i) {
5536 if (path.find (illegal_chars[i]) != string::npos) {
5537 return illegal_chars[i];
5545 Session::next_control_id () const
5549 /* the monitor bus remote ID is in a different
5550 * "namespace" than regular routes. its existence doesn't
5551 * affect normal (low) numbered routes.
5558 return nroutes() - subtract;
5562 Session::notify_remote_id_change ()
5564 if (deletion_in_progress()) {
5568 switch (Config->get_remote_model()) {
5570 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
5578 Session::sync_order_keys ()
5580 if (deletion_in_progress()) {
5584 /* tell everyone that something has happened to the sort keys
5585 and let them sync up with the change(s)
5586 this will give objects that manage the sort order keys the
5587 opportunity to keep them in sync if they wish to.
5590 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5592 reassign_track_numbers();
5594 Route::SyncOrderKeys (); /* EMIT SIGNAL */
5596 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5600 Session::operation_in_progress (GQuark op) const
5602 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5605 boost::shared_ptr<Port>
5606 Session::ltc_input_port () const
5608 return _ltc_input->nth (0);
5611 boost::shared_ptr<Port>
5612 Session::ltc_output_port () const
5614 return _ltc_output->nth (0);
5618 Session::reconnect_ltc_input ()
5622 string src = Config->get_ltc_source_port();
5624 _ltc_input->disconnect (this);
5626 if (src != _("None") && !src.empty()) {
5627 _ltc_input->nth (0)->connect (src);
5633 Session::reconnect_ltc_output ()
5638 string src = Config->get_ltc_sink_port();
5640 _ltc_output->disconnect (this);
5642 if (src != _("None") && !src.empty()) {
5643 _ltc_output->nth (0)->connect (src);