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/replace_all.h"
50 #include "pbd/unwind.h"
52 #include "ardour/amp.h"
53 #include "ardour/analyser.h"
54 #include "ardour/async_midi_port.h"
55 #include "ardour/audio_buffer.h"
56 #include "ardour/audio_diskstream.h"
57 #include "ardour/audio_port.h"
58 #include "ardour/audio_track.h"
59 #include "ardour/audioengine.h"
60 #include "ardour/audiofilesource.h"
61 #include "ardour/auditioner.h"
62 #include "ardour/buffer_manager.h"
63 #include "ardour/buffer_set.h"
64 #include "ardour/bundle.h"
65 #include "ardour/butler.h"
66 #include "ardour/click.h"
67 #include "ardour/control_protocol_manager.h"
68 #include "ardour/data_type.h"
69 #include "ardour/debug.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
74 #include "ardour/filename_extensions.h"
75 #include "ardour/graph.h"
76 #include "ardour/midiport_manager.h"
77 #include "ardour/scene_changer.h"
78 #include "ardour/midi_track.h"
79 #include "ardour/midi_ui.h"
80 #include "ardour/operations.h"
81 #include "ardour/playlist.h"
82 #include "ardour/plugin.h"
83 #include "ardour/plugin_insert.h"
84 #include "ardour/process_thread.h"
85 #include "ardour/profile.h"
86 #include "ardour/rc_configuration.h"
87 #include "ardour/recent_sessions.h"
88 #include "ardour/region.h"
89 #include "ardour/region_factory.h"
90 #include "ardour/route_graph.h"
91 #include "ardour/route_group.h"
92 #include "ardour/route_sorters.h"
93 #include "ardour/send.h"
94 #include "ardour/session.h"
95 #include "ardour/session_directory.h"
96 #include "ardour/session_playlists.h"
97 #include "ardour/smf_source.h"
98 #include "ardour/source_factory.h"
99 #include "ardour/speakers.h"
100 #include "ardour/tempo.h"
101 #include "ardour/track.h"
102 #include "ardour/user_bundle.h"
103 #include "ardour/utils.h"
105 #include "midi++/port.h"
106 #include "midi++/mmc.h"
117 using namespace ARDOUR;
120 bool Session::_disable_all_loaded_plugins = false;
121 bool Session::_bypass_all_loaded_plugins = false;
123 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
124 PBD::Signal1<void,std::string> Session::Dialog;
125 PBD::Signal0<int> Session::AskAboutPendingState;
126 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
127 PBD::Signal0<void> Session::SendFeedback;
128 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
130 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
131 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
132 PBD::Signal2<void,std::string, std::string> Session::Exported;
133 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
134 PBD::Signal0<void> Session::Quit;
135 PBD::Signal0<void> Session::FeedbackDetected;
136 PBD::Signal0<void> Session::SuccessfulGraphSort;
137 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
139 const framecnt_t Session::bounce_chunk_size = 8192;
140 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
141 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
143 // seconds should be added after the region exceeds end marker
144 #ifdef USE_TRACKS_CODE_FEATURES
145 const uint32_t Session::session_end_shift = 5;
147 const uint32_t Session::session_end_shift = 0;
150 /** @param snapshot_name Snapshot name, without .ardour suffix */
151 Session::Session (AudioEngine &eng,
152 const string& fullpath,
153 const string& snapshot_name,
154 BusProfile* bus_profile,
156 : playlists (new SessionPlaylists)
158 , process_function (&Session::process_with_events)
159 , _bounce_processing_active (false)
160 , waiting_for_sync_offset (false)
161 , _base_frame_rate (0)
162 , _current_frame_rate (0)
163 , _nominal_frame_rate (0)
164 , transport_sub_state (0)
165 , _record_status (Disabled)
166 , _transport_frame (0)
167 , _session_range_location (0)
170 , _transport_speed (0)
171 , _default_transport_speed (1.0)
172 , _last_transport_speed (0)
173 , _target_transport_speed (0.0)
174 , auto_play_legal (false)
175 , _last_slave_transport_frame (0)
176 , maximum_output_latency (0)
177 , _requested_return_frame (-1)
178 , current_block_size (0)
179 , _worst_output_latency (0)
180 , _worst_input_latency (0)
181 , _worst_track_latency (0)
182 , _have_captured (false)
183 , _non_soloed_outs_muted (false)
185 , _solo_isolated_cnt (0)
187 , _was_seamless (Config->get_seamless_loop ())
188 , _under_nsm_control (false)
190 , delta_accumulator_cnt (0)
191 , average_slave_delta (1800) // !!! why 1800 ???
193 , have_first_delta_accumulator (false)
194 , _slave_state (Stopped)
195 , _mtc_active (false)
196 , _ltc_active (false)
197 , post_export_sync (false)
198 , post_export_position (0)
200 , _export_started (false)
201 , _export_rolling (false)
202 , _pre_export_mmc_enabled (false)
203 , _name (snapshot_name)
205 , _send_qf_mtc (false)
206 , _pframes_since_last_mtc (0)
207 , session_midi_feedback (0)
209 , loop_changing (false)
211 , _session_dir (new SessionDirectory (fullpath))
212 , _current_snapshot_name (snapshot_name)
214 , state_was_pending (false)
215 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
217 , _save_queued (false)
218 , _last_roll_location (0)
219 , _last_roll_or_reversal_location (0)
220 , _last_record_location (0)
221 , pending_locate_roll (false)
222 , pending_locate_frame (0)
223 , pending_locate_flush (false)
224 , pending_abort (false)
225 , pending_auto_loop (false)
226 , _butler (new Butler (*this))
227 , _post_transport_work (0)
228 , cumulative_rf_motion (0)
230 , _locations (new Locations (*this))
231 , _ignore_skips_updates (false)
232 , _rt_thread_active (false)
233 , _rt_emit_pending (false)
235 , outbound_mtc_timecode_frame (0)
236 , next_quarter_frame_to_send (-1)
237 , _frames_per_timecode_frame (0)
238 , _frames_per_hour (0)
239 , _timecode_frames_per_hour (0)
240 , last_timecode_valid (false)
241 , last_timecode_when (0)
242 , _send_timecode_update (false)
254 , ltc_timecode_offset (0)
255 , ltc_timecode_negative_offset (false)
256 , midi_control_ui (0)
258 , _all_route_group (new RouteGroup (*this, "all"))
259 , routes (new RouteList)
260 , _adding_routes_in_progress (false)
261 , _reconnecting_routes_in_progress (false)
262 , _route_deletion_in_progress (false)
263 , destructive_index (0)
264 , _track_number_decimals(1)
265 , solo_update_disabled (false)
266 , default_fade_steepness (0)
267 , default_fade_msecs (0)
268 , _total_free_4k_blocks (0)
269 , _total_free_4k_blocks_uncertain (false)
270 , no_questions_about_missing_files (false)
273 , _bundles (new BundleList)
274 , _bundle_xml_node (0)
278 , click_emphasis_data (0)
280 , click_emphasis_length (0)
281 , _clicks_cleared (0)
282 , _play_range (false)
283 , _range_selection (-1,-1)
284 , _object_selection (-1,-1)
286 , first_file_data_format_reset (true)
287 , first_file_header_format_reset (true)
288 , have_looped (false)
289 , _have_rec_enabled_track (false)
290 , _have_rec_disabled_track (true)
292 , _suspend_timecode_transmission (0)
293 , _speakers (new Speakers)
295 , ignore_route_processor_changes (false)
302 pthread_mutex_init (&_rt_emit_mutex, 0);
303 pthread_cond_init (&_rt_emit_cond, 0);
305 pre_engine_init (fullpath);
309 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
311 #ifdef USE_TRACKS_CODE_FEATURES
312 sr = EngineStateController::instance()->get_current_sample_rate();
314 if (ensure_engine (sr)) {
316 throw failed_constructor ();
319 if (create (mix_template, bus_profile)) {
321 throw failed_constructor ();
324 /* if a mix template was provided, then ::create() will
325 * have copied it into the session and we need to load it
326 * so that we have the state ready for ::set_state()
327 * after the engine is started.
329 * Note that we do NOT try to get the sample rate from
330 * the template at this time, though doing so would
331 * be easy if we decided this was an appropriate part
335 if (!mix_template.empty()) {
336 if (load_state (_current_snapshot_name)) {
337 throw failed_constructor ();
339 store_recent_templates (mix_template);
342 /* load default session properties - if any */
347 if (load_state (_current_snapshot_name)) {
348 throw failed_constructor ();
351 /* try to get sample rate from XML state so that we
352 * can influence the SR if we set up the audio
357 const XMLProperty* prop;
358 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
359 sr = atoi (prop->value());
363 if (ensure_engine (sr)) {
365 throw failed_constructor ();
369 if (post_engine_init ()) {
371 throw failed_constructor ();
374 store_recent_sessions (_name, _path);
376 bool was_dirty = dirty();
378 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
380 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
381 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
384 DirtyChanged (); /* EMIT SIGNAL */
387 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
388 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
390 emit_thread_start ();
392 /* hook us up to the engine since we are now completely constructed */
394 BootMessage (_("Connect to engine"));
396 _engine.set_session (this);
397 _engine.reset_timebase ();
399 #ifdef USE_TRACKS_CODE_FEATURES
401 EngineStateController::instance()->set_session(this);
404 if ( ARDOUR::Profile->get_trx () ) {
406 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
407 * each available input must have corresponding track when session starts.
410 uint32_t how_many (0);
412 std::vector<std::string> inputs;
413 EngineStateController::instance()->get_physical_audio_inputs(inputs);
415 how_many = inputs.size();
417 list<boost::shared_ptr<AudioTrack> > tracks;
419 // Track names after driver
420 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
421 string track_name = "";
422 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
424 track_name = inputs[i];
425 replace_all (track_name, "system:capture", "");
427 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
428 tracks.insert(tracks.begin(), single_track.front());
430 } else { // Default track names
431 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
434 if (tracks.size() != how_many) {
436 throw failed_constructor ();
445 BootMessage (_("Session loading complete"));
457 Session::ensure_engine (uint32_t desired_sample_rate)
459 if (_engine.current_backend() == 0) {
460 /* backend is unknown ... */
461 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
462 if (r.get_value_or (-1) != 0) {
465 } else if (_engine.setup_required()) {
466 /* backend is known, but setup is needed */
467 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
468 if (r.get_value_or (-1) != 0) {
471 } else if (!_engine.running()) {
472 if (_engine.start()) {
477 /* at this point the engine should be running
480 if (!_engine.running()) {
484 return immediately_post_engine ();
489 Session::immediately_post_engine ()
491 /* Do various initializations that should take place directly after we
492 * know that the engine is running, but before we either create a
493 * session or set state for an existing one.
496 if (how_many_dsp_threads () > 1) {
497 /* For now, only create the graph if we are using >1 DSP threads, as
498 it is a bit slower than the old code with 1 thread.
500 _process_graph.reset (new Graph (*this));
503 /* every time we reconnect, recompute worst case output latencies */
505 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
507 if (synced_to_engine()) {
508 _engine.transport_stop ();
511 if (config.get_jack_time_master()) {
512 _engine.transport_locate (_transport_frame);
516 BootMessage (_("Set up LTC"));
518 BootMessage (_("Set up Click"));
520 BootMessage (_("Set up standard connections"));
524 catch (failed_constructor& err) {
528 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
530 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
538 vector<void*> debug_pointers;
540 /* if we got to here, leaving pending capture state around
544 remove_pending_capture_state ();
546 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
548 /* disconnect from any and all signals that we are connected to */
552 _engine.remove_session ();
554 #ifdef USE_TRACKS_CODE_FEATURES
555 EngineStateController::instance()->remove_session();
558 /* deregister all ports - there will be no process or any other
559 * callbacks from the engine any more.
562 Port::PortDrop (); /* EMIT SIGNAL */
566 /* clear history so that no references to objects are held any more */
570 /* clear state tree so that no references to objects are held any more */
575 /* reset dynamic state version back to default */
577 Stateful::loading_state_version = 0;
579 _butler->drop_references ();
583 delete _all_route_group;
585 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
586 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
590 if (click_data != default_click) {
591 delete [] click_data;
594 if (click_emphasis_data != default_click_emphasis) {
595 delete [] click_emphasis_data;
600 /* need to remove auditioner before monitoring section
601 * otherwise it is re-connected */
604 /* drop references to routes held by the monitoring section
605 * specifically _monitor_out aux/listen references */
606 remove_monitor_section();
608 /* clear out any pending dead wood from RCU managed objects */
613 AudioDiskstream::free_working_buffers();
615 /* tell everyone who is still standing that we're about to die */
618 /* tell everyone to drop references and delete objects as we go */
620 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
621 RegionFactory::delete_all_regions ();
623 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
625 /* reset these three references to special routes before we do the usual route delete thing */
627 _master_out.reset ();
628 _monitor_out.reset ();
631 RCUWriter<RouteList> writer (routes);
632 boost::shared_ptr<RouteList> r = writer.get_copy ();
634 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
635 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
636 (*i)->drop_references ();
640 /* writer goes out of scope and updates master */
645 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
646 Glib::Threads::Mutex::Lock lm (source_lock);
647 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
648 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
649 i->second->drop_references ();
655 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
658 emit_thread_terminate ();
660 pthread_cond_destroy (&_rt_emit_cond);
661 pthread_mutex_destroy (&_rt_emit_mutex);
663 delete _scene_changer; _scene_changer = 0;
664 delete midi_control_ui; midi_control_ui = 0;
666 delete _mmc; _mmc = 0;
667 delete _midi_ports; _midi_ports = 0;
668 delete _locations; _locations = 0;
672 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
674 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
675 boost_debug_list_ptrs ();
680 Session::setup_ltc ()
684 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
685 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
687 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
688 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
691 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
692 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
694 reconnect_ltc_input ();
697 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
698 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
701 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
702 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
704 reconnect_ltc_output ();
707 /* fix up names of LTC ports because we don't want the normal
708 * IO style of NAME/TYPE-{in,out}N
711 _ltc_input->nth (0)->set_name (X_("LTC-in"));
712 _ltc_output->nth (0)->set_name (X_("LTC-out"));
716 Session::setup_click ()
719 _click_io.reset (new ClickIO (*this, X_("Click")));
720 _click_gain.reset (new Amp (*this));
721 _click_gain->activate ();
723 setup_click_state (state_tree->root());
725 setup_click_state (0);
730 Session::setup_click_state (const XMLNode* node)
732 const XMLNode* child = 0;
734 if (node && (child = find_named_node (*node, "Click")) != 0) {
736 /* existing state for Click */
739 if (Stateful::loading_state_version < 3000) {
740 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
742 const XMLNodeList& children (child->children());
743 XMLNodeList::const_iterator i = children.begin();
744 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
746 if (i != children.end()) {
747 c = _click_gain->set_state (**i, Stateful::loading_state_version);
753 _clicking = Config->get_clicking ();
757 error << _("could not setup Click I/O") << endmsg;
764 /* default state for Click: dual-mono to first 2 physical outputs */
767 _engine.get_physical_outputs (DataType::AUDIO, outs);
769 for (uint32_t physport = 0; physport < 2; ++physport) {
770 if (outs.size() > physport) {
771 if (_click_io->add_port (outs[physport], this)) {
772 // relax, even though its an error
777 if (_click_io->n_ports () > ChanCount::ZERO) {
778 _clicking = Config->get_clicking ();
784 Session::setup_bundles ()
788 RCUWriter<BundleList> writer (_bundles);
789 boost::shared_ptr<BundleList> b = writer.get_copy ();
790 for (BundleList::iterator i = b->begin(); i != b->end();) {
791 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
799 vector<string> inputs[DataType::num_types];
800 vector<string> outputs[DataType::num_types];
801 for (uint32_t i = 0; i < DataType::num_types; ++i) {
802 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
803 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
806 /* Create a set of Bundle objects that map
807 to the physical I/O currently available. We create both
808 mono and stereo bundles, so that the common cases of mono
809 and stereo tracks get bundles to put in their mixer strip
810 in / out menus. There may be a nicer way of achieving that;
811 it doesn't really scale that well to higher channel counts
814 /* mono output bundles */
816 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
818 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
820 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
822 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
825 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
826 c->add_channel (_("mono"), DataType::AUDIO);
827 c->set_port (0, outputs[DataType::AUDIO][np]);
829 add_bundle (c, false);
832 /* stereo output bundles */
834 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
835 if (np + 1 < outputs[DataType::AUDIO].size()) {
837 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
838 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
839 c->add_channel (_("L"), DataType::AUDIO);
840 c->set_port (0, outputs[DataType::AUDIO][np]);
841 c->add_channel (_("R"), DataType::AUDIO);
842 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
844 add_bundle (c, false);
848 /* mono input bundles */
850 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
852 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
854 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
856 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
859 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
860 c->add_channel (_("mono"), DataType::AUDIO);
861 c->set_port (0, inputs[DataType::AUDIO][np]);
863 add_bundle (c, false);
866 /* stereo input bundles */
868 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
869 if (np + 1 < inputs[DataType::AUDIO].size()) {
871 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
873 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
874 c->add_channel (_("L"), DataType::AUDIO);
875 c->set_port (0, inputs[DataType::AUDIO][np]);
876 c->add_channel (_("R"), DataType::AUDIO);
877 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
879 add_bundle (c, false);
883 /* MIDI input bundles */
885 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
886 string n = inputs[DataType::MIDI][np];
887 std::string pn = _engine.get_pretty_name_by_name (n);
891 boost::erase_first (n, X_("alsa_pcm:"));
893 boost::shared_ptr<Bundle> c (new Bundle (n, false));
894 c->add_channel ("", DataType::MIDI);
895 c->set_port (0, inputs[DataType::MIDI][np]);
896 add_bundle (c, false);
899 /* MIDI output bundles */
901 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
902 string n = outputs[DataType::MIDI][np];
903 std::string pn = _engine.get_pretty_name_by_name (n);
907 boost::erase_first (n, X_("alsa_pcm:"));
909 boost::shared_ptr<Bundle> c (new Bundle (n, true));
910 c->add_channel ("", DataType::MIDI);
911 c->set_port (0, outputs[DataType::MIDI][np]);
912 add_bundle (c, false);
915 // we trust the backend to only calls us if there's a change
916 BundleAddedOrRemoved (); /* EMIT SIGNAL */
920 Session::auto_connect_master_bus ()
922 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
926 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
927 // In this case it means "Multi Out" output mode
928 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
932 /* if requested auto-connect the outputs to the first N physical ports.
935 uint32_t limit = _master_out->n_outputs().n_total();
936 vector<string> outputs[DataType::num_types];
938 for (uint32_t i = 0; i < DataType::num_types; ++i) {
939 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
942 for (uint32_t n = 0; n < limit; ++n) {
943 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
945 if (outputs[p->type()].size() > n) {
946 connect_to = outputs[p->type()][n];
949 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
950 if (_master_out->output()->connect (p, connect_to, this)) {
951 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
960 Session::remove_monitor_section ()
962 if (!_monitor_out || Profile->get_trx()) {
966 /* force reversion to Solo-In-Place */
967 Config->set_solo_control_is_listen_control (false);
969 /* if we are auditioning, cancel it ... this is a workaround
970 to a problem (auditioning does not execute the process graph,
971 which is needed to remove routes when using >1 core for processing)
976 /* Hold process lock while doing this so that we don't hear bits and
977 * pieces of audio as we work on each route.
980 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
982 /* Connect tracks to monitor section. Note that in an
983 existing session, the internal sends will already exist, but we want the
984 routes to notice that they connect to the control out specifically.
988 boost::shared_ptr<RouteList> r = routes.reader ();
989 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
991 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
993 if ((*x)->is_monitor()) {
995 } else if ((*x)->is_master()) {
998 (*x)->remove_aux_or_listen (_monitor_out);
1003 remove_route (_monitor_out);
1004 auto_connect_master_bus ();
1007 auditioner->connect ();
1012 Session::add_monitor_section ()
1016 if (_monitor_out || !_master_out || Profile->get_trx()) {
1020 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1026 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1027 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
1030 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1031 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1032 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1036 add_routes (rl, false, false, false);
1038 assert (_monitor_out);
1040 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1041 are undefined, at best.
1044 uint32_t limit = _monitor_out->n_inputs().n_audio();
1048 /* connect the inputs to the master bus outputs. this
1049 * represents a separate data feed from the internal sends from
1050 * each route. as of jan 2011, it allows the monitor section to
1051 * conditionally ignore either the internal sends or the normal
1052 * input feed, but we should really find a better way to do
1056 _master_out->output()->disconnect (this);
1058 for (uint32_t n = 0; n < limit; ++n) {
1059 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1060 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1063 string connect_to = o->name();
1064 if (_monitor_out->input()->connect (p, connect_to, this)) {
1065 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1073 /* if monitor section is not connected, connect it to physical outs
1076 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
1078 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1080 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1083 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1085 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1086 Config->get_monitor_bus_preferred_bundle())
1092 /* Monitor bus is audio only */
1094 vector<string> outputs[DataType::num_types];
1096 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1097 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1100 uint32_t mod = outputs[DataType::AUDIO].size();
1101 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1105 for (uint32_t n = 0; n < limit; ++n) {
1107 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1109 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1110 connect_to = outputs[DataType::AUDIO][n % mod];
1113 if (!connect_to.empty()) {
1114 if (_monitor_out->output()->connect (p, connect_to, this)) {
1115 error << string_compose (
1116 _("cannot connect control output %1 to %2"),
1127 /* Hold process lock while doing this so that we don't hear bits and
1128 * pieces of audio as we work on each route.
1131 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1133 /* Connect tracks to monitor section. Note that in an
1134 existing session, the internal sends will already exist, but we want the
1135 routes to notice that they connect to the control out specifically.
1139 boost::shared_ptr<RouteList> rls = routes.reader ();
1141 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1143 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1145 if ((*x)->is_monitor()) {
1147 } else if ((*x)->is_master()) {
1150 (*x)->enable_monitor_send ();
1155 auditioner->connect ();
1160 Session::reset_monitor_section ()
1162 /* Process lock should be held by the caller.*/
1164 if (!_monitor_out || Profile->get_trx()) {
1168 uint32_t limit = _master_out->n_outputs().n_audio();
1170 /* connect the inputs to the master bus outputs. this
1171 * represents a separate data feed from the internal sends from
1172 * each route. as of jan 2011, it allows the monitor section to
1173 * conditionally ignore either the internal sends or the normal
1174 * input feed, but we should really find a better way to do
1178 _master_out->output()->disconnect (this);
1179 _monitor_out->output()->disconnect (this);
1181 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1182 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1184 for (uint32_t n = 0; n < limit; ++n) {
1185 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1186 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1189 string connect_to = o->name();
1190 if (_monitor_out->input()->connect (p, connect_to, this)) {
1191 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1198 /* connect monitor section to physical outs
1201 if (Config->get_auto_connect_standard_busses()) {
1203 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1205 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1208 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1210 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1211 Config->get_monitor_bus_preferred_bundle())
1217 /* Monitor bus is audio only */
1219 vector<string> outputs[DataType::num_types];
1221 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1222 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1225 uint32_t mod = outputs[DataType::AUDIO].size();
1226 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1230 for (uint32_t n = 0; n < limit; ++n) {
1232 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1234 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1235 connect_to = outputs[DataType::AUDIO][n % mod];
1238 if (!connect_to.empty()) {
1239 if (_monitor_out->output()->connect (p, connect_to, this)) {
1240 error << string_compose (
1241 _("cannot connect control output %1 to %2"),
1252 /* Connect tracks to monitor section. Note that in an
1253 existing session, the internal sends will already exist, but we want the
1254 routes to notice that they connect to the control out specifically.
1258 boost::shared_ptr<RouteList> rls = routes.reader ();
1260 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1262 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1264 if ((*x)->is_monitor()) {
1266 } else if ((*x)->is_master()) {
1269 (*x)->enable_monitor_send ();
1275 Session::hookup_io ()
1277 /* stop graph reordering notifications from
1278 causing resorts, etc.
1281 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1285 /* we delay creating the auditioner till now because
1286 it makes its own connections to ports.
1290 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1292 throw failed_constructor ();
1294 a->use_new_diskstream ();
1298 catch (failed_constructor& err) {
1299 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1303 /* load bundles, which we may have postponed earlier on */
1304 if (_bundle_xml_node) {
1305 load_bundles (*_bundle_xml_node);
1306 delete _bundle_xml_node;
1309 /* Tell all IO objects to connect themselves together */
1311 IO::enable_connecting ();
1313 /* Now tell all "floating" ports to connect to whatever
1314 they should be connected to.
1317 AudioEngine::instance()->reconnect_ports ();
1319 /* Anyone who cares about input state, wake up and do something */
1321 IOConnectionsComplete (); /* EMIT SIGNAL */
1323 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1325 /* now handle the whole enchilada as if it was one
1326 graph reorder event.
1331 /* update the full solo state, which can't be
1332 correctly determined on a per-route basis, but
1333 needs the global overview that only the session
1337 update_route_solo_state ();
1341 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1343 boost::shared_ptr<Track> track = wp.lock ();
1348 boost::shared_ptr<Playlist> playlist;
1350 if ((playlist = track->playlist()) != 0) {
1351 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1352 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1353 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1358 Session::record_enabling_legal () const
1360 /* this used to be in here, but survey says.... we don't need to restrict it */
1361 // if (record_status() == Recording) {
1365 if (Config->get_all_safe()) {
1372 Session::set_track_monitor_input_status (bool yn)
1374 boost::shared_ptr<RouteList> rl = routes.reader ();
1375 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1376 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1377 if (tr && tr->record_enabled ()) {
1378 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1379 tr->request_input_monitoring (yn);
1385 Session::auto_punch_start_changed (Location* location)
1387 replace_event (SessionEvent::PunchIn, location->start());
1389 if (get_record_enabled() && config.get_punch_in()) {
1390 /* capture start has been changed, so save new pending state */
1391 save_state ("", true);
1396 Session::auto_punch_end_changed (Location* location)
1398 framepos_t when_to_stop = location->end();
1399 // when_to_stop += _worst_output_latency + _worst_input_latency;
1400 replace_event (SessionEvent::PunchOut, when_to_stop);
1404 Session::auto_punch_changed (Location* location)
1406 framepos_t when_to_stop = location->end();
1408 replace_event (SessionEvent::PunchIn, location->start());
1409 //when_to_stop += _worst_output_latency + _worst_input_latency;
1410 replace_event (SessionEvent::PunchOut, when_to_stop);
1413 /** @param loc A loop location.
1414 * @param pos Filled in with the start time of the required fade-out (in session frames).
1415 * @param length Filled in with the length of the required fade-out.
1418 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1420 pos = max (loc->start(), loc->end() - 64);
1421 length = loc->end() - pos;
1425 Session::auto_loop_changed (Location* location)
1427 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1430 auto_loop_declick_range (location, dcp, dcl);
1432 if (transport_rolling() && play_loop) {
1434 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1436 // if (_transport_frame > location->end()) {
1438 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1439 // relocate to beginning of loop
1440 clear_events (SessionEvent::LocateRoll);
1442 request_locate (location->start(), true);
1445 else if (Config->get_seamless_loop() && !loop_changing) {
1447 // schedule a locate-roll to refill the diskstreams at the
1448 // previous loop end
1449 loop_changing = true;
1451 if (location->end() > last_loopend) {
1452 clear_events (SessionEvent::LocateRoll);
1453 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1459 clear_events (SessionEvent::AutoLoopDeclick);
1460 clear_events (SessionEvent::AutoLoop);
1463 /* possibly move playhead if not rolling; if we are rolling we'll move
1464 to the loop start on stop if that is appropriate.
1469 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1470 if (pos == location->start()) {
1471 request_locate (pos);
1476 last_loopend = location->end();
1481 Session::set_auto_punch_location (Location* location)
1485 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1486 punch_connections.drop_connections();
1487 existing->set_auto_punch (false, this);
1488 remove_event (existing->start(), SessionEvent::PunchIn);
1489 clear_events (SessionEvent::PunchOut);
1490 auto_punch_location_changed (0);
1495 if (location == 0) {
1499 if (location->end() <= location->start()) {
1500 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1504 punch_connections.drop_connections ();
1506 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1507 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1508 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1510 location->set_auto_punch (true, this);
1512 auto_punch_changed (location);
1514 auto_punch_location_changed (location);
1518 Session::set_session_extents (framepos_t start, framepos_t end)
1521 if ((existing = _locations->session_range_location()) == 0) {
1522 //if there is no existing session, we need to make a new session location (should never happen)
1523 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1527 error << _("Session: you can't use that location for session start/end)") << endmsg;
1531 existing->set( start, end );
1537 Session::set_auto_loop_location (Location* location)
1541 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1542 loop_connections.drop_connections ();
1543 existing->set_auto_loop (false, this);
1544 remove_event (existing->end(), SessionEvent::AutoLoop);
1547 auto_loop_declick_range (existing, dcp, dcl);
1548 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1549 auto_loop_location_changed (0);
1554 if (location == 0) {
1558 if (location->end() <= location->start()) {
1559 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1563 last_loopend = location->end();
1565 loop_connections.drop_connections ();
1567 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1568 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1569 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1570 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1572 location->set_auto_loop (true, this);
1574 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1575 // set all tracks to use internal looping
1576 boost::shared_ptr<RouteList> rl = routes.reader ();
1577 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1578 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1579 if (tr && !tr->hidden()) {
1580 tr->set_loop (location);
1585 /* take care of our stuff first */
1587 auto_loop_changed (location);
1589 /* now tell everyone else */
1591 auto_loop_location_changed (location);
1595 Session::update_marks (Location*)
1601 Session::update_skips (Location* loc, bool consolidate)
1603 if (_ignore_skips_updates) {
1607 Locations::LocationList skips;
1610 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1611 consolidate_skips (loc);
1614 sync_locations_to_skips ();
1620 Session::consolidate_skips (Location* loc)
1622 Locations::LocationList all_locations = _locations->list ();
1624 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1626 if (!(*l)->is_skip ()) {
1631 /* don't test against self */
1638 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1639 case Evoral::OverlapInternal:
1640 case Evoral::OverlapExternal:
1641 case Evoral::OverlapStart:
1642 case Evoral::OverlapEnd:
1643 /* adjust new location to cover existing one */
1644 loc->set_start (min (loc->start(), (*l)->start()));
1645 loc->set_end (max (loc->end(), (*l)->end()));
1646 /* we don't need this one any more */
1647 _locations->remove (*l);
1648 /* the location has been deleted, so remove reference to it in our local list */
1649 l = all_locations.erase (l);
1652 case Evoral::OverlapNone:
1660 Session::sync_locations_to_skips ()
1662 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1663 * Session::_sync_locations_to_skips() from the audioengine thread.
1665 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1669 Session::_sync_locations_to_skips ()
1671 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1673 Locations::LocationList const & locs (_locations->list());
1675 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1677 Location* location = *i;
1679 if (location->is_skip() && location->is_skipping()) {
1680 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1688 Session::location_added (Location *location)
1690 if (location->is_auto_punch()) {
1691 set_auto_punch_location (location);
1694 if (location->is_auto_loop()) {
1695 set_auto_loop_location (location);
1698 if (location->is_session_range()) {
1699 /* no need for any signal handling or event setting with the session range,
1700 because we keep a direct reference to it and use its start/end directly.
1702 _session_range_location = location;
1705 if (location->is_mark()) {
1706 /* listen for per-location signals that require us to do any * global updates for marks */
1708 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1709 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1710 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1711 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1714 if (location->is_skip()) {
1715 /* listen for per-location signals that require us to update skip-locate events */
1717 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1718 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1719 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1720 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1722 update_skips (location, true);
1729 Session::location_removed (Location *location)
1731 if (location->is_auto_loop()) {
1732 set_auto_loop_location (0);
1733 set_track_loop (false);
1736 if (location->is_auto_punch()) {
1737 set_auto_punch_location (0);
1740 if (location->is_session_range()) {
1741 /* this is never supposed to happen */
1742 error << _("programming error: session range removed!") << endl;
1745 if (location->is_skip()) {
1747 update_skips (location, false);
1754 Session::locations_changed ()
1756 _locations->apply (*this, &Session::_locations_changed);
1760 Session::_locations_changed (const Locations::LocationList& locations)
1762 /* There was some mass-change in the Locations object.
1764 We might be re-adding a location here but it doesn't actually matter
1765 for all the locations that the Session takes an interest in.
1769 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1770 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1771 location_added (*i);
1775 update_skips (NULL, false);
1779 Session::enable_record ()
1781 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1782 /* no recording at anything except normal speed */
1787 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1789 if (rs == Recording) {
1793 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1795 _last_record_location = _transport_frame;
1796 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1798 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1799 set_track_monitor_input_status (true);
1802 RecordStateChanged ();
1809 Session::disable_record (bool rt_context, bool force)
1813 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1815 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1816 g_atomic_int_set (&_record_status, Disabled);
1817 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1819 if (rs == Recording) {
1820 g_atomic_int_set (&_record_status, Enabled);
1824 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1825 set_track_monitor_input_status (false);
1828 RecordStateChanged (); /* emit signal */
1831 remove_pending_capture_state ();
1837 Session::step_back_from_record ()
1839 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1841 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1842 set_track_monitor_input_status (false);
1845 RecordStateChanged (); /* emit signal */
1850 Session::maybe_enable_record ()
1852 if (_step_editors > 0) {
1856 g_atomic_int_set (&_record_status, Enabled);
1858 /* This function is currently called from somewhere other than an RT thread.
1859 This save_state() call therefore doesn't impact anything. Doing it here
1860 means that we save pending state of which sources the next record will use,
1861 which gives us some chance of recovering from a crash during the record.
1864 save_state ("", true);
1866 if (Config->get_loop_is_mode()) {
1867 /* makes no sense to use loop play as mode when recording */
1868 request_play_loop (false);
1871 if (_transport_speed) {
1872 if (!config.get_punch_in()) {
1876 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1877 RecordStateChanged (); /* EMIT SIGNAL */
1884 Session::audible_frame () const
1890 offset = worst_playback_latency ();
1892 if (synced_to_engine()) {
1893 /* Note: this is basically just sync-to-JACK */
1894 tf = _engine.transport_frame();
1896 tf = _transport_frame;
1901 if (!non_realtime_work_pending()) {
1905 /* Check to see if we have passed the first guaranteed
1906 audible frame past our last start position. if not,
1907 return that last start point because in terms
1908 of audible frames, we have not moved yet.
1910 `Start position' in this context means the time we last
1911 either started, located, or changed transport direction.
1914 if (_transport_speed > 0.0f) {
1916 if (!play_loop || !have_looped) {
1917 if (tf < _last_roll_or_reversal_location + offset) {
1918 return _last_roll_or_reversal_location;
1926 } else if (_transport_speed < 0.0f) {
1928 /* XXX wot? no backward looping? */
1930 if (tf > _last_roll_or_reversal_location - offset) {
1931 return _last_roll_or_reversal_location;
1943 Session::set_frame_rate (framecnt_t frames_per_second)
1945 /** \fn void Session::set_frame_size(framecnt_t)
1946 the AudioEngine object that calls this guarantees
1947 that it will not be called while we are also in
1948 ::process(). Its fine to do things that block
1952 _base_frame_rate = frames_per_second;
1953 _nominal_frame_rate = frames_per_second;
1958 reset_write_sources (false);
1960 // XXX we need some equivalent to this, somehow
1961 // SndFileSource::setup_standard_crossfades (frames_per_second);
1965 /* XXX need to reset/reinstantiate all LADSPA plugins */
1969 Session::set_block_size (pframes_t nframes)
1971 /* the AudioEngine guarantees
1972 that it will not be called while we are also in
1973 ::process(). It is therefore fine to do things that block
1978 current_block_size = nframes;
1982 boost::shared_ptr<RouteList> r = routes.reader ();
1984 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1985 (*i)->set_block_size (nframes);
1988 boost::shared_ptr<RouteList> rl = routes.reader ();
1989 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1990 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1992 tr->set_block_size (nframes);
1996 set_worst_io_latencies ();
2002 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2004 boost::shared_ptr<Route> r2;
2006 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2007 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2011 /* make a copy of the existing list of routes that feed r1 */
2013 Route::FedBy existing (r1->fed_by());
2015 /* for each route that feeds r1, recurse, marking it as feeding
2019 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2020 if (!(r2 = i->r.lock ())) {
2021 /* (*i) went away, ignore it */
2025 /* r2 is a route that feeds r1 which somehow feeds base. mark
2026 base as being fed by r2
2029 rbase->add_fed_by (r2, i->sends_only);
2033 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2037 if (r1->feeds (r2) && r2->feeds (r1)) {
2041 /* now recurse, so that we can mark base as being fed by
2042 all routes that feed r2
2045 trace_terminal (r2, rbase);
2052 Session::resort_routes ()
2054 /* don't do anything here with signals emitted
2055 by Routes during initial setup or while we
2056 are being destroyed.
2059 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2064 RCUWriter<RouteList> writer (routes);
2065 boost::shared_ptr<RouteList> r = writer.get_copy ();
2066 resort_routes_using (r);
2067 /* writer goes out of scope and forces update */
2071 boost::shared_ptr<RouteList> rl = routes.reader ();
2072 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2073 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2075 const Route::FedBy& fb ((*i)->fed_by());
2077 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2078 boost::shared_ptr<Route> sf = f->r.lock();
2080 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2088 /** This is called whenever we need to rebuild the graph of how we will process
2090 * @param r List of routes, in any order.
2094 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2096 /* We are going to build a directed graph of our routes;
2097 this is where the edges of that graph are put.
2102 /* Go through all routes doing two things:
2104 * 1. Collect the edges of the route graph. Each of these edges
2105 * is a pair of routes, one of which directly feeds the other
2106 * either by a JACK connection or by an internal send.
2108 * 2. Begin the process of making routes aware of which other
2109 * routes directly or indirectly feed them. This information
2110 * is used by the solo code.
2113 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2115 /* Clear out the route's list of direct or indirect feeds */
2116 (*i)->clear_fed_by ();
2118 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2120 bool via_sends_only;
2122 /* See if this *j feeds *i according to the current state of the JACK
2123 connections and internal sends.
2125 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2126 /* add the edge to the graph (part #1) */
2127 edges.add (*j, *i, via_sends_only);
2128 /* tell the route (for part #2) */
2129 (*i)->add_fed_by (*j, via_sends_only);
2134 /* Attempt a topological sort of the route graph */
2135 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2137 if (sorted_routes) {
2138 /* We got a satisfactory topological sort, so there is no feedback;
2141 Note: the process graph rechain does not require a
2142 topologically-sorted list, but hey ho.
2144 if (_process_graph) {
2145 _process_graph->rechain (sorted_routes, edges);
2148 _current_route_graph = edges;
2150 /* Complete the building of the routes' lists of what directly
2151 or indirectly feeds them.
2153 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2154 trace_terminal (*i, *i);
2157 *r = *sorted_routes;
2160 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2161 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2162 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2163 (*i)->name(), (*i)->order_key ()));
2167 SuccessfulGraphSort (); /* EMIT SIGNAL */
2170 /* The topological sort failed, so we have a problem. Tell everyone
2171 and stick to the old graph; this will continue to be processed, so
2172 until the feedback is fixed, what is played back will not quite
2173 reflect what is actually connected. Note also that we do not
2174 do trace_terminal here, as it would fail due to an endless recursion,
2175 so the solo code will think that everything is still connected
2179 FeedbackDetected (); /* EMIT SIGNAL */
2184 /** Find a route name starting with \a base, maybe followed by the
2185 * lowest \a id. \a id will always be added if \a definitely_add_number
2186 * is true on entry; otherwise it will only be added if required
2187 * to make the name unique.
2189 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2190 * The available route name with the lowest ID will be used, and \a id
2191 * will be set to the ID.
2193 * \return false if a route name could not be found, and \a track_name
2194 * and \a id do not reflect a free route name.
2197 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2199 if (!definitely_add_number && route_by_name (base) == 0) {
2200 /* juse use the base */
2206 name = string_compose ("%1 %2", base, id);
2208 if (route_by_name (name) == 0) {
2214 } while (id < (UINT_MAX-1));
2219 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2221 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2223 in = ChanCount::ZERO;
2224 out = ChanCount::ZERO;
2226 boost::shared_ptr<RouteList> r = routes.reader ();
2228 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2229 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2230 if (tr && !tr->is_auditioner()) {
2231 in += tr->n_inputs();
2232 out += tr->n_outputs();
2238 Session::default_track_name_pattern (DataType t)
2241 case DataType::AUDIO:
2242 if (Profile->get_trx()) {
2249 case DataType::MIDI:
2256 /** Caller must not hold process lock
2257 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2258 * @param instrument plugin info for the instrument to insert pre-fader, if any
2260 list<boost::shared_ptr<MidiTrack> >
2261 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2262 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2265 uint32_t track_id = 0;
2267 RouteList new_routes;
2268 list<boost::shared_ptr<MidiTrack> > ret;
2270 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2271 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2274 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2275 error << "cannot find name for new midi track" << endmsg;
2279 boost::shared_ptr<MidiTrack> track;
2282 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2284 if (track->init ()) {
2288 track->use_new_diskstream();
2290 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2291 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2294 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2295 if (track->input()->ensure_io (input, false, this)) {
2296 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2300 if (track->output()->ensure_io (output, false, this)) {
2301 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2306 track->non_realtime_input_change();
2309 route_group->add (track);
2312 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2314 if (Config->get_remote_model() == UserOrdered) {
2315 track->set_remote_control_id (next_control_id());
2318 new_routes.push_back (track);
2319 ret.push_back (track);
2321 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2324 catch (failed_constructor &err) {
2325 error << _("Session: could not create new midi track.") << endmsg;
2329 catch (AudioEngine::PortRegistrationFailure& pfe) {
2331 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;
2339 if (!new_routes.empty()) {
2340 StateProtector sp (this);
2341 if (Profile->get_trx()) {
2342 add_routes (new_routes, false, false, false);
2344 add_routes (new_routes, true, true, false);
2348 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2349 PluginPtr plugin = instrument->load (*this);
2350 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2351 (*r)->add_processor (p, PreFader);
2361 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2363 boost::shared_ptr<Route> midi_track (wmt.lock());
2369 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2371 if (change.after.n_audio() <= change.before.n_audio()) {
2375 /* new audio ports: make sure the audio goes somewhere useful,
2376 unless the user has no-auto-connect selected.
2378 The existing ChanCounts don't matter for this call as they are only
2379 to do with matching input and output indices, and we are only changing
2385 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
2389 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
2390 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
2391 * @param output_start As \a input_start, but for outputs.
2394 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
2395 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
2397 if (!IO::connecting_legal) {
2401 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2407 /* If both inputs and outputs are auto-connected to physical ports,
2408 use the max of input and output offsets to ensure auto-connected
2409 port numbers always match up (e.g. the first audio input and the
2410 first audio output of the route will have the same physical
2411 port number). Otherwise just use the lowest input or output
2415 DEBUG_TRACE (DEBUG::Graph,
2416 string_compose("Auto-connect: existing in = %1 out = %2\n",
2417 existing_inputs, existing_outputs));
2419 const bool in_out_physical =
2420 (Config->get_input_auto_connect() & AutoConnectPhysical)
2421 && (Config->get_output_auto_connect() & AutoConnectPhysical)
2424 const ChanCount in_offset = in_out_physical
2425 ? ChanCount::max(existing_inputs, existing_outputs)
2428 const ChanCount out_offset = in_out_physical
2429 ? ChanCount::max(existing_inputs, existing_outputs)
2432 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2433 vector<string> physinputs;
2434 vector<string> physoutputs;
2436 _engine.get_physical_outputs (*t, physoutputs);
2437 _engine.get_physical_inputs (*t, physinputs);
2439 if (!physinputs.empty() && connect_inputs) {
2440 uint32_t nphysical_in = physinputs.size();
2442 DEBUG_TRACE (DEBUG::Graph,
2443 string_compose("There are %1 physical inputs of type %2\n",
2446 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2449 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2450 DEBUG_TRACE (DEBUG::Graph,
2451 string_compose("Get index %1 + %2 % %3 = %4\n",
2452 in_offset.get(*t), i, nphysical_in,
2453 (in_offset.get(*t) + i) % nphysical_in));
2454 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2457 DEBUG_TRACE (DEBUG::Graph,
2458 string_compose("Connect route %1 IN to %2\n",
2459 route->name(), port));
2461 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2465 ChanCount one_added (*t, 1);
2466 existing_inputs += one_added;
2470 if (!physoutputs.empty()) {
2471 uint32_t nphysical_out = physoutputs.size();
2472 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2476 * do not create new connections if we reached the limit of physical outputs
2480 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
2481 ARDOUR::Profile->get_trx () &&
2482 existing_outputs.get(*t) == nphysical_out ) {
2486 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2487 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2488 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2489 /* master bus is audio only */
2490 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2491 port = _master_out->input()->ports().port(*t,
2492 i % _master_out->input()->n_ports().get(*t))->name();
2496 DEBUG_TRACE (DEBUG::Graph,
2497 string_compose("Connect route %1 OUT to %2\n",
2498 route->name(), port));
2500 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2504 ChanCount one_added (*t, 1);
2505 existing_outputs += one_added;
2511 #ifdef USE_TRACKS_CODE_FEATURES
2514 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2516 return route1->remote_control_id() < route2->remote_control_id();
2520 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2522 // it is not allowed to perform connection
2523 if (!IO::connecting_legal) {
2527 // if we are deleting routes we will call this once at the end
2528 if (_route_deletion_in_progress) {
2532 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2538 // We need to disconnect the route's inputs and outputs first
2539 // basing on autoconnect configuration
2540 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2541 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2543 ChanCount existing_inputs;
2544 ChanCount existing_outputs;
2545 count_existing_track_channels (existing_inputs, existing_outputs);
2547 //ChanCount inputs = ChanCount::ZERO;
2548 //ChanCount outputs = ChanCount::ZERO;
2550 RouteList existing_routes = *routes.reader ();
2551 existing_routes.sort (compare_routes_by_remote_id);
2554 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2556 vector<string> physinputs;
2557 vector<string> physoutputs;
2559 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2560 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2562 uint32_t input_n = 0;
2563 uint32_t output_n = 0;
2564 RouteList::iterator rIter = existing_routes.begin();
2565 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2566 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2567 for (; rIter != existing_routes.end(); ++rIter) {
2568 if (*rIter == _master_out || *rIter == _monitor_out ) {
2572 if (current_output_auto_connection == AutoConnectPhysical) {
2573 (*rIter)->amp()->deactivate();
2574 } else if (current_output_auto_connection == AutoConnectMaster) {
2575 (*rIter)->amp()->activate();
2578 if (reconnectIputs) {
2579 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2581 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2583 if (current_input_auto_connection & AutoConnectPhysical) {
2585 if ( input_n == physinputs.size() ) {
2589 string port = physinputs[input_n];
2591 if (port.empty() ) {
2592 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2595 //GZ: check this; could be heavy
2596 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2602 if (reconnectOutputs) {
2604 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2605 if (current_output_auto_connection & AutoConnectPhysical) {
2607 //GZ: check this; could be heavy
2608 (*rIter)->output()->disconnect (this);
2609 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2611 //GZ: check this; could be heavy
2612 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2614 } else if (current_output_auto_connection & AutoConnectMaster){
2616 if (!reconnect_master) {
2620 //GZ: check this; could be heavy
2621 (*rIter)->output()->disconnect (this);
2624 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2625 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2627 error << error << "Master bus is not available" << endmsg;
2632 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2633 if (current_output_auto_connection & AutoConnectPhysical) {
2635 if ( output_n == physoutputs.size() ) {
2639 string port = physoutputs[output_n];
2641 if (port.empty() ) {
2642 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2645 //GZ: check this; could be heavy
2646 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2649 } else if (current_output_auto_connection & AutoConnectMaster) {
2651 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2655 // connect to master bus
2656 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2658 if (port.empty() ) {
2659 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2663 //GZ: check this; could be heavy
2664 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2670 //auto_connect_route (*rIter, inputs, outputs, false, reconnectIputs);
2673 _master_out->output()->disconnect (this);
2674 auto_connect_master_bus ();
2679 session_routes_reconnected (); /* EMIT SIGNAL */
2683 Session::reconnect_midi_scene_ports(bool inputs)
2687 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2689 scene_in_ptr->disconnect_all ();
2691 std::vector<EngineStateController::MidiPortState> midi_port_states;
2692 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2694 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2696 for (; state_iter != midi_port_states.end(); ++state_iter) {
2697 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2698 scene_in_ptr->connect (state_iter->name);
2705 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2707 if (scene_out_ptr ) {
2708 scene_out_ptr->disconnect_all ();
2710 std::vector<EngineStateController::MidiPortState> midi_port_states;
2711 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2713 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2715 for (; state_iter != midi_port_states.end(); ++state_iter) {
2716 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2717 scene_out_ptr->connect (state_iter->name);
2725 Session::reconnect_mtc_ports ()
2727 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2733 mtc_in_ptr->disconnect_all ();
2735 std::vector<EngineStateController::MidiPortState> midi_port_states;
2736 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2738 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2740 for (; state_iter != midi_port_states.end(); ++state_iter) {
2741 if (state_iter->available && state_iter->mtc_in) {
2742 mtc_in_ptr->connect (state_iter->name);
2746 if (!_midi_ports->mtc_input_port ()->connected () &&
2747 config.get_external_sync () &&
2748 (Config->get_sync_source () == MTC) ) {
2749 config.set_external_sync (false);
2752 if ( ARDOUR::Profile->get_trx () ) {
2753 // Tracks need this signal to update timecode_source_dropdown
2754 MtcOrLtcInputPortChanged (); //emit signal
2759 Session::reconnect_mmc_ports(bool inputs)
2761 if (inputs ) { // get all enabled midi input ports
2763 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2765 mmc_in_ptr->disconnect_all ();
2766 std::vector<std::string> enabled_midi_inputs;
2767 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2769 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2771 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2772 mmc_in_ptr->connect (*port_iter);
2776 } else { // get all enabled midi output ports
2778 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2780 mmc_out_ptr->disconnect_all ();
2781 std::vector<std::string> enabled_midi_outputs;
2782 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2784 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2786 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2787 mmc_out_ptr->connect (*port_iter);
2795 /** Caller must not hold process lock
2796 * @param name_template string to use for the start of the name, or "" to use "Audio".
2798 list< boost::shared_ptr<AudioTrack> >
2799 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2800 uint32_t how_many, string name_template)
2803 uint32_t track_id = 0;
2805 RouteList new_routes;
2806 list<boost::shared_ptr<AudioTrack> > ret;
2808 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2809 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2813 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2814 error << "cannot find name for new audio track" << endmsg;
2818 boost::shared_ptr<AudioTrack> track;
2821 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2823 if (track->init ()) {
2827 if (ARDOUR::Profile->get_trx ()) {
2828 // TRACKS considers it's not a USE CASE, it's
2829 // a piece of behavior of the session model:
2831 // Gain for a newly created route depends on
2832 // the current output_auto_connect mode:
2834 // 0 for Stereo Out mode
2836 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2837 track->set_gain (dB_to_coefficient (0), 0);
2841 track->use_new_diskstream();
2843 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2844 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2847 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2849 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2850 error << string_compose (
2851 _("cannot configure %1 in/%2 out configuration for new audio track"),
2852 input_channels, output_channels)
2857 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2858 error << string_compose (
2859 _("cannot configure %1 in/%2 out configuration for new audio track"),
2860 input_channels, output_channels)
2867 route_group->add (track);
2870 track->non_realtime_input_change();
2872 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2873 if (Config->get_remote_model() == UserOrdered) {
2874 track->set_remote_control_id (next_control_id());
2877 new_routes.push_back (track);
2878 ret.push_back (track);
2880 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2883 catch (failed_constructor &err) {
2884 error << _("Session: could not create new audio track.") << endmsg;
2888 catch (AudioEngine::PortRegistrationFailure& pfe) {
2890 error << pfe.what() << endmsg;
2898 if (!new_routes.empty()) {
2899 StateProtector sp (this);
2900 if (Profile->get_trx()) {
2901 add_routes (new_routes, false, false, false);
2903 add_routes (new_routes, true, true, false);
2910 /** Caller must not hold process lock.
2911 * @param name_template string to use for the start of the name, or "" to use "Bus".
2914 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2917 uint32_t bus_id = 0;
2921 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2924 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
2925 error << "cannot find name for new audio bus" << endmsg;
2930 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2936 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2937 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2940 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2942 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2943 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2944 input_channels, output_channels)
2950 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2951 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2952 input_channels, output_channels)
2959 route_group->add (bus);
2961 if (Config->get_remote_model() == UserOrdered) {
2962 bus->set_remote_control_id (next_control_id());
2965 bus->add_internal_return ();
2967 ret.push_back (bus);
2969 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2975 catch (failed_constructor &err) {
2976 error << _("Session: could not create new audio route.") << endmsg;
2980 catch (AudioEngine::PortRegistrationFailure& pfe) {
2981 error << pfe.what() << endmsg;
2991 StateProtector sp (this);
2992 if (Profile->get_trx()) {
2993 add_routes (ret, false, false, false);
2995 add_routes (ret, false, true, true); // autoconnect // outputs only
3004 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
3007 uint32_t control_id;
3009 uint32_t number = 0;
3010 const uint32_t being_added = how_many;
3012 if (!tree.read (template_path.c_str())) {
3016 XMLNode* node = tree.root();
3018 IO::disable_connecting ();
3020 control_id = next_control_id ();
3024 XMLNode node_copy (*node);
3026 /* Remove IDs of everything so that new ones are used */
3027 node_copy.remove_property_recursively (X_("id"));
3032 if (!name_base.empty()) {
3034 /* if we're adding more than one routes, force
3035 * all the names of the new routes to be
3036 * numbered, via the final parameter.
3039 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3040 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3046 string const route_name = node_copy.property(X_("name"))->value ();
3048 /* generate a new name by adding a number to the end of the template name */
3049 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3050 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3051 abort(); /*NOTREACHED*/
3055 /* set this name in the XML description that we are about to use */
3056 Route::set_name_in_state (node_copy, name);
3058 /* trim bitslots from listen sends so that new ones are used */
3059 XMLNodeList children = node_copy.children ();
3060 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3061 if ((*i)->name() == X_("Processor")) {
3062 XMLProperty* role = (*i)->property (X_("role"));
3063 if (role && role->value() == X_("Listen")) {
3064 (*i)->remove_property (X_("bitslot"));
3069 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3072 error << _("Session: cannot create track/bus from template description") << endmsg;
3076 if (boost::dynamic_pointer_cast<Track>(route)) {
3077 /* force input/output change signals so that the new diskstream
3078 picks up the configuration of the route. During session
3079 loading this normally happens in a different way.
3082 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3084 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3085 change.after = route->input()->n_ports();
3086 route->input()->changed (change, this);
3087 change.after = route->output()->n_ports();
3088 route->output()->changed (change, this);
3091 route->set_remote_control_id (control_id);
3094 ret.push_back (route);
3096 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3099 catch (failed_constructor &err) {
3100 error << _("Session: could not create new route from template") << endmsg;
3104 catch (AudioEngine::PortRegistrationFailure& pfe) {
3105 error << pfe.what() << endmsg;
3114 StateProtector sp (this);
3115 if (Profile->get_trx()) {
3116 add_routes (ret, false, false, false);
3118 add_routes (ret, true, true, false);
3120 IO::enable_connecting ();
3127 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3130 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3131 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3134 error << _("Adding new tracks/busses failed") << endmsg;
3139 update_latency (true);
3140 update_latency (false);
3145 save_state (_current_snapshot_name);
3148 reassign_track_numbers();
3150 update_route_record_state ();
3152 RouteAdded (new_routes); /* EMIT SIGNAL */
3156 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3158 ChanCount existing_inputs;
3159 ChanCount existing_outputs;
3160 uint32_t order = next_control_id();
3162 if (_order_hint > -1) {
3163 order = _order_hint;
3167 count_existing_track_channels (existing_inputs, existing_outputs);
3170 RCUWriter<RouteList> writer (routes);
3171 boost::shared_ptr<RouteList> r = writer.get_copy ();
3172 r->insert (r->end(), new_routes.begin(), new_routes.end());
3174 /* if there is no control out and we're not in the middle of loading,
3175 resort the graph here. if there is a control out, we will resort
3176 toward the end of this method. if we are in the middle of loading,
3177 we will resort when done.
3180 if (!_monitor_out && IO::connecting_legal) {
3181 resort_routes_using (r);
3185 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3187 boost::weak_ptr<Route> wpr (*x);
3188 boost::shared_ptr<Route> r (*x);
3190 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
3191 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3192 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
3193 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
3194 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3195 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3197 if (r->is_master()) {
3201 if (r->is_monitor()) {
3205 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3207 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3208 track_playlist_changed (boost::weak_ptr<Track> (tr));
3209 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3211 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3213 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3214 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3219 if (input_auto_connect || output_auto_connect) {
3220 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
3223 /* order keys are a GUI responsibility but we need to set up
3224 reasonable defaults because they also affect the remote control
3225 ID in most situations.
3228 if (!r->has_order_key ()) {
3229 if (r->is_auditioner()) {
3230 /* use an arbitrarily high value */
3231 r->set_order_key (UINT_MAX);
3233 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3234 r->set_order_key (order);
3242 if (_monitor_out && IO::connecting_legal) {
3243 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3245 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3246 if ((*x)->is_monitor()) {
3248 } else if ((*x)->is_master()) {
3251 (*x)->enable_monitor_send ();
3258 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3260 boost::shared_ptr<RouteList> r = routes.reader ();
3261 boost::shared_ptr<Send> s;
3263 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3264 if ((s = (*i)->internal_send_for (dest)) != 0) {
3265 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO);
3271 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3273 boost::shared_ptr<RouteList> r = routes.reader ();
3274 boost::shared_ptr<Send> s;
3276 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3277 if ((s = (*i)->internal_send_for (dest)) != 0) {
3278 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY);
3284 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3286 boost::shared_ptr<RouteList> r = routes.reader ();
3287 boost::shared_ptr<Send> s;
3289 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3290 if ((s = (*i)->internal_send_for (dest)) != 0) {
3291 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
3296 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3298 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3300 boost::shared_ptr<RouteList> r = routes.reader ();
3301 boost::shared_ptr<RouteList> t (new RouteList);
3303 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3304 /* no MIDI sends because there are no MIDI busses yet */
3305 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3310 add_internal_sends (dest, p, t);
3314 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3316 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3317 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3322 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3324 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3328 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3330 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3334 if (!dest->internal_return()) {
3335 dest->add_internal_return ();
3338 sender->add_aux_send (dest, before);
3345 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3347 { // RCU Writer scope
3348 RCUWriter<RouteList> writer (routes);
3349 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3352 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3354 if (*iter == _master_out) {
3358 (*iter)->set_solo (false, this);
3362 /* deleting the master out seems like a dumb
3363 idea, but its more of a UI policy issue
3367 if (*iter == _master_out) {
3368 _master_out = boost::shared_ptr<Route> ();
3371 if (*iter == _monitor_out) {
3372 _monitor_out.reset ();
3375 update_route_solo_state ();
3377 // We need to disconnect the route's inputs and outputs
3379 (*iter)->input()->disconnect (0);
3380 (*iter)->output()->disconnect (0);
3382 /* if the route had internal sends sending to it, remove them */
3383 if ((*iter)->internal_return()) {
3385 boost::shared_ptr<RouteList> r = routes.reader ();
3386 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3387 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3389 (*i)->remove_processor (s);
3394 /* if the monitoring section had a pointer to this route, remove it */
3395 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3396 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3397 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3398 (*iter)->remove_aux_or_listen (_monitor_out);
3401 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3402 if (mt && mt->step_editing()) {
3403 if (_step_editors > 0) {
3408 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3411 /* writer goes out of scope, forces route list update */
3413 } // end of RCU Writer scope
3415 update_latency_compensation ();
3418 /* Re-sort routes to remove the graph's current references to the one that is
3419 * going away, then flush old references out of the graph.
3420 * Wave Tracks: reconnect routes
3423 #ifdef USE_TRACKS_CODE_FEATURES
3424 reconnect_existing_routes(true, false);
3426 routes.flush (); // maybe unsafe, see below.
3430 if (_process_graph) {
3431 _process_graph->clear_other_chain ();
3434 /* get rid of it from the dead wood collection in the route list manager */
3435 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3439 /* try to cause everyone to drop their references
3440 * and unregister ports from the backend
3442 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3444 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3445 (*iter)->drop_references ();
3448 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3450 /* save the new state of the world */
3452 if (save_state (_current_snapshot_name)) {
3453 save_history (_current_snapshot_name);
3456 reassign_track_numbers();
3457 update_route_record_state ();
3461 Session::remove_route (boost::shared_ptr<Route> route)
3463 boost::shared_ptr<RouteList> rl (new RouteList);
3464 rl->push_back (route);
3469 Session::route_mute_changed (void* /*src*/)
3475 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3477 boost::shared_ptr<Route> route = wpr.lock();
3479 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
3483 if (route->listening_via_monitor ()) {
3485 if (Config->get_exclusive_solo()) {
3486 /* new listen: disable all other listen */
3487 boost::shared_ptr<RouteList> r = routes.reader ();
3488 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3489 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3492 (*i)->set_listen (false, this);
3498 } else if (_listen_cnt > 0) {
3503 update_route_solo_state ();
3506 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3508 boost::shared_ptr<Route> route = wpr.lock ();
3511 /* should not happen */
3512 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
3516 bool send_changed = false;
3518 if (route->solo_isolated()) {
3519 if (_solo_isolated_cnt == 0) {
3520 send_changed = true;
3522 _solo_isolated_cnt++;
3523 } else if (_solo_isolated_cnt > 0) {
3524 _solo_isolated_cnt--;
3525 if (_solo_isolated_cnt == 0) {
3526 send_changed = true;
3531 IsolatedChanged (); /* EMIT SIGNAL */
3536 Session::routes_solo_changed (boost::shared_ptr<RouteList> solo_change_routes)
3538 if (solo_update_disabled) {
3540 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
3544 if (solo_change_routes->empty() ) {
3548 boost::shared_ptr<RouteList> non_solo_change_routes (new RouteList);
3549 boost::shared_ptr<RouteList> r = routes.reader ();
3552 std::set_difference (r->begin(), r->end(),
3553 solo_change_routes->begin(), solo_change_routes->end(),
3554 std::back_inserter(*non_solo_change_routes) );
3556 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3558 solo_update_disabled = true;
3559 RouteList uninvolved;
3561 for (RouteList::iterator route = solo_change_routes->begin(); route != solo_change_routes->end(); ++route) {
3563 if ((*route)->self_soloed() ) {
3569 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", (*route)->name()));
3571 for (RouteList::iterator i = non_solo_change_routes->begin(); i != non_solo_change_routes->end(); ++i) {
3572 bool via_sends_only;
3573 bool in_signal_flow;
3575 if ((*i) == *route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ) {
3579 in_signal_flow = false;
3581 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3583 if ((*i)->feeds (*route, &via_sends_only)) {
3584 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3585 if (!via_sends_only) {
3586 if (!(*route)->soloed_by_others_upstream()) {
3587 (*i)->mod_solo_by_others_downstream (delta);
3590 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3592 in_signal_flow = true;
3594 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3597 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3599 if ((*route)->feeds (*i, &via_sends_only)) {
3600 /* propagate solo upstream only if routing other than
3601 sends is involved, but do consider the other route
3602 (*i) to be part of the signal flow even if only
3605 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3609 (*route)->soloed_by_others_downstream(),
3610 (*route)->soloed_by_others_upstream()));
3611 if (!via_sends_only) {
3612 if (!(*route)->soloed_by_others_downstream()) {
3613 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3614 (*i)->mod_solo_by_others_upstream (delta);
3616 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
3619 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3621 in_signal_flow = true;
3623 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3626 if (!in_signal_flow) {
3627 uninvolved.push_back (*i);
3631 solo_update_disabled = false;
3632 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3634 update_route_solo_state ();
3636 /* now notify that the mute state of the routes not involved in the signal
3637 pathway of the just-solo-changed route may have altered.
3640 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3641 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1\n", (*i)->name() ));
3642 (*i)->mute_changed (this);
3645 SoloChanged (); /* EMIT SIGNAL */
3650 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
3652 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3654 if (!self_solo_change) {
3655 // session doesn't care about changes to soloed-by-others
3659 if (solo_update_disabled) {
3661 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
3665 boost::shared_ptr<Route> route = wpr.lock ();
3668 boost::shared_ptr<RouteList> r = routes.reader ();
3671 if (route->self_soloed()) {
3677 RouteGroup* rg = route->route_group ();
3678 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
3680 if (delta == 1 && Config->get_exclusive_solo()) {
3682 /* new solo: disable all other solos, but not the group if its solo-enabled */
3684 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3685 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3686 (leave_group_alone && ((*i)->route_group() == rg))) {
3689 (*i)->set_solo (false, this);
3693 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3695 solo_update_disabled = true;
3697 RouteList uninvolved;
3699 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3701 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3702 bool via_sends_only;
3703 bool in_signal_flow;
3705 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3706 (leave_group_alone && ((*i)->route_group() == rg))) {
3710 in_signal_flow = false;
3712 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3714 if ((*i)->feeds (route, &via_sends_only)) {
3715 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3716 if (!via_sends_only) {
3717 if (!route->soloed_by_others_upstream()) {
3718 (*i)->mod_solo_by_others_downstream (delta);
3721 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3723 in_signal_flow = true;
3725 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3728 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3730 if (route->feeds (*i, &via_sends_only)) {
3731 /* propagate solo upstream only if routing other than
3732 sends is involved, but do consider the other route
3733 (*i) to be part of the signal flow even if only
3736 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3740 route->soloed_by_others_downstream(),
3741 route->soloed_by_others_upstream()));
3742 if (!via_sends_only) {
3743 if (!route->soloed_by_others_downstream()) {
3744 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3745 (*i)->mod_solo_by_others_upstream (delta);
3747 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
3750 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3752 in_signal_flow = true;
3754 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3757 if (!in_signal_flow) {
3758 uninvolved.push_back (*i);
3762 solo_update_disabled = false;
3763 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3765 update_route_solo_state (r);
3767 /* now notify that the mute state of the routes not involved in the signal
3768 pathway of the just-solo-changed route may have altered.
3771 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3772 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3773 (*i)->act_on_mute ();
3774 (*i)->mute_changed (this);
3777 SoloChanged (); /* EMIT SIGNAL */
3782 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3784 /* now figure out if anything that matters is soloed (or is "listening")*/
3786 bool something_soloed = false;
3787 uint32_t listeners = 0;
3788 uint32_t isolated = 0;
3791 r = routes.reader();
3794 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3795 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3796 something_soloed = true;
3799 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3800 if (Config->get_solo_control_is_listen_control()) {
3803 (*i)->set_listen (false, this);
3807 if ((*i)->solo_isolated()) {
3812 if (something_soloed != _non_soloed_outs_muted) {
3813 _non_soloed_outs_muted = something_soloed;
3814 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3817 _listen_cnt = listeners;
3819 if (isolated != _solo_isolated_cnt) {
3820 _solo_isolated_cnt = isolated;
3821 IsolatedChanged (); /* EMIT SIGNAL */
3824 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3825 something_soloed, listeners, isolated));
3828 boost::shared_ptr<RouteList>
3829 Session::get_routes_with_internal_returns() const
3831 boost::shared_ptr<RouteList> r = routes.reader ();
3832 boost::shared_ptr<RouteList> rl (new RouteList);
3834 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3835 if ((*i)->internal_return ()) {
3843 Session::io_name_is_legal (const std::string& name)
3845 boost::shared_ptr<RouteList> r = routes.reader ();
3847 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3848 if ((*i)->name() == name) {
3852 if ((*i)->has_io_processor_named (name)) {
3861 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3864 vector<string> connections;
3866 /* if we are passed only a single route and we're not told to turn
3867 * others off, then just do the simple thing.
3870 if (flip_others == false && rl->size() == 1) {
3871 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3873 mt->set_input_active (onoff);
3878 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3880 PortSet& ps ((*rt)->input()->ports());
3882 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3883 p->get_connections (connections);
3886 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3887 routes_using_input_from (*s, rl2);
3890 /* scan all relevant routes to see if others are on or off */
3892 bool others_are_already_on = false;
3894 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3896 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3902 if ((*r) != (*rt)) {
3903 if (mt->input_active()) {
3904 others_are_already_on = true;
3907 /* this one needs changing */
3908 mt->set_input_active (onoff);
3914 /* globally reverse other routes */
3916 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3917 if ((*r) != (*rt)) {
3918 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3920 mt->set_input_active (!others_are_already_on);
3929 Session::routes_using_input_from (const string& str, RouteList& rl)
3931 boost::shared_ptr<RouteList> r = routes.reader();
3933 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3934 if ((*i)->input()->connected_to (str)) {
3940 boost::shared_ptr<Route>
3941 Session::route_by_name (string name)
3943 boost::shared_ptr<RouteList> r = routes.reader ();
3945 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3946 if ((*i)->name() == name) {
3951 return boost::shared_ptr<Route> ((Route*) 0);
3954 boost::shared_ptr<Route>
3955 Session::route_by_id (PBD::ID id)
3957 boost::shared_ptr<RouteList> r = routes.reader ();
3959 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3960 if ((*i)->id() == id) {
3965 return boost::shared_ptr<Route> ((Route*) 0);
3968 boost::shared_ptr<Track>
3969 Session::track_by_diskstream_id (PBD::ID id)
3971 boost::shared_ptr<RouteList> r = routes.reader ();
3973 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3974 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3975 if (t && t->using_diskstream_id (id)) {
3980 return boost::shared_ptr<Track> ();
3983 boost::shared_ptr<Route>
3984 Session::route_by_remote_id (uint32_t id)
3986 boost::shared_ptr<RouteList> r = routes.reader ();
3988 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3989 if ((*i)->remote_control_id() == id) {
3994 return boost::shared_ptr<Route> ((Route*) 0);
3999 Session::reassign_track_numbers ()
4003 RouteList r (*(routes.reader ()));
4004 SignalOrderRouteSorter sorter;
4007 StateProtector sp (this);
4009 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4010 if (boost::dynamic_pointer_cast<Track> (*i)) {
4011 (*i)->set_track_number(++tn);
4013 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4014 (*i)->set_track_number(--bn);
4017 const uint32_t decimals = ceilf (log10f (tn + 1));
4018 const bool decimals_changed = _track_number_decimals != decimals;
4019 _track_number_decimals = decimals;
4021 if (decimals_changed && config.get_track_name_number ()) {
4022 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4023 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4025 t->resync_track_name();
4028 // trigger GUI re-layout
4029 config.ParameterChanged("track-name-number");
4034 Session::playlist_region_added (boost::weak_ptr<Region> w)
4036 boost::shared_ptr<Region> r = w.lock ();
4041 /* These are the operations that are currently in progress... */
4042 list<GQuark> curr = _current_trans_quarks;
4045 /* ...and these are the operations during which we want to update
4046 the session range location markers.
4049 ops.push_back (Operations::capture);
4050 ops.push_back (Operations::paste);
4051 ops.push_back (Operations::duplicate_region);
4052 ops.push_back (Operations::insert_file);
4053 ops.push_back (Operations::insert_region);
4054 ops.push_back (Operations::drag_region_brush);
4055 ops.push_back (Operations::region_drag);
4056 ops.push_back (Operations::selection_grab);
4057 ops.push_back (Operations::region_fill);
4058 ops.push_back (Operations::fill_selection);
4059 ops.push_back (Operations::create_region);
4060 ops.push_back (Operations::region_copy);
4061 ops.push_back (Operations::fixed_time_region_copy);
4064 /* See if any of the current operations match the ones that we want */
4066 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4068 /* If so, update the session range markers */
4070 maybe_update_session_range (r->position (), r->last_frame ());
4074 /** Update the session range markers if a is before the current start or
4075 * b is after the current end.
4078 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4080 if (_state_of_the_state & Loading) {
4084 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4086 if (_session_range_location == 0) {
4088 set_session_range_location (a, b + session_end_marker_shift_samples);
4092 if (a < _session_range_location->start()) {
4093 _session_range_location->set_start (a);
4096 if (b > _session_range_location->end()) {
4097 _session_range_location->set_end (b);
4103 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4105 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4106 maybe_update_session_range (i->to, i->to + i->length);
4111 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4113 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4114 maybe_update_session_range (i->from, i->to);
4118 /* Region management */
4120 boost::shared_ptr<Region>
4121 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4123 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4124 RegionFactory::RegionMap::const_iterator i;
4125 boost::shared_ptr<Region> region;
4127 Glib::Threads::Mutex::Lock lm (region_lock);
4129 for (i = regions.begin(); i != regions.end(); ++i) {
4133 if (region->whole_file()) {
4135 if (child->source_equivalent (region)) {
4141 return boost::shared_ptr<Region> ();
4145 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4147 set<boost::shared_ptr<Region> > relevant_regions;
4149 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4150 RegionFactory::get_regions_using_source (*s, relevant_regions);
4153 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4154 set<boost::shared_ptr<Region> >::iterator tmp;
4159 playlists->destroy_region (*r);
4160 RegionFactory::map_remove (*r);
4162 (*r)->drop_sources ();
4163 (*r)->drop_references ();
4165 relevant_regions.erase (r);
4170 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4173 Glib::Threads::Mutex::Lock ls (source_lock);
4174 /* remove from the main source list */
4175 sources.erase ((*s)->id());
4178 (*s)->mark_for_remove ();
4179 (*s)->drop_references ();
4188 Session::remove_last_capture ()
4190 list<boost::shared_ptr<Source> > srcs;
4192 boost::shared_ptr<RouteList> rl = routes.reader ();
4193 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4194 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4199 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4202 srcs.insert (srcs.end(), l.begin(), l.end());
4207 destroy_sources (srcs);
4209 save_state (_current_snapshot_name);
4214 /* Source Management */
4217 Session::add_source (boost::shared_ptr<Source> source)
4219 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4220 pair<SourceMap::iterator,bool> result;
4222 entry.first = source->id();
4223 entry.second = source;
4226 Glib::Threads::Mutex::Lock lm (source_lock);
4227 result = sources.insert (entry);
4230 if (result.second) {
4232 /* yay, new source */
4234 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4237 if (!fs->within_session()) {
4238 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4244 boost::shared_ptr<AudioFileSource> afs;
4246 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4247 if (Config->get_auto_analyse_audio()) {
4248 Analyser::queue_source_for_analysis (source, false);
4252 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4257 Session::remove_source (boost::weak_ptr<Source> src)
4259 if (_state_of_the_state & Deletion) {
4263 SourceMap::iterator i;
4264 boost::shared_ptr<Source> source = src.lock();
4271 Glib::Threads::Mutex::Lock lm (source_lock);
4273 if ((i = sources.find (source->id())) != sources.end()) {
4278 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4280 /* save state so we don't end up with a session file
4281 referring to non-existent sources.
4284 save_state (_current_snapshot_name);
4288 boost::shared_ptr<Source>
4289 Session::source_by_id (const PBD::ID& id)
4291 Glib::Threads::Mutex::Lock lm (source_lock);
4292 SourceMap::iterator i;
4293 boost::shared_ptr<Source> source;
4295 if ((i = sources.find (id)) != sources.end()) {
4302 boost::shared_ptr<AudioFileSource>
4303 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4305 /* Restricted to audio files because only audio sources have channel
4309 Glib::Threads::Mutex::Lock lm (source_lock);
4311 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4312 boost::shared_ptr<AudioFileSource> afs
4313 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4315 if (afs && afs->path() == path && chn == afs->channel()) {
4320 return boost::shared_ptr<AudioFileSource>();
4323 boost::shared_ptr<MidiSource>
4324 Session::midi_source_by_path (const std::string& path) const
4326 /* Restricted to MIDI files because audio sources require a channel
4327 for unique identification, in addition to a path.
4330 Glib::Threads::Mutex::Lock lm (source_lock);
4332 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4333 boost::shared_ptr<MidiSource> ms
4334 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4335 boost::shared_ptr<FileSource> fs
4336 = boost::dynamic_pointer_cast<FileSource>(s->second);
4338 if (ms && fs && fs->path() == path) {
4343 return boost::shared_ptr<MidiSource>();
4347 Session::count_sources_by_origin (const string& path)
4350 Glib::Threads::Mutex::Lock lm (source_lock);
4352 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4353 boost::shared_ptr<FileSource> fs
4354 = boost::dynamic_pointer_cast<FileSource>(i->second);
4356 if (fs && fs->origin() == path) {
4365 Session::peak_path (string base) const
4367 if (Glib::path_is_absolute (base)) {
4369 /* rip the session dir from the audiofile source */
4371 string session_path;
4372 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4373 bool in_another_session = true;
4375 if (base.find (interchange_dir_string) != string::npos) {
4377 session_path = Glib::path_get_dirname (base); /* now ends in audiofiles */
4378 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4379 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4380 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4382 /* see if it is within our session */
4384 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4385 if (i->path == session_path) {
4386 in_another_session = false;
4391 in_another_session = false;
4395 if (in_another_session) {
4396 SessionDirectory sd (session_path);
4397 return Glib::build_filename (sd.peak_path(), Glib::path_get_basename (base) + peakfile_suffix);
4401 base = Glib::path_get_basename (base);
4402 return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
4406 Session::new_audio_source_path_for_embedded (const std::string& path)
4410 * we know that the filename is already unique because it exists
4411 * out in the filesystem.
4413 * However, when we bring it into the session, we could get a
4416 * Eg. two embedded files:
4421 * When merged into session, these collide.
4423 * There will not be a conflict with in-memory sources
4424 * because when the source was created we already picked
4425 * a unique name for it.
4427 * This collision is not likely to be common, but we have to guard
4428 * against it. So, if there is a collision, take the md5 hash of the
4429 * the path, and use that as the filename instead.
4432 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4433 string base = Glib::path_get_basename (path);
4434 string newpath = Glib::build_filename (sdir.sound_path(), base);
4436 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4440 md5.digestString (path.c_str());
4441 md5.writeToString ();
4442 base = md5.digestChars;
4444 string ext = get_suffix (path);
4451 newpath = Glib::build_filename (sdir.sound_path(), base);
4453 /* if this collides, we're screwed */
4455 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4456 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4465 /** Return true if there are no audio file sources that use @param name as
4466 * the filename component of their path.
4468 * Return false otherwise.
4470 * This method MUST ONLY be used to check in-session, mono files since it
4471 * hard-codes the channel of the audio file source we are looking for as zero.
4473 * If/when Ardour supports native files in non-mono formats, the logic here
4474 * will need to be revisited.
4477 Session::audio_source_name_is_unique (const string& name)
4479 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4480 vector<space_and_path>::iterator i;
4481 uint32_t existing = 0;
4483 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4485 /* note that we search *without* the extension so that
4486 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4487 in the event that this new name is required for
4488 a file format change.
4491 const string spath = *i;
4493 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4498 /* it is possible that we have the path already
4499 * assigned to a source that has not yet been written
4500 * (ie. the write source for a diskstream). we have to
4501 * check this in order to make sure that our candidate
4502 * path isn't used again, because that can lead to
4503 * two Sources point to the same file with different
4504 * notions of their removability.
4508 string possible_path = Glib::build_filename (spath, name);
4510 if (audio_source_by_path_and_channel (possible_path, 0)) {
4516 return (existing == 0);
4520 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)
4523 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4525 if (Profile->get_trx() && destructive) {
4527 sstr << setfill ('0') << setw (4) << cnt;
4528 sstr << legalized_base;
4530 sstr << legalized_base;
4532 if (take_required || related_exists) {
4544 } else if (nchan > 2) {
4549 /* XXX what? more than 26 channels! */
4560 /** Return a unique name based on \a base for a new internal audio source */
4562 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4565 string possible_name;
4566 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4568 bool some_related_source_name_exists = false;
4570 legalized = legalize_for_path (base);
4572 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4574 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4576 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4578 if (audio_source_name_is_unique (possible_name)) {
4582 some_related_source_name_exists = true;
4585 error << string_compose(
4586 _("There are already %1 recordings for %2, which I consider too many."),
4587 limit, base) << endmsg;
4589 throw failed_constructor();
4593 /* We've established that the new name does not exist in any session
4594 * directory, so now find out which one we should use for this new
4598 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4600 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4605 /** Return a unique name based on `base` for a new internal MIDI source */
4607 Session::new_midi_source_path (const string& base)
4610 char buf[PATH_MAX+1];
4611 const uint32_t limit = 10000;
4613 string possible_path;
4614 string possible_name;
4617 legalized = legalize_for_path (base);
4619 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4620 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4622 /* - the main session folder is the first in the vector.
4623 * - after checking all locations for file-name uniqueness,
4624 * we keep the one from the last iteration as new file name
4625 * - midi files are small and should just be kept in the main session-folder
4627 * -> reverse the array, check main session folder last and use that as location
4630 std::reverse(sdirs.begin(), sdirs.end());
4632 for (cnt = 1; cnt <= limit; ++cnt) {
4634 vector<space_and_path>::iterator i;
4635 uint32_t existing = 0;
4637 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4639 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4640 possible_name = buf;
4642 possible_path = Glib::build_filename (*i, possible_name);
4644 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4648 if (midi_source_by_path (possible_path)) {
4653 if (existing == 0) {
4658 error << string_compose(
4659 _("There are already %1 recordings for %2, which I consider too many."),
4660 limit, base) << endmsg;
4666 /* No need to "find best location" for software/app-based RAID, because
4667 MIDI is so small that we always put it in the same place.
4670 return possible_path;
4674 /** Create a new within-session audio source */
4675 boost::shared_ptr<AudioFileSource>
4676 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4678 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4680 if (!path.empty()) {
4681 return boost::dynamic_pointer_cast<AudioFileSource> (
4682 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
4684 throw failed_constructor ();
4688 /** Create a new within-session MIDI source */
4689 boost::shared_ptr<MidiSource>
4690 Session::create_midi_source_for_session (string const & basic_name)
4692 const string path = new_midi_source_path (basic_name);
4694 if (!path.empty()) {
4695 return boost::dynamic_pointer_cast<SMFSource> (
4696 SourceFactory::createWritable (
4697 DataType::MIDI, *this, path, false, frame_rate()));
4699 throw failed_constructor ();
4703 /** Create a new within-session MIDI source */
4704 boost::shared_ptr<MidiSource>
4705 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4707 /* the caller passes in the track the source will be used in,
4708 so that we can keep the numbering sane.
4710 Rationale: a track with the name "Foo" that has had N
4711 captures carried out so far will ALREADY have a write source
4712 named "Foo-N+1.mid" waiting to be used for the next capture.
4714 If we call new_midi_source_name() we will get "Foo-N+2". But
4715 there is no region corresponding to "Foo-N+1", so when
4716 "Foo-N+2" appears in the track, the gap presents the user
4717 with odd behaviour - why did it skip past Foo-N+1?
4719 We could explain this to the user in some odd way, but
4720 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4723 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4726 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4728 std::string name = track->steal_write_source_name ();
4731 return boost::shared_ptr<MidiSource>();
4734 /* MIDI files are small, just put them in the first location of the
4735 session source search path.
4738 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4740 return boost::dynamic_pointer_cast<SMFSource> (
4741 SourceFactory::createWritable (
4742 DataType::MIDI, *this, path, false, frame_rate()));
4747 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4749 if (playlist->hidden()) {
4753 playlists->add (playlist);
4756 playlist->release();
4763 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4765 if (_state_of_the_state & Deletion) {
4769 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4775 playlists->remove (playlist);
4781 Session::set_audition (boost::shared_ptr<Region> r)
4783 pending_audition_region = r;
4784 add_post_transport_work (PostTransportAudition);
4785 _butler->schedule_transport_work ();
4789 Session::audition_playlist ()
4791 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4792 ev->region.reset ();
4797 Session::non_realtime_set_audition ()
4799 assert (pending_audition_region);
4800 auditioner->audition_region (pending_audition_region);
4801 pending_audition_region.reset ();
4802 AuditionActive (true); /* EMIT SIGNAL */
4806 Session::audition_region (boost::shared_ptr<Region> r)
4808 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4814 Session::cancel_audition ()
4819 if (auditioner->auditioning()) {
4820 auditioner->cancel_audition ();
4821 AuditionActive (false); /* EMIT SIGNAL */
4826 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
4828 if (a->is_monitor()) {
4831 if (b->is_monitor()) {
4834 return a->order_key () < b->order_key ();
4838 Session::is_auditioning () const
4840 /* can be called before we have an auditioner object */
4842 return auditioner->auditioning();
4849 Session::graph_reordered ()
4851 /* don't do this stuff if we are setting up connections
4852 from a set_state() call or creating new tracks. Ditto for deletion.
4855 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress) {
4859 /* every track/bus asked for this to be handled but it was deferred because
4860 we were connecting. do it now.
4863 request_input_change_handling ();
4867 /* force all diskstreams to update their capture offset values to
4868 reflect any changes in latencies within the graph.
4871 boost::shared_ptr<RouteList> rl = routes.reader ();
4872 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4873 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4875 tr->set_capture_offset ();
4880 /** @return Number of frames that there is disk space available to write,
4883 boost::optional<framecnt_t>
4884 Session::available_capture_duration ()
4886 Glib::Threads::Mutex::Lock lm (space_lock);
4888 if (_total_free_4k_blocks_uncertain) {
4889 return boost::optional<framecnt_t> ();
4892 float sample_bytes_on_disk = 4.0; // keep gcc happy
4894 switch (config.get_native_file_data_format()) {
4896 sample_bytes_on_disk = 4.0;
4900 sample_bytes_on_disk = 3.0;
4904 sample_bytes_on_disk = 2.0;
4908 /* impossible, but keep some gcc versions happy */
4909 fatal << string_compose (_("programming error: %1"),
4910 X_("illegal native file data format"))
4912 abort(); /*NOTREACHED*/
4915 double scale = 4096.0 / sample_bytes_on_disk;
4917 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
4918 return max_framecnt;
4921 return (framecnt_t) floor (_total_free_4k_blocks * scale);
4925 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
4928 RCUWriter<BundleList> writer (_bundles);
4929 boost::shared_ptr<BundleList> b = writer.get_copy ();
4930 b->push_back (bundle);
4934 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4941 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
4943 bool removed = false;
4946 RCUWriter<BundleList> writer (_bundles);
4947 boost::shared_ptr<BundleList> b = writer.get_copy ();
4948 BundleList::iterator i = find (b->begin(), b->end(), bundle);
4950 if (i != b->end()) {
4957 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4963 boost::shared_ptr<Bundle>
4964 Session::bundle_by_name (string name) const
4966 boost::shared_ptr<BundleList> b = _bundles.reader ();
4968 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
4969 if ((*i)->name() == name) {
4974 return boost::shared_ptr<Bundle> ();
4978 Session::tempo_map_changed (const PropertyChange&)
4982 playlists->update_after_tempo_map_change ();
4984 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
4990 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
4992 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
4993 (*i)->recompute_frames_from_bbt ();
4997 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
4998 * the given count with the current block size.
5001 Session::ensure_buffers (ChanCount howmany)
5003 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5007 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5009 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5010 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5015 Session::next_insert_id ()
5017 /* this doesn't really loop forever. just think about it */
5020 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
5021 if (!insert_bitset[n]) {
5022 insert_bitset[n] = true;
5028 /* none available, so resize and try again */
5030 insert_bitset.resize (insert_bitset.size() + 16, false);
5035 Session::next_send_id ()
5037 /* this doesn't really loop forever. just think about it */
5040 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
5041 if (!send_bitset[n]) {
5042 send_bitset[n] = true;
5048 /* none available, so resize and try again */
5050 send_bitset.resize (send_bitset.size() + 16, false);
5055 Session::next_aux_send_id ()
5057 /* this doesn't really loop forever. just think about it */
5060 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
5061 if (!aux_send_bitset[n]) {
5062 aux_send_bitset[n] = true;
5068 /* none available, so resize and try again */
5070 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5075 Session::next_return_id ()
5077 /* this doesn't really loop forever. just think about it */
5080 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
5081 if (!return_bitset[n]) {
5082 return_bitset[n] = true;
5088 /* none available, so resize and try again */
5090 return_bitset.resize (return_bitset.size() + 16, false);
5095 Session::mark_send_id (uint32_t id)
5097 if (id >= send_bitset.size()) {
5098 send_bitset.resize (id+16, false);
5100 if (send_bitset[id]) {
5101 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5103 send_bitset[id] = true;
5107 Session::mark_aux_send_id (uint32_t id)
5109 if (id >= aux_send_bitset.size()) {
5110 aux_send_bitset.resize (id+16, false);
5112 if (aux_send_bitset[id]) {
5113 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5115 aux_send_bitset[id] = true;
5119 Session::mark_return_id (uint32_t id)
5121 if (id >= return_bitset.size()) {
5122 return_bitset.resize (id+16, false);
5124 if (return_bitset[id]) {
5125 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5127 return_bitset[id] = true;
5131 Session::mark_insert_id (uint32_t id)
5133 if (id >= insert_bitset.size()) {
5134 insert_bitset.resize (id+16, false);
5136 if (insert_bitset[id]) {
5137 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5139 insert_bitset[id] = true;
5143 Session::unmark_send_id (uint32_t id)
5145 if (id < send_bitset.size()) {
5146 send_bitset[id] = false;
5151 Session::unmark_aux_send_id (uint32_t id)
5153 if (id < aux_send_bitset.size()) {
5154 aux_send_bitset[id] = false;
5159 Session::unmark_return_id (uint32_t id)
5161 if (id < return_bitset.size()) {
5162 return_bitset[id] = false;
5167 Session::unmark_insert_id (uint32_t id)
5169 if (id < insert_bitset.size()) {
5170 insert_bitset[id] = false;
5175 Session::reset_native_file_format ()
5177 boost::shared_ptr<RouteList> rl = routes.reader ();
5179 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5180 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5182 /* don't save state as we do this, there's no point
5184 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5185 tr->reset_write_sources (false);
5186 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5192 Session::route_name_unique (string n) const
5194 boost::shared_ptr<RouteList> r = routes.reader ();
5196 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5197 if ((*i)->name() == n) {
5206 Session::route_name_internal (string n) const
5208 if (auditioner && auditioner->name() == n) {
5212 if (_click_io && _click_io->name() == n) {
5220 Session::freeze_all (InterThreadInfo& itt)
5222 boost::shared_ptr<RouteList> r = routes.reader ();
5224 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5226 boost::shared_ptr<Track> t;
5228 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5229 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5239 boost::shared_ptr<Region>
5240 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5241 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5242 InterThreadInfo& itt,
5243 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5244 bool for_export, bool for_freeze)
5246 boost::shared_ptr<Region> result;
5247 boost::shared_ptr<Playlist> playlist;
5248 boost::shared_ptr<Source> source;
5249 ChanCount diskstream_channels (track.n_channels());
5250 framepos_t position;
5251 framecnt_t this_chunk;
5253 framepos_t latency_skip;
5255 framepos_t len = end - start;
5256 bool need_block_size_reset = false;
5257 ChanCount const max_proc = track.max_processor_streams ();
5258 string legal_playlist_name;
5259 string possible_path;
5262 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5263 end, start) << endmsg;
5267 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5268 include_endpoint, for_export, for_freeze);
5270 if (diskstream_channels.n(track.data_type()) < 1) {
5271 error << _("Cannot write a range with no data.") << endmsg;
5275 // block all process callback handling
5277 block_processing ();
5280 // synchronize with AudioEngine::process_callback()
5281 // make sure processing is not currently running
5282 // and processing_blocked() is honored before
5283 // acquiring thread buffers
5284 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5287 _bounce_processing_active = true;
5289 /* call tree *MUST* hold route_lock */
5291 if ((playlist = track.playlist()) == 0) {
5295 legal_playlist_name = legalize_for_path (playlist->name());
5297 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5299 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5300 string path = ((track.data_type() == DataType::AUDIO)
5301 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5302 : new_midi_source_path (legal_playlist_name));
5309 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5312 catch (failed_constructor& err) {
5313 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5317 srcs.push_back (source);
5320 /* tell redirects that care that we are about to use a much larger
5321 * blocksize. this will flush all plugins too, so that they are ready
5322 * to be used for this process.
5325 need_block_size_reset = true;
5326 track.set_block_size (bounce_chunk_size);
5327 _engine.main_thread()->get_buffers ();
5331 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5333 /* create a set of reasonably-sized buffers */
5334 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5335 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5337 buffers.set_count (max_proc);
5339 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5340 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5341 boost::shared_ptr<MidiSource> ms;
5343 afs->prepare_for_peakfile_writes ();
5344 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5345 Source::Lock lock(ms->mutex());
5346 ms->mark_streaming_write_started(lock);
5350 while (to_do && !itt.cancel) {
5352 this_chunk = min (to_do, bounce_chunk_size);
5354 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5358 start += this_chunk;
5359 to_do -= this_chunk;
5360 itt.progress = (float) (1.0 - ((double) to_do / len));
5362 if (latency_skip >= bounce_chunk_size) {
5363 latency_skip -= bounce_chunk_size;
5367 const framecnt_t current_chunk = this_chunk - latency_skip;
5370 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5371 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5372 boost::shared_ptr<MidiSource> ms;
5375 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5378 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5379 Source::Lock lock(ms->mutex());
5381 const MidiBuffer& buf = buffers.get_midi(0);
5382 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5383 Evoral::Event<framepos_t> ev = *i;
5384 ev.set_time(ev.time() - position);
5385 ms->append_event_frames(lock, ev, ms->timeline_position());
5392 /* post-roll, pick up delayed processor output */
5393 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5395 while (latency_skip && !itt.cancel) {
5396 this_chunk = min (latency_skip, bounce_chunk_size);
5397 latency_skip -= this_chunk;
5399 buffers.silence (this_chunk, 0);
5400 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5403 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5404 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5407 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5419 xnow = localtime (&now);
5421 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5422 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5423 boost::shared_ptr<MidiSource> ms;
5426 afs->update_header (position, *xnow, now);
5427 afs->flush_header ();
5428 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5429 Source::Lock lock(ms->mutex());
5430 ms->mark_streaming_write_completed(lock);
5434 /* construct a region to represent the bounced material */
5438 plist.add (Properties::start, 0);
5439 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5440 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5442 result = RegionFactory::create (srcs, plist);
5448 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5449 (*src)->mark_for_remove ();
5450 (*src)->drop_references ();
5454 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5455 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5458 afs->done_with_peakfile_writes ();
5462 _bounce_processing_active = false;
5464 if (need_block_size_reset) {
5465 _engine.main_thread()->drop_buffers ();
5466 track.set_block_size (get_block_size());
5469 unblock_processing ();
5475 Session::gain_automation_buffer() const
5477 return ProcessThread::gain_automation_buffer ();
5481 Session::trim_automation_buffer() const
5483 return ProcessThread::trim_automation_buffer ();
5487 Session::send_gain_automation_buffer() const
5489 return ProcessThread::send_gain_automation_buffer ();
5493 Session::pan_automation_buffer() const
5495 return ProcessThread::pan_automation_buffer ();
5499 Session::get_silent_buffers (ChanCount count)
5501 return ProcessThread::get_silent_buffers (count);
5505 Session::get_scratch_buffers (ChanCount count, bool silence)
5507 return ProcessThread::get_scratch_buffers (count, silence);
5511 Session::get_route_buffers (ChanCount count, bool silence)
5513 return ProcessThread::get_route_buffers (count, silence);
5518 Session::get_mix_buffers (ChanCount count)
5520 return ProcessThread::get_mix_buffers (count);
5524 Session::ntracks () const
5527 boost::shared_ptr<RouteList> r = routes.reader ();
5529 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5530 if (boost::dynamic_pointer_cast<Track> (*i)) {
5539 Session::nbusses () const
5542 boost::shared_ptr<RouteList> r = routes.reader ();
5544 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5545 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5554 Session::add_automation_list(AutomationList *al)
5556 automation_lists[al->id()] = al;
5559 /** @return true if there is at least one record-enabled track, otherwise false */
5561 Session::have_rec_enabled_track () const
5563 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
5567 Session::have_rec_disabled_track () const
5569 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
5572 /** Update the state of our rec-enabled tracks flag */
5574 Session::update_route_record_state ()
5576 boost::shared_ptr<RouteList> rl = routes.reader ();
5577 RouteList::iterator i = rl->begin();
5578 while (i != rl->end ()) {
5580 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5581 if (tr && tr->record_enabled ()) {
5588 int const old = g_atomic_int_get (&_have_rec_enabled_track);
5590 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5592 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5593 RecordStateChanged (); /* EMIT SIGNAL */
5596 for (i = rl->begin(); i != rl->end (); ++i) {
5597 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5598 if (tr && !tr->record_enabled ()) {
5603 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
5605 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
5607 if (record_status() == Recording && record_arm_state_changed ) {
5608 RecordArmStateChanged ();
5614 Session::listen_position_changed ()
5616 boost::shared_ptr<RouteList> r = routes.reader ();
5618 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5619 (*i)->listen_position_changed ();
5624 Session::solo_control_mode_changed ()
5626 /* cancel all solo or all listen when solo control mode changes */
5629 set_solo (get_routes(), false);
5630 } else if (listening()) {
5631 set_listen (get_routes(), false);
5635 /** Called when a property of one of our route groups changes */
5637 Session::route_group_property_changed (RouteGroup* rg)
5639 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
5642 /** Called when a route is added to one of our route groups */
5644 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5646 RouteAddedToRouteGroup (rg, r);
5649 /** Called when a route is removed from one of our route groups */
5651 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5653 update_route_record_state ();
5654 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
5657 boost::shared_ptr<RouteList>
5658 Session::get_tracks () const
5660 boost::shared_ptr<RouteList> rl = routes.reader ();
5661 boost::shared_ptr<RouteList> tl (new RouteList);
5663 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
5664 if (boost::dynamic_pointer_cast<Track> (*r)) {
5665 if (!(*r)->is_auditioner()) {
5673 boost::shared_ptr<RouteList>
5674 Session::get_routes_with_regions_at (framepos_t const p) const
5676 boost::shared_ptr<RouteList> r = routes.reader ();
5677 boost::shared_ptr<RouteList> rl (new RouteList);
5679 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5680 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5685 boost::shared_ptr<Playlist> pl = tr->playlist ();
5690 if (pl->has_region_at (p)) {
5699 Session::goto_end ()
5701 if (_session_range_location) {
5702 request_locate (_session_range_location->end(), false);
5704 request_locate (0, false);
5709 Session::goto_start ()
5711 if (_session_range_location) {
5712 request_locate (_session_range_location->start(), false);
5714 request_locate (0, false);
5719 Session::current_start_frame () const
5721 return _session_range_location ? _session_range_location->start() : 0;
5725 Session::current_end_frame () const
5727 return _session_range_location ? _session_range_location->end() : 0;
5731 Session::set_session_range_location (framepos_t start, framepos_t end)
5733 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
5734 _locations->add (_session_range_location);
5738 Session::step_edit_status_change (bool yn)
5744 send = (_step_editors == 0);
5749 send = (_step_editors == 1);
5752 if (_step_editors > 0) {
5758 StepEditStatusChange (val);
5764 Session::start_time_changed (framepos_t old)
5766 /* Update the auto loop range to match the session range
5767 (unless the auto loop range has been changed by the user)
5770 Location* s = _locations->session_range_location ();
5775 Location* l = _locations->auto_loop_location ();
5777 if (l && l->start() == old) {
5778 l->set_start (s->start(), true);
5783 Session::end_time_changed (framepos_t old)
5785 /* Update the auto loop range to match the session range
5786 (unless the auto loop range has been changed by the user)
5789 Location* s = _locations->session_range_location ();
5794 Location* l = _locations->auto_loop_location ();
5796 if (l && l->end() == old) {
5797 l->set_end (s->end(), true);
5801 std::vector<std::string>
5802 Session::source_search_path (DataType type) const
5806 if (session_dirs.size() == 1) {
5808 case DataType::AUDIO:
5809 sp.push_back (_session_dir->sound_path());
5811 case DataType::MIDI:
5812 sp.push_back (_session_dir->midi_path());
5816 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5817 SessionDirectory sdir (i->path);
5819 case DataType::AUDIO:
5820 sp.push_back (sdir.sound_path());
5822 case DataType::MIDI:
5823 sp.push_back (sdir.midi_path());
5829 if (type == DataType::AUDIO) {
5830 const string sound_path_2X = _session_dir->sound_path_2X();
5831 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
5832 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
5833 sp.push_back (sound_path_2X);
5838 // now check the explicit (possibly user-specified) search path
5841 case DataType::AUDIO:
5842 sp += Searchpath(config.get_audio_search_path ());
5844 case DataType::MIDI:
5845 sp += Searchpath(config.get_midi_search_path ());
5853 Session::ensure_search_path_includes (const string& path, DataType type)
5862 case DataType::AUDIO:
5863 sp += Searchpath(config.get_audio_search_path ());
5865 case DataType::MIDI:
5866 sp += Searchpath (config.get_midi_search_path ());
5870 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
5871 /* No need to add this new directory if it has the same inode as
5872 an existing one; checking inode rather than name prevents duplicated
5873 directories when we are using symlinks.
5875 On Windows, I think we could just do if (*i == path) here.
5877 if (PBD::equivalent_paths (*i, path)) {
5885 case DataType::AUDIO:
5886 config.set_audio_search_path (sp.to_string());
5888 case DataType::MIDI:
5889 config.set_midi_search_path (sp.to_string());
5895 Session::remove_dir_from_search_path (const string& dir, DataType type)
5900 case DataType::AUDIO:
5901 sp = Searchpath(config.get_audio_search_path ());
5903 case DataType::MIDI:
5904 sp = Searchpath (config.get_midi_search_path ());
5911 case DataType::AUDIO:
5912 config.set_audio_search_path (sp.to_string());
5914 case DataType::MIDI:
5915 config.set_midi_search_path (sp.to_string());
5921 boost::shared_ptr<Speakers>
5922 Session::get_speakers()
5928 Session::unknown_processors () const
5932 boost::shared_ptr<RouteList> r = routes.reader ();
5933 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5934 list<string> t = (*i)->unknown_processors ();
5935 copy (t.begin(), t.end(), back_inserter (p));
5945 Session::update_latency (bool playback)
5947 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
5949 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
5953 boost::shared_ptr<RouteList> r = routes.reader ();
5954 framecnt_t max_latency = 0;
5957 /* reverse the list so that we work backwards from the last route to run to the first */
5958 RouteList* rl = routes.reader().get();
5959 r.reset (new RouteList (*rl));
5960 reverse (r->begin(), r->end());
5963 /* compute actual latency values for the given direction and store them all in per-port
5964 structures. this will also publish the same values (to JACK) so that computation of latency
5965 for routes can consistently use public latency values.
5968 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5969 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
5972 /* because we latency compensate playback, our published playback latencies should
5973 be the same for all output ports - all material played back by ardour has
5974 the same latency, whether its caused by plugins or by latency compensation. since
5975 these may differ from the values computed above, reset all playback port latencies
5979 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
5981 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5982 (*i)->set_public_port_latencies (max_latency, playback);
5987 post_playback_latency ();
5991 post_capture_latency ();
5994 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
5998 Session::post_playback_latency ()
6000 set_worst_playback_latency ();
6002 boost::shared_ptr<RouteList> r = routes.reader ();
6004 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6005 if (!(*i)->is_auditioner() && ((*i)->active())) {
6006 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6010 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6011 (*i)->set_latency_compensation (_worst_track_latency);
6016 Session::post_capture_latency ()
6018 set_worst_capture_latency ();
6020 /* reflect any changes in capture latencies into capture offsets
6023 boost::shared_ptr<RouteList> rl = routes.reader();
6024 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6025 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6027 tr->set_capture_offset ();
6033 Session::initialize_latencies ()
6036 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6037 update_latency (false);
6038 update_latency (true);
6041 set_worst_io_latencies ();
6045 Session::set_worst_io_latencies ()
6047 set_worst_playback_latency ();
6048 set_worst_capture_latency ();
6052 Session::set_worst_playback_latency ()
6054 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6058 _worst_output_latency = 0;
6060 if (!_engine.connected()) {
6064 boost::shared_ptr<RouteList> r = routes.reader ();
6066 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6067 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6070 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6074 Session::set_worst_capture_latency ()
6076 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6080 _worst_input_latency = 0;
6082 if (!_engine.connected()) {
6086 boost::shared_ptr<RouteList> r = routes.reader ();
6088 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6089 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6092 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6096 Session::update_latency_compensation (bool force_whole_graph)
6098 bool some_track_latency_changed = false;
6100 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6104 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6106 _worst_track_latency = 0;
6108 boost::shared_ptr<RouteList> r = routes.reader ();
6110 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6111 if (!(*i)->is_auditioner() && ((*i)->active())) {
6113 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6114 some_track_latency_changed = true;
6116 _worst_track_latency = max (tl, _worst_track_latency);
6120 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6121 (some_track_latency_changed ? "yes" : "no")));
6123 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6125 if (some_track_latency_changed || force_whole_graph) {
6126 _engine.update_latencies ();
6130 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6131 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6135 tr->set_capture_offset ();
6140 Session::session_name_is_legal (const string& path)
6142 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6144 for (int i = 0; illegal_chars[i]; ++i) {
6145 if (path.find (illegal_chars[i]) != string::npos) {
6146 return illegal_chars[i];
6154 Session::next_control_id () const
6158 /* the monitor bus remote ID is in a different
6159 * "namespace" than regular routes. its existence doesn't
6160 * affect normal (low) numbered routes.
6167 /* the same about masterbus in Waves Tracks */
6169 if (Profile->get_trx() && _master_out) {
6173 return nroutes() - subtract;
6177 Session::notify_remote_id_change ()
6179 if (deletion_in_progress()) {
6183 switch (Config->get_remote_model()) {
6185 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6191 #ifdef USE_TRACKS_CODE_FEATURES
6192 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6193 * if track order has been changed by user
6195 reconnect_existing_routes(true, true);
6201 Session::sync_order_keys ()
6203 if (deletion_in_progress()) {
6207 /* tell everyone that something has happened to the sort keys
6208 and let them sync up with the change(s)
6209 this will give objects that manage the sort order keys the
6210 opportunity to keep them in sync if they wish to.
6213 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6215 reassign_track_numbers();
6217 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6219 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6223 Session::operation_in_progress (GQuark op) const
6225 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6228 boost::shared_ptr<Port>
6229 Session::ltc_input_port () const
6231 return _ltc_input->nth (0);
6234 boost::shared_ptr<Port>
6235 Session::ltc_output_port () const
6237 return _ltc_output->nth (0);
6241 Session::reconnect_ltc_input ()
6245 string src = Config->get_ltc_source_port();
6247 _ltc_input->disconnect (this);
6249 if (src != _("None") && !src.empty()) {
6250 _ltc_input->nth (0)->connect (src);
6253 if ( ARDOUR::Profile->get_trx () ) {
6254 // Tracks need this signal to update timecode_source_dropdown
6255 MtcOrLtcInputPortChanged (); //emit signal
6261 Session::reconnect_ltc_output ()
6265 string src = Config->get_ltc_output_port();
6267 _ltc_output->disconnect (this);
6269 if (src != _("None") && !src.empty()) {
6270 _ltc_output->nth (0)->connect (src);
6276 Session::set_range_selection (framepos_t start, framepos_t end)
6278 _range_selection = Evoral::Range<framepos_t> (start, end);
6279 #ifdef USE_TRACKS_CODE_FEATURES
6280 follow_playhead_priority ();
6285 Session::set_object_selection (framepos_t start, framepos_t end)
6287 _object_selection = Evoral::Range<framepos_t> (start, end);
6288 #ifdef USE_TRACKS_CODE_FEATURES
6289 follow_playhead_priority ();
6294 Session::clear_range_selection ()
6296 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6297 #ifdef USE_TRACKS_CODE_FEATURES
6298 follow_playhead_priority ();
6303 Session::clear_object_selection ()
6305 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6306 #ifdef USE_TRACKS_CODE_FEATURES
6307 follow_playhead_priority ();