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.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <glibmm/threads.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
36 #include <boost/algorithm/string/erase.hpp>
38 #include "pbd/basename.h"
39 #include "pbd/boost_debug.h"
40 #include "pbd/convert.h"
41 #include "pbd/convert.h"
42 #include "pbd/error.h"
43 #include "pbd/file_utils.h"
45 #include "pbd/search_path.h"
46 #include "pbd/stacktrace.h"
47 #include "pbd/stl_delete.h"
48 #include "pbd/replace_all.h"
49 #include "pbd/unwind.h"
51 #include "ardour/amp.h"
52 #include "ardour/analyser.h"
53 #include "ardour/async_midi_port.h"
54 #include "ardour/audio_buffer.h"
55 #include "ardour/audio_diskstream.h"
56 #include "ardour/audio_port.h"
57 #include "ardour/audio_track.h"
58 #include "ardour/audioengine.h"
59 #include "ardour/audiofilesource.h"
60 #include "ardour/auditioner.h"
61 #include "ardour/buffer_manager.h"
62 #include "ardour/buffer_set.h"
63 #include "ardour/bundle.h"
64 #include "ardour/butler.h"
65 #include "ardour/click.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/data_type.h"
68 #include "ardour/debug.h"
69 #include "ardour/directory_names.h"
70 #ifdef USE_TRACKS_CODE_FEATURES
71 #include "ardour/engine_state_controller.h"
73 #include "ardour/filename_extensions.h"
74 #include "ardour/graph.h"
75 #include "ardour/midiport_manager.h"
76 #include "ardour/scene_changer.h"
77 #include "ardour/midi_patch_manager.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"
110 #include <glibmm/checksum.h>
119 using namespace ARDOUR;
122 bool Session::_disable_all_loaded_plugins = false;
123 bool Session::_bypass_all_loaded_plugins = false;
125 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
126 PBD::Signal1<void,std::string> Session::Dialog;
127 PBD::Signal0<int> Session::AskAboutPendingState;
128 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
129 PBD::Signal0<void> Session::SendFeedback;
130 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
132 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
133 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
134 PBD::Signal2<void,std::string, std::string> Session::Exported;
135 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
136 PBD::Signal0<void> Session::Quit;
137 PBD::Signal0<void> Session::FeedbackDetected;
138 PBD::Signal0<void> Session::SuccessfulGraphSort;
139 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
141 const framecnt_t Session::bounce_chunk_size = 8192;
142 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
143 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
145 // seconds should be added after the region exceeds end marker
146 #ifdef USE_TRACKS_CODE_FEATURES
147 const uint32_t Session::session_end_shift = 5;
149 const uint32_t Session::session_end_shift = 0;
152 /** @param snapshot_name Snapshot name, without .ardour suffix */
153 Session::Session (AudioEngine &eng,
154 const string& fullpath,
155 const string& snapshot_name,
156 BusProfile* bus_profile,
158 : playlists (new SessionPlaylists)
160 , process_function (&Session::process_with_events)
161 , _bounce_processing_active (false)
162 , waiting_for_sync_offset (false)
163 , _base_frame_rate (0)
164 , _current_frame_rate (0)
165 , _nominal_frame_rate (0)
166 , transport_sub_state (0)
167 , _record_status (Disabled)
168 , _transport_frame (0)
169 , _session_range_location (0)
172 , _transport_speed (0)
173 , _default_transport_speed (1.0)
174 , _last_transport_speed (0)
175 , _target_transport_speed (0.0)
176 , auto_play_legal (false)
177 , _last_slave_transport_frame (0)
178 , maximum_output_latency (0)
179 , _requested_return_frame (-1)
180 , current_block_size (0)
181 , _worst_output_latency (0)
182 , _worst_input_latency (0)
183 , _worst_track_latency (0)
184 , _have_captured (false)
185 , _non_soloed_outs_muted (false)
188 , _solo_isolated_cnt (0)
190 , _was_seamless (Config->get_seamless_loop ())
191 , _under_nsm_control (false)
193 , delta_accumulator_cnt (0)
194 , average_slave_delta (1800) // !!! why 1800 ???
196 , have_first_delta_accumulator (false)
197 , _slave_state (Stopped)
198 , _mtc_active (false)
199 , _ltc_active (false)
200 , post_export_sync (false)
201 , post_export_position (0)
203 , _export_started (false)
204 , _export_rolling (false)
205 , _pre_export_mmc_enabled (false)
206 , _name (snapshot_name)
208 , _send_qf_mtc (false)
209 , _pframes_since_last_mtc (0)
210 , session_midi_feedback (0)
212 , loop_changing (false)
214 , _session_dir (new SessionDirectory (fullpath))
215 , _current_snapshot_name (snapshot_name)
217 , state_was_pending (false)
218 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
220 , _save_queued (false)
221 , _last_roll_location (0)
222 , _last_roll_or_reversal_location (0)
223 , _last_record_location (0)
224 , pending_locate_roll (false)
225 , pending_locate_frame (0)
226 , pending_locate_flush (false)
227 , pending_abort (false)
228 , pending_auto_loop (false)
229 , _butler (new Butler (*this))
230 , _post_transport_work (0)
231 , cumulative_rf_motion (0)
233 , _locations (new Locations (*this))
234 , _ignore_skips_updates (false)
235 , _rt_thread_active (false)
236 , _rt_emit_pending (false)
238 , outbound_mtc_timecode_frame (0)
239 , next_quarter_frame_to_send (-1)
240 , _frames_per_timecode_frame (0)
241 , _frames_per_hour (0)
242 , _timecode_frames_per_hour (0)
243 , last_timecode_valid (false)
244 , last_timecode_when (0)
245 , _send_timecode_update (false)
257 , ltc_timecode_offset (0)
258 , ltc_timecode_negative_offset (false)
259 , midi_control_ui (0)
261 , _all_route_group (new RouteGroup (*this, "all"))
262 , routes (new RouteList)
263 , _adding_routes_in_progress (false)
264 , _reconnecting_routes_in_progress (false)
265 , _route_deletion_in_progress (false)
266 , destructive_index (0)
267 , _track_number_decimals(1)
268 , default_fade_steepness (0)
269 , default_fade_msecs (0)
270 , _total_free_4k_blocks (0)
271 , _total_free_4k_blocks_uncertain (false)
272 , no_questions_about_missing_files (false)
275 , _bundles (new BundleList)
276 , _bundle_xml_node (0)
280 , click_emphasis_data (0)
282 , click_emphasis_length (0)
283 , _clicks_cleared (0)
284 , _play_range (false)
285 , _range_selection (-1,-1)
286 , _object_selection (-1,-1)
288 , first_file_data_format_reset (true)
289 , first_file_header_format_reset (true)
290 , have_looped (false)
291 , _have_rec_enabled_track (false)
292 , _have_rec_disabled_track (true)
294 , _suspend_timecode_transmission (0)
295 , _speakers (new Speakers)
297 , ignore_route_processor_changes (false)
304 pthread_mutex_init (&_rt_emit_mutex, 0);
305 pthread_cond_init (&_rt_emit_cond, 0);
307 pre_engine_init (fullpath);
311 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
313 #ifdef USE_TRACKS_CODE_FEATURES
314 sr = EngineStateController::instance()->get_current_sample_rate();
316 if (ensure_engine (sr)) {
318 throw SessionException (_("Cannot connect to audio/midi engine"));
321 // set samplerate for plugins added early
322 // e.g from templates or MB channelstrip
323 set_block_size (_engine.samples_per_cycle());
324 set_frame_rate (_engine.sample_rate());
326 if (create (mix_template, bus_profile)) {
328 throw SessionException (_("Session initialization failed"));
331 /* if a mix template was provided, then ::create() will
332 * have copied it into the session and we need to load it
333 * so that we have the state ready for ::set_state()
334 * after the engine is started.
336 * Note that we do NOT try to get the sample rate from
337 * the template at this time, though doing so would
338 * be easy if we decided this was an appropriate part
342 if (!mix_template.empty()) {
343 if (load_state (_current_snapshot_name)) {
344 throw SessionException (_("Failed to load template/snapshot state"));
346 store_recent_templates (mix_template);
349 /* load default session properties - if any */
354 if (load_state (_current_snapshot_name)) {
355 throw SessionException (_("Failed to load state"));
358 /* try to get sample rate from XML state so that we
359 * can influence the SR if we set up the audio
364 const XMLProperty* prop;
365 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
366 sr = atoi (prop->value());
370 if (ensure_engine (sr)) {
372 throw SessionException (_("Cannot connect to audio/midi engine"));
376 if (post_engine_init ()) {
378 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
381 store_recent_sessions (_name, _path);
383 bool was_dirty = dirty();
385 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
387 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
388 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
391 DirtyChanged (); /* EMIT SIGNAL */
394 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
395 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
397 emit_thread_start ();
399 /* hook us up to the engine since we are now completely constructed */
401 BootMessage (_("Connect to engine"));
403 _engine.set_session (this);
404 _engine.reset_timebase ();
406 #ifdef USE_TRACKS_CODE_FEATURES
408 EngineStateController::instance()->set_session(this);
411 if ( ARDOUR::Profile->get_trx () ) {
413 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
414 * each available input must have corresponding track when session starts.
417 uint32_t how_many (0);
419 std::vector<std::string> inputs;
420 EngineStateController::instance()->get_physical_audio_inputs(inputs);
422 how_many = inputs.size();
424 list<boost::shared_ptr<AudioTrack> > tracks;
426 // Track names after driver
427 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
428 string track_name = "";
429 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
431 track_name = inputs[i];
432 replace_all (track_name, "system:capture", "");
434 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
435 tracks.insert(tracks.begin(), single_track.front());
437 } else { // Default track names
438 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
441 if (tracks.size() != how_many) {
443 throw failed_constructor ();
452 BootMessage (_("Session loading complete"));
464 Session::ensure_engine (uint32_t desired_sample_rate)
466 if (_engine.current_backend() == 0) {
467 /* backend is unknown ... */
468 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
469 if (r.get_value_or (-1) != 0) {
472 } else if (_engine.setup_required()) {
473 /* backend is known, but setup is needed */
474 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
475 if (r.get_value_or (-1) != 0) {
478 } else if (!_engine.running()) {
479 if (_engine.start()) {
484 /* at this point the engine should be running
487 if (!_engine.running()) {
491 return immediately_post_engine ();
496 Session::immediately_post_engine ()
498 /* Do various initializations that should take place directly after we
499 * know that the engine is running, but before we either create a
500 * session or set state for an existing one.
503 if (how_many_dsp_threads () > 1) {
504 /* For now, only create the graph if we are using >1 DSP threads, as
505 it is a bit slower than the old code with 1 thread.
507 _process_graph.reset (new Graph (*this));
510 /* every time we reconnect, recompute worst case output latencies */
512 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
514 if (synced_to_engine()) {
515 _engine.transport_stop ();
518 if (config.get_jack_time_master()) {
519 _engine.transport_locate (_transport_frame);
523 BootMessage (_("Set up LTC"));
525 BootMessage (_("Set up Click"));
527 BootMessage (_("Set up standard connections"));
531 catch (failed_constructor& err) {
535 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
537 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
545 vector<void*> debug_pointers;
547 /* if we got to here, leaving pending capture state around
551 remove_pending_capture_state ();
555 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
557 /* disconnect from any and all signals that we are connected to */
561 /* shutdown control surface protocols while we still have ports
562 and the engine to move data to any devices.
565 ControlProtocolManager::instance().drop_protocols ();
567 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
569 _engine.remove_session ();
571 #ifdef USE_TRACKS_CODE_FEATURES
572 EngineStateController::instance()->remove_session();
575 /* deregister all ports - there will be no process or any other
576 * callbacks from the engine any more.
579 Port::PortDrop (); /* EMIT SIGNAL */
583 /* clear history so that no references to objects are held any more */
587 /* clear state tree so that no references to objects are held any more */
592 /* reset dynamic state version back to default */
594 Stateful::loading_state_version = 0;
596 _butler->drop_references ();
600 delete _all_route_group;
602 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
603 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
607 if (click_data != default_click) {
608 delete [] click_data;
611 if (click_emphasis_data != default_click_emphasis) {
612 delete [] click_emphasis_data;
617 /* need to remove auditioner before monitoring section
618 * otherwise it is re-connected */
621 /* drop references to routes held by the monitoring section
622 * specifically _monitor_out aux/listen references */
623 remove_monitor_section();
625 /* clear out any pending dead wood from RCU managed objects */
630 AudioDiskstream::free_working_buffers();
632 /* tell everyone who is still standing that we're about to die */
635 /* tell everyone to drop references and delete objects as we go */
637 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
638 RegionFactory::delete_all_regions ();
640 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
642 /* reset these three references to special routes before we do the usual route delete thing */
644 _master_out.reset ();
645 _monitor_out.reset ();
648 RCUWriter<RouteList> writer (routes);
649 boost::shared_ptr<RouteList> r = writer.get_copy ();
651 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
652 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
653 (*i)->drop_references ();
657 /* writer goes out of scope and updates master */
662 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
663 Glib::Threads::Mutex::Lock lm (source_lock);
664 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
665 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
666 i->second->drop_references ();
672 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
675 emit_thread_terminate ();
677 pthread_cond_destroy (&_rt_emit_cond);
678 pthread_mutex_destroy (&_rt_emit_mutex);
680 delete _scene_changer; _scene_changer = 0;
681 delete midi_control_ui; midi_control_ui = 0;
683 delete _mmc; _mmc = 0;
684 delete _midi_ports; _midi_ports = 0;
685 delete _locations; _locations = 0;
689 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
691 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
692 boost_debug_list_ptrs ();
697 Session::setup_ltc ()
701 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
702 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
704 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
705 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
708 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
709 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
711 reconnect_ltc_input ();
714 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
715 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
718 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
719 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
721 reconnect_ltc_output ();
724 /* fix up names of LTC ports because we don't want the normal
725 * IO style of NAME/TYPE-{in,out}N
728 _ltc_input->nth (0)->set_name (X_("LTC-in"));
729 _ltc_output->nth (0)->set_name (X_("LTC-out"));
733 Session::setup_click ()
737 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
738 boost::shared_ptr<AutomationControl> gain_control = boost::shared_ptr<Amp::GainControl> (new Amp::GainControl (*this, Evoral::Parameter(GainAutomation), gl));
740 _click_io.reset (new ClickIO (*this, X_("Click")));
741 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
742 _click_gain->activate ();
744 setup_click_state (state_tree->root());
746 setup_click_state (0);
751 Session::setup_click_state (const XMLNode* node)
753 const XMLNode* child = 0;
755 if (node && (child = find_named_node (*node, "Click")) != 0) {
757 /* existing state for Click */
760 if (Stateful::loading_state_version < 3000) {
761 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
763 const XMLNodeList& children (child->children());
764 XMLNodeList::const_iterator i = children.begin();
765 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
767 if (i != children.end()) {
768 c = _click_gain->set_state (**i, Stateful::loading_state_version);
774 _clicking = Config->get_clicking ();
778 error << _("could not setup Click I/O") << endmsg;
785 /* default state for Click: dual-mono to first 2 physical outputs */
788 _engine.get_physical_outputs (DataType::AUDIO, outs);
790 for (uint32_t physport = 0; physport < 2; ++physport) {
791 if (outs.size() > physport) {
792 if (_click_io->add_port (outs[physport], this)) {
793 // relax, even though its an error
798 if (_click_io->n_ports () > ChanCount::ZERO) {
799 _clicking = Config->get_clicking ();
805 Session::setup_bundles ()
809 RCUWriter<BundleList> writer (_bundles);
810 boost::shared_ptr<BundleList> b = writer.get_copy ();
811 for (BundleList::iterator i = b->begin(); i != b->end();) {
812 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
820 vector<string> inputs[DataType::num_types];
821 vector<string> outputs[DataType::num_types];
822 for (uint32_t i = 0; i < DataType::num_types; ++i) {
823 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
824 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
827 /* Create a set of Bundle objects that map
828 to the physical I/O currently available. We create both
829 mono and stereo bundles, so that the common cases of mono
830 and stereo tracks get bundles to put in their mixer strip
831 in / out menus. There may be a nicer way of achieving that;
832 it doesn't really scale that well to higher channel counts
835 /* mono output bundles */
837 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
839 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
841 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
843 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
846 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
847 c->add_channel (_("mono"), DataType::AUDIO);
848 c->set_port (0, outputs[DataType::AUDIO][np]);
850 add_bundle (c, false);
853 /* stereo output bundles */
855 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
856 if (np + 1 < outputs[DataType::AUDIO].size()) {
858 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
859 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
860 c->add_channel (_("L"), DataType::AUDIO);
861 c->set_port (0, outputs[DataType::AUDIO][np]);
862 c->add_channel (_("R"), DataType::AUDIO);
863 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
865 add_bundle (c, false);
869 /* mono input bundles */
871 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
873 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
875 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
877 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
880 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
881 c->add_channel (_("mono"), DataType::AUDIO);
882 c->set_port (0, inputs[DataType::AUDIO][np]);
884 add_bundle (c, false);
887 /* stereo input bundles */
889 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
890 if (np + 1 < inputs[DataType::AUDIO].size()) {
892 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
894 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
895 c->add_channel (_("L"), DataType::AUDIO);
896 c->set_port (0, inputs[DataType::AUDIO][np]);
897 c->add_channel (_("R"), DataType::AUDIO);
898 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
900 add_bundle (c, false);
904 /* MIDI input bundles */
906 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
907 string n = inputs[DataType::MIDI][np];
908 std::string pn = _engine.get_pretty_name_by_name (n);
912 boost::erase_first (n, X_("alsa_pcm:"));
914 boost::shared_ptr<Bundle> c (new Bundle (n, false));
915 c->add_channel ("", DataType::MIDI);
916 c->set_port (0, inputs[DataType::MIDI][np]);
917 add_bundle (c, false);
920 /* MIDI output bundles */
922 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
923 string n = outputs[DataType::MIDI][np];
924 std::string pn = _engine.get_pretty_name_by_name (n);
928 boost::erase_first (n, X_("alsa_pcm:"));
930 boost::shared_ptr<Bundle> c (new Bundle (n, true));
931 c->add_channel ("", DataType::MIDI);
932 c->set_port (0, outputs[DataType::MIDI][np]);
933 add_bundle (c, false);
936 // we trust the backend to only calls us if there's a change
937 BundleAddedOrRemoved (); /* EMIT SIGNAL */
941 Session::auto_connect_master_bus ()
943 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
947 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
948 // In this case it means "Multi Out" output mode
949 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
953 /* if requested auto-connect the outputs to the first N physical ports.
956 uint32_t limit = _master_out->n_outputs().n_total();
957 vector<string> outputs[DataType::num_types];
959 for (uint32_t i = 0; i < DataType::num_types; ++i) {
960 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
963 for (uint32_t n = 0; n < limit; ++n) {
964 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
966 if (outputs[p->type()].size() > n) {
967 connect_to = outputs[p->type()][n];
970 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
971 if (_master_out->output()->connect (p, connect_to, this)) {
972 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
981 Session::remove_monitor_section ()
983 if (!_monitor_out || Profile->get_trx()) {
987 /* force reversion to Solo-In-Place */
988 Config->set_solo_control_is_listen_control (false);
990 /* if we are auditioning, cancel it ... this is a workaround
991 to a problem (auditioning does not execute the process graph,
992 which is needed to remove routes when using >1 core for processing)
997 /* Hold process lock while doing this so that we don't hear bits and
998 * pieces of audio as we work on each route.
1001 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1003 /* Connect tracks to monitor section. Note that in an
1004 existing session, the internal sends will already exist, but we want the
1005 routes to notice that they connect to the control out specifically.
1009 boost::shared_ptr<RouteList> r = routes.reader ();
1010 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1012 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1014 if ((*x)->is_monitor()) {
1016 } else if ((*x)->is_master()) {
1019 (*x)->remove_aux_or_listen (_monitor_out);
1024 remove_route (_monitor_out);
1025 auto_connect_master_bus ();
1028 auditioner->connect ();
1030 Config->ParameterChanged ("use-monitor-bus");
1034 Session::add_monitor_section ()
1038 if (_monitor_out || !_master_out || Profile->get_trx()) {
1042 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1048 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1049 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
1052 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1053 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1054 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1056 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1061 add_routes (rl, false, false, false);
1063 assert (_monitor_out);
1065 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1066 are undefined, at best.
1069 uint32_t limit = _monitor_out->n_inputs().n_audio();
1073 /* connect the inputs to the master bus outputs. this
1074 * represents a separate data feed from the internal sends from
1075 * each route. as of jan 2011, it allows the monitor section to
1076 * conditionally ignore either the internal sends or the normal
1077 * input feed, but we should really find a better way to do
1081 _master_out->output()->disconnect (this);
1083 for (uint32_t n = 0; n < limit; ++n) {
1084 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1085 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1088 string connect_to = o->name();
1089 if (_monitor_out->input()->connect (p, connect_to, this)) {
1090 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1098 /* if monitor section is not connected, connect it to physical outs
1101 if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
1103 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1105 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1108 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1110 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1111 Config->get_monitor_bus_preferred_bundle())
1117 /* Monitor bus is audio only */
1119 vector<string> outputs[DataType::num_types];
1121 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1122 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1125 uint32_t mod = outputs[DataType::AUDIO].size();
1126 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1130 for (uint32_t n = 0; n < limit; ++n) {
1132 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1134 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1135 connect_to = outputs[DataType::AUDIO][n % mod];
1138 if (!connect_to.empty()) {
1139 if (_monitor_out->output()->connect (p, connect_to, this)) {
1140 error << string_compose (
1141 _("cannot connect control output %1 to %2"),
1152 /* Hold process lock while doing this so that we don't hear bits and
1153 * pieces of audio as we work on each route.
1156 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1158 /* Connect tracks to monitor section. Note that in an
1159 existing session, the internal sends will already exist, but we want the
1160 routes to notice that they connect to the control out specifically.
1164 boost::shared_ptr<RouteList> rls = routes.reader ();
1166 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1168 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1170 if ((*x)->is_monitor()) {
1172 } else if ((*x)->is_master()) {
1175 (*x)->enable_monitor_send ();
1180 auditioner->connect ();
1182 Config->ParameterChanged ("use-monitor-bus");
1186 Session::reset_monitor_section ()
1188 /* Process lock should be held by the caller.*/
1190 if (!_monitor_out || Profile->get_trx()) {
1194 uint32_t limit = _master_out->n_outputs().n_audio();
1196 /* connect the inputs to the master bus outputs. this
1197 * represents a separate data feed from the internal sends from
1198 * each route. as of jan 2011, it allows the monitor section to
1199 * conditionally ignore either the internal sends or the normal
1200 * input feed, but we should really find a better way to do
1204 _master_out->output()->disconnect (this);
1205 _monitor_out->output()->disconnect (this);
1207 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1208 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1210 for (uint32_t n = 0; n < limit; ++n) {
1211 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1212 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1215 string connect_to = o->name();
1216 if (_monitor_out->input()->connect (p, connect_to, this)) {
1217 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1224 /* connect monitor section to physical outs
1227 if (Config->get_auto_connect_standard_busses()) {
1229 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1231 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1234 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1236 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1237 Config->get_monitor_bus_preferred_bundle())
1243 /* Monitor bus is audio only */
1245 vector<string> outputs[DataType::num_types];
1247 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1248 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1251 uint32_t mod = outputs[DataType::AUDIO].size();
1252 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1256 for (uint32_t n = 0; n < limit; ++n) {
1258 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1260 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1261 connect_to = outputs[DataType::AUDIO][n % mod];
1264 if (!connect_to.empty()) {
1265 if (_monitor_out->output()->connect (p, connect_to, this)) {
1266 error << string_compose (
1267 _("cannot connect control output %1 to %2"),
1278 /* Connect tracks to monitor section. Note that in an
1279 existing session, the internal sends will already exist, but we want the
1280 routes to notice that they connect to the control out specifically.
1284 boost::shared_ptr<RouteList> rls = routes.reader ();
1286 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1288 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1290 if ((*x)->is_monitor()) {
1292 } else if ((*x)->is_master()) {
1295 (*x)->enable_monitor_send ();
1301 Session::hookup_io ()
1303 /* stop graph reordering notifications from
1304 causing resorts, etc.
1307 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1311 /* we delay creating the auditioner till now because
1312 it makes its own connections to ports.
1316 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1318 throw failed_constructor ();
1320 a->use_new_diskstream ();
1324 catch (failed_constructor& err) {
1325 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1329 /* load bundles, which we may have postponed earlier on */
1330 if (_bundle_xml_node) {
1331 load_bundles (*_bundle_xml_node);
1332 delete _bundle_xml_node;
1335 /* Tell all IO objects to connect themselves together */
1337 IO::enable_connecting ();
1339 /* Now tell all "floating" ports to connect to whatever
1340 they should be connected to.
1343 AudioEngine::instance()->reconnect_ports ();
1345 /* Anyone who cares about input state, wake up and do something */
1347 IOConnectionsComplete (); /* EMIT SIGNAL */
1349 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1351 /* now handle the whole enchilada as if it was one
1352 graph reorder event.
1357 /* update the full solo state, which can't be
1358 correctly determined on a per-route basis, but
1359 needs the global overview that only the session
1363 update_route_solo_state ();
1367 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1369 boost::shared_ptr<Track> track = wp.lock ();
1374 boost::shared_ptr<Playlist> playlist;
1376 if ((playlist = track->playlist()) != 0) {
1377 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1378 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1379 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1384 Session::record_enabling_legal () const
1386 /* this used to be in here, but survey says.... we don't need to restrict it */
1387 // if (record_status() == Recording) {
1391 if (Config->get_all_safe()) {
1398 Session::set_track_monitor_input_status (bool yn)
1400 boost::shared_ptr<RouteList> rl = routes.reader ();
1401 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1402 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1403 if (tr && tr->record_enabled ()) {
1404 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1405 tr->request_input_monitoring (yn);
1411 Session::auto_punch_start_changed (Location* location)
1413 replace_event (SessionEvent::PunchIn, location->start());
1415 if (get_record_enabled() && config.get_punch_in()) {
1416 /* capture start has been changed, so save new pending state */
1417 save_state ("", true);
1422 Session::auto_punch_end_changed (Location* location)
1424 framepos_t when_to_stop = location->end();
1425 // when_to_stop += _worst_output_latency + _worst_input_latency;
1426 replace_event (SessionEvent::PunchOut, when_to_stop);
1430 Session::auto_punch_changed (Location* location)
1432 framepos_t when_to_stop = location->end();
1434 replace_event (SessionEvent::PunchIn, location->start());
1435 //when_to_stop += _worst_output_latency + _worst_input_latency;
1436 replace_event (SessionEvent::PunchOut, when_to_stop);
1439 /** @param loc A loop location.
1440 * @param pos Filled in with the start time of the required fade-out (in session frames).
1441 * @param length Filled in with the length of the required fade-out.
1444 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1446 pos = max (loc->start(), loc->end() - 64);
1447 length = loc->end() - pos;
1451 Session::auto_loop_changed (Location* location)
1453 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1456 auto_loop_declick_range (location, dcp, dcl);
1458 if (transport_rolling() && play_loop) {
1460 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1462 // if (_transport_frame > location->end()) {
1464 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1465 // relocate to beginning of loop
1466 clear_events (SessionEvent::LocateRoll);
1468 request_locate (location->start(), true);
1471 else if (Config->get_seamless_loop() && !loop_changing) {
1473 // schedule a locate-roll to refill the diskstreams at the
1474 // previous loop end
1475 loop_changing = true;
1477 if (location->end() > last_loopend) {
1478 clear_events (SessionEvent::LocateRoll);
1479 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1485 clear_events (SessionEvent::AutoLoopDeclick);
1486 clear_events (SessionEvent::AutoLoop);
1489 /* possibly move playhead if not rolling; if we are rolling we'll move
1490 to the loop start on stop if that is appropriate.
1495 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1496 if (pos == location->start()) {
1497 request_locate (pos);
1502 last_loopend = location->end();
1507 Session::set_auto_punch_location (Location* location)
1511 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1512 punch_connections.drop_connections();
1513 existing->set_auto_punch (false, this);
1514 remove_event (existing->start(), SessionEvent::PunchIn);
1515 clear_events (SessionEvent::PunchOut);
1516 auto_punch_location_changed (0);
1521 if (location == 0) {
1525 if (location->end() <= location->start()) {
1526 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1530 punch_connections.drop_connections ();
1532 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1533 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1534 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1536 location->set_auto_punch (true, this);
1538 auto_punch_changed (location);
1540 auto_punch_location_changed (location);
1544 Session::set_session_extents (framepos_t start, framepos_t end)
1547 if ((existing = _locations->session_range_location()) == 0) {
1548 //if there is no existing session, we need to make a new session location (should never happen)
1549 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1553 error << _("Session: you can't use that location for session start/end)") << endmsg;
1557 existing->set( start, end );
1563 Session::set_auto_loop_location (Location* location)
1567 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1568 loop_connections.drop_connections ();
1569 existing->set_auto_loop (false, this);
1570 remove_event (existing->end(), SessionEvent::AutoLoop);
1573 auto_loop_declick_range (existing, dcp, dcl);
1574 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1575 auto_loop_location_changed (0);
1580 if (location == 0) {
1584 if (location->end() <= location->start()) {
1585 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1589 last_loopend = location->end();
1591 loop_connections.drop_connections ();
1593 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1594 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1595 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1596 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1598 location->set_auto_loop (true, this);
1600 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1601 // set all tracks to use internal looping
1602 boost::shared_ptr<RouteList> rl = routes.reader ();
1603 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1604 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1605 if (tr && !tr->hidden()) {
1606 tr->set_loop (location);
1611 /* take care of our stuff first */
1613 auto_loop_changed (location);
1615 /* now tell everyone else */
1617 auto_loop_location_changed (location);
1621 Session::update_marks (Location*)
1627 Session::update_skips (Location* loc, bool consolidate)
1629 if (_ignore_skips_updates) {
1633 Locations::LocationList skips;
1636 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1637 consolidate_skips (loc);
1640 sync_locations_to_skips ();
1646 Session::consolidate_skips (Location* loc)
1648 Locations::LocationList all_locations = _locations->list ();
1650 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1652 if (!(*l)->is_skip ()) {
1657 /* don't test against self */
1664 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1665 case Evoral::OverlapInternal:
1666 case Evoral::OverlapExternal:
1667 case Evoral::OverlapStart:
1668 case Evoral::OverlapEnd:
1669 /* adjust new location to cover existing one */
1670 loc->set_start (min (loc->start(), (*l)->start()));
1671 loc->set_end (max (loc->end(), (*l)->end()));
1672 /* we don't need this one any more */
1673 _locations->remove (*l);
1674 /* the location has been deleted, so remove reference to it in our local list */
1675 l = all_locations.erase (l);
1678 case Evoral::OverlapNone:
1686 Session::sync_locations_to_skips ()
1688 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1689 * Session::_sync_locations_to_skips() from the audioengine thread.
1691 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1695 Session::_sync_locations_to_skips ()
1697 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1699 Locations::LocationList const & locs (_locations->list());
1701 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1703 Location* location = *i;
1705 if (location->is_skip() && location->is_skipping()) {
1706 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1714 Session::location_added (Location *location)
1716 if (location->is_auto_punch()) {
1717 set_auto_punch_location (location);
1720 if (location->is_auto_loop()) {
1721 set_auto_loop_location (location);
1724 if (location->is_session_range()) {
1725 /* no need for any signal handling or event setting with the session range,
1726 because we keep a direct reference to it and use its start/end directly.
1728 _session_range_location = location;
1731 if (location->is_mark()) {
1732 /* listen for per-location signals that require us to do any * global updates for marks */
1734 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1735 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1736 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1737 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1740 if (location->is_skip()) {
1741 /* listen for per-location signals that require us to update skip-locate events */
1743 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1744 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1745 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1746 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1748 update_skips (location, true);
1755 Session::location_removed (Location *location)
1757 if (location->is_auto_loop()) {
1758 set_auto_loop_location (0);
1759 set_track_loop (false);
1762 if (location->is_auto_punch()) {
1763 set_auto_punch_location (0);
1766 if (location->is_session_range()) {
1767 /* this is never supposed to happen */
1768 error << _("programming error: session range removed!") << endl;
1771 if (location->is_skip()) {
1773 update_skips (location, false);
1780 Session::locations_changed ()
1782 _locations->apply (*this, &Session::_locations_changed);
1786 Session::_locations_changed (const Locations::LocationList& locations)
1788 /* There was some mass-change in the Locations object.
1790 We might be re-adding a location here but it doesn't actually matter
1791 for all the locations that the Session takes an interest in.
1795 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1796 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1797 location_added (*i);
1801 update_skips (NULL, false);
1805 Session::enable_record ()
1807 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1808 /* no recording at anything except normal speed */
1813 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1815 if (rs == Recording) {
1819 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1821 _last_record_location = _transport_frame;
1822 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1824 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1825 set_track_monitor_input_status (true);
1828 RecordStateChanged ();
1835 Session::disable_record (bool rt_context, bool force)
1839 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1841 if (!Config->get_latched_record_enable () || force) {
1842 g_atomic_int_set (&_record_status, Disabled);
1843 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1845 if (rs == Recording) {
1846 g_atomic_int_set (&_record_status, Enabled);
1850 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1851 set_track_monitor_input_status (false);
1854 RecordStateChanged (); /* emit signal */
1857 remove_pending_capture_state ();
1863 Session::step_back_from_record ()
1865 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1867 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1868 set_track_monitor_input_status (false);
1871 RecordStateChanged (); /* emit signal */
1876 Session::maybe_enable_record ()
1878 if (_step_editors > 0) {
1882 g_atomic_int_set (&_record_status, Enabled);
1884 /* This function is currently called from somewhere other than an RT thread.
1885 This save_state() call therefore doesn't impact anything. Doing it here
1886 means that we save pending state of which sources the next record will use,
1887 which gives us some chance of recovering from a crash during the record.
1890 save_state ("", true);
1892 if (_transport_speed) {
1893 if (!config.get_punch_in()) {
1897 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1898 RecordStateChanged (); /* EMIT SIGNAL */
1905 Session::audible_frame () const
1911 offset = worst_playback_latency ();
1913 if (synced_to_engine()) {
1914 /* Note: this is basically just sync-to-JACK */
1915 tf = _engine.transport_frame();
1917 tf = _transport_frame;
1922 if (!non_realtime_work_pending()) {
1926 /* Check to see if we have passed the first guaranteed
1927 audible frame past our last start position. if not,
1928 return that last start point because in terms
1929 of audible frames, we have not moved yet.
1931 `Start position' in this context means the time we last
1932 either started, located, or changed transport direction.
1935 if (_transport_speed > 0.0f) {
1937 if (!play_loop || !have_looped) {
1938 if (tf < _last_roll_or_reversal_location + offset) {
1939 return _last_roll_or_reversal_location;
1947 } else if (_transport_speed < 0.0f) {
1949 /* XXX wot? no backward looping? */
1951 if (tf > _last_roll_or_reversal_location - offset) {
1952 return _last_roll_or_reversal_location;
1964 Session::set_frame_rate (framecnt_t frames_per_second)
1966 /** \fn void Session::set_frame_size(framecnt_t)
1967 the AudioEngine object that calls this guarantees
1968 that it will not be called while we are also in
1969 ::process(). Its fine to do things that block
1973 _base_frame_rate = frames_per_second;
1974 _nominal_frame_rate = frames_per_second;
1979 reset_write_sources (false);
1981 // XXX we need some equivalent to this, somehow
1982 // SndFileSource::setup_standard_crossfades (frames_per_second);
1986 /* XXX need to reset/reinstantiate all LADSPA plugins */
1990 Session::set_block_size (pframes_t nframes)
1992 /* the AudioEngine guarantees
1993 that it will not be called while we are also in
1994 ::process(). It is therefore fine to do things that block
1999 current_block_size = nframes;
2003 boost::shared_ptr<RouteList> r = routes.reader ();
2005 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2006 (*i)->set_block_size (nframes);
2009 boost::shared_ptr<RouteList> rl = routes.reader ();
2010 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2011 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2013 tr->set_block_size (nframes);
2017 set_worst_io_latencies ();
2023 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2025 boost::shared_ptr<Route> r2;
2027 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2028 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2032 /* make a copy of the existing list of routes that feed r1 */
2034 Route::FedBy existing (r1->fed_by());
2036 /* for each route that feeds r1, recurse, marking it as feeding
2040 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2041 if (!(r2 = i->r.lock ())) {
2042 /* (*i) went away, ignore it */
2046 /* r2 is a route that feeds r1 which somehow feeds base. mark
2047 base as being fed by r2
2050 rbase->add_fed_by (r2, i->sends_only);
2054 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2058 if (r1->feeds (r2) && r2->feeds (r1)) {
2062 /* now recurse, so that we can mark base as being fed by
2063 all routes that feed r2
2066 trace_terminal (r2, rbase);
2073 Session::resort_routes ()
2075 /* don't do anything here with signals emitted
2076 by Routes during initial setup or while we
2077 are being destroyed.
2080 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2084 if (_route_deletion_in_progress) {
2089 RCUWriter<RouteList> writer (routes);
2090 boost::shared_ptr<RouteList> r = writer.get_copy ();
2091 resort_routes_using (r);
2092 /* writer goes out of scope and forces update */
2096 boost::shared_ptr<RouteList> rl = routes.reader ();
2097 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2098 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2100 const Route::FedBy& fb ((*i)->fed_by());
2102 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2103 boost::shared_ptr<Route> sf = f->r.lock();
2105 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2113 /** This is called whenever we need to rebuild the graph of how we will process
2115 * @param r List of routes, in any order.
2119 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2121 /* We are going to build a directed graph of our routes;
2122 this is where the edges of that graph are put.
2127 /* Go through all routes doing two things:
2129 * 1. Collect the edges of the route graph. Each of these edges
2130 * is a pair of routes, one of which directly feeds the other
2131 * either by a JACK connection or by an internal send.
2133 * 2. Begin the process of making routes aware of which other
2134 * routes directly or indirectly feed them. This information
2135 * is used by the solo code.
2138 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2140 /* Clear out the route's list of direct or indirect feeds */
2141 (*i)->clear_fed_by ();
2143 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2145 bool via_sends_only;
2147 /* See if this *j feeds *i according to the current state of the JACK
2148 connections and internal sends.
2150 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2151 /* add the edge to the graph (part #1) */
2152 edges.add (*j, *i, via_sends_only);
2153 /* tell the route (for part #2) */
2154 (*i)->add_fed_by (*j, via_sends_only);
2159 /* Attempt a topological sort of the route graph */
2160 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2162 if (sorted_routes) {
2163 /* We got a satisfactory topological sort, so there is no feedback;
2166 Note: the process graph rechain does not require a
2167 topologically-sorted list, but hey ho.
2169 if (_process_graph) {
2170 _process_graph->rechain (sorted_routes, edges);
2173 _current_route_graph = edges;
2175 /* Complete the building of the routes' lists of what directly
2176 or indirectly feeds them.
2178 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2179 trace_terminal (*i, *i);
2182 *r = *sorted_routes;
2185 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2186 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2187 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2188 (*i)->name(), (*i)->order_key ()));
2192 SuccessfulGraphSort (); /* EMIT SIGNAL */
2195 /* The topological sort failed, so we have a problem. Tell everyone
2196 and stick to the old graph; this will continue to be processed, so
2197 until the feedback is fixed, what is played back will not quite
2198 reflect what is actually connected. Note also that we do not
2199 do trace_terminal here, as it would fail due to an endless recursion,
2200 so the solo code will think that everything is still connected
2204 FeedbackDetected (); /* EMIT SIGNAL */
2209 /** Find a route name starting with \a base, maybe followed by the
2210 * lowest \a id. \a id will always be added if \a definitely_add_number
2211 * is true on entry; otherwise it will only be added if required
2212 * to make the name unique.
2214 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2215 * The available route name with the lowest ID will be used, and \a id
2216 * will be set to the ID.
2218 * \return false if a route name could not be found, and \a track_name
2219 * and \a id do not reflect a free route name.
2222 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2224 /* the base may conflict with ports that do not belong to existing
2225 routes, but hidden objects like the click track. So check port names
2226 before anything else.
2229 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2230 if (base == *reserved) {
2231 /* Check if this reserved name already exists, and if
2232 so, disallow it without a numeric suffix.
2234 if (route_by_name (*reserved)) {
2235 definitely_add_number = true;
2244 if (!definitely_add_number && route_by_name (base) == 0) {
2245 /* juse use the base */
2251 name = string_compose ("%1 %2", base, id);
2253 if (route_by_name (name) == 0) {
2259 } while (id < (UINT_MAX-1));
2264 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2266 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2268 in = ChanCount::ZERO;
2269 out = ChanCount::ZERO;
2271 boost::shared_ptr<RouteList> r = routes.reader ();
2273 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2274 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2275 if (tr && !tr->is_auditioner()) {
2276 in += tr->n_inputs();
2277 out += tr->n_outputs();
2283 Session::default_track_name_pattern (DataType t)
2286 case DataType::AUDIO:
2287 if (Profile->get_trx()) {
2294 case DataType::MIDI:
2301 /** Caller must not hold process lock
2302 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2303 * @param instrument plugin info for the instrument to insert pre-fader, if any
2305 list<boost::shared_ptr<MidiTrack> >
2306 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2307 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2310 uint32_t track_id = 0;
2312 RouteList new_routes;
2313 list<boost::shared_ptr<MidiTrack> > ret;
2315 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2316 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2319 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2320 error << "cannot find name for new midi track" << endmsg;
2324 boost::shared_ptr<MidiTrack> track;
2327 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2329 if (track->init ()) {
2333 track->use_new_diskstream();
2335 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2336 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2339 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2340 if (track->input()->ensure_io (input, false, this)) {
2341 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2345 if (track->output()->ensure_io (output, false, this)) {
2346 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2351 track->non_realtime_input_change();
2354 route_group->add (track);
2357 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2359 if (Config->get_remote_model() == UserOrdered) {
2360 track->set_remote_control_id (next_control_id());
2363 new_routes.push_back (track);
2364 ret.push_back (track);
2366 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2369 catch (failed_constructor &err) {
2370 error << _("Session: could not create new midi track.") << endmsg;
2374 catch (AudioEngine::PortRegistrationFailure& pfe) {
2376 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;
2384 if (!new_routes.empty()) {
2385 StateProtector sp (this);
2386 if (Profile->get_trx()) {
2387 add_routes (new_routes, false, false, false);
2389 add_routes (new_routes, true, true, false);
2393 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2394 PluginPtr plugin = instrument->load (*this);
2395 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2396 (*r)->add_processor (p, PreFader);
2406 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2408 boost::shared_ptr<Route> midi_track (wmt.lock());
2414 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2416 if (change.after.n_audio() <= change.before.n_audio()) {
2420 /* new audio ports: make sure the audio goes somewhere useful,
2421 unless the user has no-auto-connect selected.
2423 The existing ChanCounts don't matter for this call as they are only
2424 to do with matching input and output indices, and we are only changing
2430 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
2434 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
2435 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
2436 * @param output_start As \a input_start, but for outputs.
2439 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
2440 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
2442 if (!IO::connecting_legal) {
2446 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2452 /* If both inputs and outputs are auto-connected to physical ports,
2453 use the max of input and output offsets to ensure auto-connected
2454 port numbers always match up (e.g. the first audio input and the
2455 first audio output of the route will have the same physical
2456 port number). Otherwise just use the lowest input or output
2460 DEBUG_TRACE (DEBUG::Graph,
2461 string_compose("Auto-connect: existing in = %1 out = %2\n",
2462 existing_inputs, existing_outputs));
2464 const bool in_out_physical =
2465 (Config->get_input_auto_connect() & AutoConnectPhysical)
2466 && (Config->get_output_auto_connect() & AutoConnectPhysical)
2469 const ChanCount in_offset = in_out_physical
2470 ? ChanCount::max(existing_inputs, existing_outputs)
2473 const ChanCount out_offset = in_out_physical
2474 ? ChanCount::max(existing_inputs, existing_outputs)
2477 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
2478 vector<string> physinputs;
2479 vector<string> physoutputs;
2481 _engine.get_physical_outputs (*t, physoutputs);
2482 _engine.get_physical_inputs (*t, physinputs);
2484 if (!physinputs.empty() && connect_inputs) {
2485 uint32_t nphysical_in = physinputs.size();
2487 DEBUG_TRACE (DEBUG::Graph,
2488 string_compose("There are %1 physical inputs of type %2\n",
2491 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
2494 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2495 DEBUG_TRACE (DEBUG::Graph,
2496 string_compose("Get index %1 + %2 % %3 = %4\n",
2497 in_offset.get(*t), i, nphysical_in,
2498 (in_offset.get(*t) + i) % nphysical_in));
2499 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2502 DEBUG_TRACE (DEBUG::Graph,
2503 string_compose("Connect route %1 IN to %2\n",
2504 route->name(), port));
2506 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2510 ChanCount one_added (*t, 1);
2511 existing_inputs += one_added;
2515 if (!physoutputs.empty()) {
2516 uint32_t nphysical_out = physoutputs.size();
2517 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2521 * do not create new connections if we reached the limit of physical outputs
2525 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
2526 ARDOUR::Profile->get_trx () &&
2527 existing_outputs.get(*t) == nphysical_out ) {
2531 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2532 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2533 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2534 /* master bus is audio only */
2535 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2536 port = _master_out->input()->ports().port(*t,
2537 i % _master_out->input()->n_ports().get(*t))->name();
2541 DEBUG_TRACE (DEBUG::Graph,
2542 string_compose("Connect route %1 OUT to %2\n",
2543 route->name(), port));
2545 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2549 ChanCount one_added (*t, 1);
2550 existing_outputs += one_added;
2556 #ifdef USE_TRACKS_CODE_FEATURES
2559 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2561 return route1->remote_control_id() < route2->remote_control_id();
2565 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2567 // it is not allowed to perform connection
2568 if (!IO::connecting_legal) {
2572 // if we are deleting routes we will call this once at the end
2573 if (_route_deletion_in_progress) {
2577 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2583 // We need to disconnect the route's inputs and outputs first
2584 // basing on autoconnect configuration
2585 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2586 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2588 ChanCount existing_inputs;
2589 ChanCount existing_outputs;
2590 count_existing_track_channels (existing_inputs, existing_outputs);
2592 //ChanCount inputs = ChanCount::ZERO;
2593 //ChanCount outputs = ChanCount::ZERO;
2595 RouteList existing_routes = *routes.reader ();
2596 existing_routes.sort (compare_routes_by_remote_id);
2599 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2601 vector<string> physinputs;
2602 vector<string> physoutputs;
2604 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2605 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2607 uint32_t input_n = 0;
2608 uint32_t output_n = 0;
2609 RouteList::iterator rIter = existing_routes.begin();
2610 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2611 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2612 for (; rIter != existing_routes.end(); ++rIter) {
2613 if (*rIter == _master_out || *rIter == _monitor_out ) {
2617 if (current_output_auto_connection == AutoConnectPhysical) {
2618 (*rIter)->amp()->deactivate();
2619 } else if (current_output_auto_connection == AutoConnectMaster) {
2620 (*rIter)->amp()->activate();
2623 if (reconnectIputs) {
2624 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2626 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2628 if (current_input_auto_connection & AutoConnectPhysical) {
2630 if ( input_n == physinputs.size() ) {
2634 string port = physinputs[input_n];
2636 if (port.empty() ) {
2637 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2640 //GZ: check this; could be heavy
2641 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2647 if (reconnectOutputs) {
2649 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2650 if (current_output_auto_connection & AutoConnectPhysical) {
2652 //GZ: check this; could be heavy
2653 (*rIter)->output()->disconnect (this);
2654 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2656 //GZ: check this; could be heavy
2657 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2659 } else if (current_output_auto_connection & AutoConnectMaster){
2661 if (!reconnect_master) {
2665 //GZ: check this; could be heavy
2666 (*rIter)->output()->disconnect (this);
2669 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2670 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2672 error << error << "Master bus is not available" << endmsg;
2677 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2678 if (current_output_auto_connection & AutoConnectPhysical) {
2680 if ( output_n == physoutputs.size() ) {
2684 string port = physoutputs[output_n];
2686 if (port.empty() ) {
2687 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2690 //GZ: check this; could be heavy
2691 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2694 } else if (current_output_auto_connection & AutoConnectMaster) {
2696 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2700 // connect to master bus
2701 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2703 if (port.empty() ) {
2704 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2708 //GZ: check this; could be heavy
2709 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2715 //auto_connect_route (*rIter, inputs, outputs, false, reconnectIputs);
2718 _master_out->output()->disconnect (this);
2719 auto_connect_master_bus ();
2724 session_routes_reconnected (); /* EMIT SIGNAL */
2728 Session::reconnect_midi_scene_ports(bool inputs)
2732 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2734 scene_in_ptr->disconnect_all ();
2736 std::vector<EngineStateController::MidiPortState> midi_port_states;
2737 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2739 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2741 for (; state_iter != midi_port_states.end(); ++state_iter) {
2742 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2743 scene_in_ptr->connect (state_iter->name);
2750 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2752 if (scene_out_ptr ) {
2753 scene_out_ptr->disconnect_all ();
2755 std::vector<EngineStateController::MidiPortState> midi_port_states;
2756 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2758 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2760 for (; state_iter != midi_port_states.end(); ++state_iter) {
2761 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2762 scene_out_ptr->connect (state_iter->name);
2770 Session::reconnect_mtc_ports ()
2772 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2778 mtc_in_ptr->disconnect_all ();
2780 std::vector<EngineStateController::MidiPortState> midi_port_states;
2781 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2783 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2785 for (; state_iter != midi_port_states.end(); ++state_iter) {
2786 if (state_iter->available && state_iter->mtc_in) {
2787 mtc_in_ptr->connect (state_iter->name);
2791 if (!_midi_ports->mtc_input_port ()->connected () &&
2792 config.get_external_sync () &&
2793 (Config->get_sync_source () == MTC) ) {
2794 config.set_external_sync (false);
2797 if ( ARDOUR::Profile->get_trx () ) {
2798 // Tracks need this signal to update timecode_source_dropdown
2799 MtcOrLtcInputPortChanged (); //emit signal
2804 Session::reconnect_mmc_ports(bool inputs)
2806 if (inputs ) { // get all enabled midi input ports
2808 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2810 mmc_in_ptr->disconnect_all ();
2811 std::vector<std::string> enabled_midi_inputs;
2812 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2814 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2816 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2817 mmc_in_ptr->connect (*port_iter);
2821 } else { // get all enabled midi output ports
2823 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2825 mmc_out_ptr->disconnect_all ();
2826 std::vector<std::string> enabled_midi_outputs;
2827 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2829 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2831 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2832 mmc_out_ptr->connect (*port_iter);
2840 /** Caller must not hold process lock
2841 * @param name_template string to use for the start of the name, or "" to use "Audio".
2843 list< boost::shared_ptr<AudioTrack> >
2844 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2845 uint32_t how_many, string name_template)
2848 uint32_t track_id = 0;
2850 RouteList new_routes;
2851 list<boost::shared_ptr<AudioTrack> > ret;
2853 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2854 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2858 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2859 error << "cannot find name for new audio track" << endmsg;
2863 boost::shared_ptr<AudioTrack> track;
2866 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2868 if (track->init ()) {
2872 if (ARDOUR::Profile->get_trx ()) {
2873 // TRACKS considers it's not a USE CASE, it's
2874 // a piece of behavior of the session model:
2876 // Gain for a newly created route depends on
2877 // the current output_auto_connect mode:
2879 // 0 for Stereo Out mode
2881 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2882 track->set_gain (dB_to_coefficient (0), 0);
2886 track->use_new_diskstream();
2888 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2889 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2892 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2894 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2895 error << string_compose (
2896 _("cannot configure %1 in/%2 out configuration for new audio track"),
2897 input_channels, output_channels)
2902 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2903 error << string_compose (
2904 _("cannot configure %1 in/%2 out configuration for new audio track"),
2905 input_channels, output_channels)
2912 route_group->add (track);
2915 track->non_realtime_input_change();
2917 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2918 if (Config->get_remote_model() == UserOrdered) {
2919 track->set_remote_control_id (next_control_id());
2922 new_routes.push_back (track);
2923 ret.push_back (track);
2925 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2928 catch (failed_constructor &err) {
2929 error << _("Session: could not create new audio track.") << endmsg;
2933 catch (AudioEngine::PortRegistrationFailure& pfe) {
2935 error << pfe.what() << endmsg;
2943 if (!new_routes.empty()) {
2944 StateProtector sp (this);
2945 if (Profile->get_trx()) {
2946 add_routes (new_routes, false, false, false);
2948 add_routes (new_routes, true, true, false);
2955 /** Caller must not hold process lock.
2956 * @param name_template string to use for the start of the name, or "" to use "Bus".
2959 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2962 uint32_t bus_id = 0;
2966 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2969 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
2970 error << "cannot find name for new audio bus" << endmsg;
2975 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2981 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2982 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2985 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2987 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2988 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2989 input_channels, output_channels)
2995 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2996 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2997 input_channels, output_channels)
3004 route_group->add (bus);
3006 if (Config->get_remote_model() == UserOrdered) {
3007 bus->set_remote_control_id (next_control_id());
3010 bus->add_internal_return ();
3012 ret.push_back (bus);
3014 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3020 catch (failed_constructor &err) {
3021 error << _("Session: could not create new audio route.") << endmsg;
3025 catch (AudioEngine::PortRegistrationFailure& pfe) {
3026 error << pfe.what() << endmsg;
3036 StateProtector sp (this);
3037 if (Profile->get_trx()) {
3038 add_routes (ret, false, false, false);
3040 add_routes (ret, false, true, true); // autoconnect // outputs only
3049 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3053 if (!tree.read (template_path.c_str())) {
3057 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3061 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3064 uint32_t control_id;
3065 uint32_t number = 0;
3066 const uint32_t being_added = how_many;
3067 /* This will prevent the use of any existing XML-provided PBD::ID
3070 Stateful::ForceIDRegeneration force_ids;
3071 IO::disable_connecting ();
3073 control_id = next_control_id ();
3077 /* We're going to modify the node contents a bit so take a
3078 * copy. The node may be re-used when duplicating more than once.
3081 XMLNode node_copy (node);
3086 if (!name_base.empty()) {
3088 /* if we're adding more than one routes, force
3089 * all the names of the new routes to be
3090 * numbered, via the final parameter.
3093 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3094 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3100 string const route_name = node_copy.property(X_("name"))->value ();
3102 /* generate a new name by adding a number to the end of the template name */
3103 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3104 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3105 abort(); /*NOTREACHED*/
3109 /* set this name in the XML description that we are about to use */
3111 bool rename_playlist;
3114 rename_playlist = true;
3118 rename_playlist = false;
3121 Route::set_name_in_state (node_copy, name, rename_playlist);
3123 /* trim bitslots from listen sends so that new ones are used */
3124 XMLNodeList children = node_copy.children ();
3125 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3126 if ((*i)->name() == X_("Processor")) {
3127 XMLProperty* role = (*i)->property (X_("role"));
3128 if (role && role->value() == X_("Listen")) {
3129 (*i)->remove_property (X_("bitslot"));
3134 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3137 error << _("Session: cannot create track/bus from template description") << endmsg;
3141 if (boost::dynamic_pointer_cast<Track>(route)) {
3142 /* force input/output change signals so that the new diskstream
3143 picks up the configuration of the route. During session
3144 loading this normally happens in a different way.
3147 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3149 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3150 change.after = route->input()->n_ports();
3151 route->input()->changed (change, this);
3152 change.after = route->output()->n_ports();
3153 route->output()->changed (change, this);
3156 route->set_remote_control_id (control_id);
3159 boost::shared_ptr<Track> track;
3161 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3164 track->use_new_playlist ();
3167 track->use_copy_playlist ();
3174 ret.push_back (route);
3176 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3179 catch (failed_constructor &err) {
3180 error << _("Session: could not create new route from template") << endmsg;
3184 catch (AudioEngine::PortRegistrationFailure& pfe) {
3185 error << pfe.what() << endmsg;
3194 StateProtector sp (this);
3195 if (Profile->get_trx()) {
3196 add_routes (ret, false, false, false);
3198 add_routes (ret, true, true, false);
3200 IO::enable_connecting ();
3207 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3210 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3211 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3214 error << _("Adding new tracks/busses failed") << endmsg;
3219 update_latency (true);
3220 update_latency (false);
3225 save_state (_current_snapshot_name);
3228 reassign_track_numbers();
3230 update_route_record_state ();
3232 RouteAdded (new_routes); /* EMIT SIGNAL */
3236 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3238 ChanCount existing_inputs;
3239 ChanCount existing_outputs;
3240 uint32_t order = next_control_id();
3242 if (_order_hint > -1) {
3243 order = _order_hint;
3247 count_existing_track_channels (existing_inputs, existing_outputs);
3250 RCUWriter<RouteList> writer (routes);
3251 boost::shared_ptr<RouteList> r = writer.get_copy ();
3252 r->insert (r->end(), new_routes.begin(), new_routes.end());
3254 /* if there is no control out and we're not in the middle of loading,
3255 resort the graph here. if there is a control out, we will resort
3256 toward the end of this method. if we are in the middle of loading,
3257 we will resort when done.
3260 if (!_monitor_out && IO::connecting_legal) {
3261 resort_routes_using (r);
3265 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3267 boost::weak_ptr<Route> wpr (*x);
3268 boost::shared_ptr<Route> r (*x);
3270 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _2, wpr));
3271 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _3, wpr));
3272 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
3273 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
3274 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3275 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3277 if (r->is_master()) {
3281 if (r->is_monitor()) {
3285 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3287 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3288 track_playlist_changed (boost::weak_ptr<Track> (tr));
3289 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3291 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3293 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3294 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3299 if (input_auto_connect || output_auto_connect) {
3300 auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
3303 /* order keys are a GUI responsibility but we need to set up
3304 reasonable defaults because they also affect the remote control
3305 ID in most situations.
3308 if (!r->has_order_key ()) {
3309 if (r->is_auditioner()) {
3310 /* use an arbitrarily high value */
3311 r->set_order_key (UINT_MAX);
3313 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3314 r->set_order_key (order);
3322 if (_monitor_out && IO::connecting_legal) {
3323 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3325 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3326 if ((*x)->is_monitor()) {
3328 } else if ((*x)->is_master()) {
3331 (*x)->enable_monitor_send ();
3338 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3340 boost::shared_ptr<RouteList> r = routes.reader ();
3341 boost::shared_ptr<Send> s;
3343 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3344 if ((s = (*i)->internal_send_for (dest)) != 0) {
3345 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3351 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3353 boost::shared_ptr<RouteList> r = routes.reader ();
3354 boost::shared_ptr<Send> s;
3356 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3357 if ((s = (*i)->internal_send_for (dest)) != 0) {
3358 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3364 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3366 boost::shared_ptr<RouteList> r = routes.reader ();
3367 boost::shared_ptr<Send> s;
3369 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3370 if ((s = (*i)->internal_send_for (dest)) != 0) {
3371 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3376 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3378 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3380 boost::shared_ptr<RouteList> r = routes.reader ();
3381 boost::shared_ptr<RouteList> t (new RouteList);
3383 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3384 /* no MIDI sends because there are no MIDI busses yet */
3385 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3390 add_internal_sends (dest, p, t);
3394 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3396 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3397 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3402 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3404 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3408 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3410 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3414 if (!dest->internal_return()) {
3415 dest->add_internal_return ();
3418 sender->add_aux_send (dest, before);
3425 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3427 { // RCU Writer scope
3428 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3429 RCUWriter<RouteList> writer (routes);
3430 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3433 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3435 if (*iter == _master_out) {
3439 (*iter)->set_solo (false, this);
3443 /* deleting the master out seems like a dumb
3444 idea, but its more of a UI policy issue
3448 if (*iter == _master_out) {
3449 _master_out = boost::shared_ptr<Route> ();
3452 if (*iter == _monitor_out) {
3453 _monitor_out.reset ();
3456 // We need to disconnect the route's inputs and outputs
3458 (*iter)->input()->disconnect (0);
3459 (*iter)->output()->disconnect (0);
3461 /* if the route had internal sends sending to it, remove them */
3462 if ((*iter)->internal_return()) {
3464 boost::shared_ptr<RouteList> r = routes.reader ();
3465 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3466 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3468 (*i)->remove_processor (s);
3473 /* if the monitoring section had a pointer to this route, remove it */
3474 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3475 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3476 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3477 (*iter)->remove_aux_or_listen (_monitor_out);
3480 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3481 if (mt && mt->step_editing()) {
3482 if (_step_editors > 0) {
3488 /* writer goes out of scope, forces route list update */
3490 } // end of RCU Writer scope
3492 update_route_solo_state ();
3493 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3494 update_latency_compensation ();
3497 /* Re-sort routes to remove the graph's current references to the one that is
3498 * going away, then flush old references out of the graph.
3499 * Wave Tracks: reconnect routes
3502 #ifdef USE_TRACKS_CODE_FEATURES
3503 reconnect_existing_routes(true, false);
3505 routes.flush (); // maybe unsafe, see below.
3509 if (_process_graph) {
3510 _process_graph->clear_other_chain ();
3513 /* get rid of it from the dead wood collection in the route list manager */
3514 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3518 /* try to cause everyone to drop their references
3519 * and unregister ports from the backend
3522 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3523 (*iter)->drop_references ();
3526 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3528 /* save the new state of the world */
3530 if (save_state (_current_snapshot_name)) {
3531 save_history (_current_snapshot_name);
3534 reassign_track_numbers();
3535 update_route_record_state ();
3539 Session::remove_route (boost::shared_ptr<Route> route)
3541 boost::shared_ptr<RouteList> rl (new RouteList);
3542 rl->push_back (route);
3547 Session::route_mute_changed (void* /*src*/)
3553 Session::route_listen_changed (bool group_override, boost::weak_ptr<Route> wpr)
3555 boost::shared_ptr<Route> route = wpr.lock();
3557 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_listen_changed")) << endmsg;
3561 if (route->listening_via_monitor ()) {
3563 if (Config->get_exclusive_solo()) {
3564 /* new listen: disable all other listen, except solo-grouped channels */
3565 RouteGroup* rg = route->route_group ();
3566 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
3567 if (group_override && rg) {
3568 leave_group_alone = !leave_group_alone;
3570 boost::shared_ptr<RouteList> r = routes.reader ();
3571 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3572 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() || (leave_group_alone && ((*i)->route_group() == rg))) {
3575 (*i)->set_listen (false, this, group_override);
3581 } else if (_listen_cnt > 0) {
3586 update_route_solo_state ();
3589 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
3591 boost::shared_ptr<Route> route = wpr.lock ();
3594 /* should not happen */
3595 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_isolated_changed")) << endmsg;
3599 bool send_changed = false;
3601 if (route->solo_isolated()) {
3602 if (_solo_isolated_cnt == 0) {
3603 send_changed = true;
3605 _solo_isolated_cnt++;
3606 } else if (_solo_isolated_cnt > 0) {
3607 _solo_isolated_cnt--;
3608 if (_solo_isolated_cnt == 0) {
3609 send_changed = true;
3614 IsolatedChanged (); /* EMIT SIGNAL */
3619 Session::route_solo_changed (bool self_solo_change, bool group_override, boost::weak_ptr<Route> wpr)
3621 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3623 if (!self_solo_change) {
3624 // session doesn't care about changes to soloed-by-others
3628 boost::shared_ptr<Route> route = wpr.lock ();
3631 boost::shared_ptr<RouteList> r = routes.reader ();
3634 if (route->self_soloed()) {
3640 RouteGroup* rg = route->route_group ();
3641 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
3642 if (group_override && rg) {
3643 leave_group_alone = !leave_group_alone;
3645 if (delta == 1 && Config->get_exclusive_solo()) {
3647 /* new solo: disable all other solos, but not the group if its solo-enabled */
3649 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3650 if ((*i) == route || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3651 (leave_group_alone && ((*i)->route_group() == rg))) {
3654 (*i)->set_solo (false, this, group_override);
3658 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3660 RouteList uninvolved;
3662 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3664 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3665 bool via_sends_only;
3666 bool in_signal_flow;
3668 if ((*i) == route || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
3669 (leave_group_alone && ((*i)->route_group() == rg))) {
3673 in_signal_flow = false;
3675 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3677 if ((*i)->feeds (route, &via_sends_only)) {
3678 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3679 if (!via_sends_only) {
3680 if (!route->soloed_by_others_upstream()) {
3681 (*i)->mod_solo_by_others_downstream (delta);
3683 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3686 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3688 in_signal_flow = true;
3690 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3693 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3695 if (route->feeds (*i, &via_sends_only)) {
3696 /* propagate solo upstream only if routing other than
3697 sends is involved, but do consider the other route
3698 (*i) to be part of the signal flow even if only
3701 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3705 route->soloed_by_others_downstream(),
3706 route->soloed_by_others_upstream()));
3707 if (!via_sends_only) {
3708 //NB. Triggers Invert Push, which handles soloed by downstream
3709 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3710 (*i)->mod_solo_by_others_upstream (delta);
3712 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3714 in_signal_flow = true;
3716 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3719 if (!in_signal_flow) {
3720 uninvolved.push_back (*i);
3724 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3726 update_route_solo_state (r);
3728 /* now notify that the mute state of the routes not involved in the signal
3729 pathway of the just-solo-changed route may have altered.
3732 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3733 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3734 (*i)->act_on_mute ();
3735 (*i)->mute_changed (this);
3738 SoloChanged (); /* EMIT SIGNAL */
3743 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3745 /* now figure out if anything that matters is soloed (or is "listening")*/
3747 bool something_soloed = false;
3748 bool something_listening = false;
3749 uint32_t listeners = 0;
3750 uint32_t isolated = 0;
3753 r = routes.reader();
3756 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3757 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3758 something_soloed = true;
3761 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3762 if (Config->get_solo_control_is_listen_control()) {
3764 something_listening = true;
3766 (*i)->set_listen (false, this);
3770 if ((*i)->solo_isolated()) {
3775 if (something_soloed != _non_soloed_outs_muted) {
3776 _non_soloed_outs_muted = something_soloed;
3777 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3780 if (something_listening != _listening) {
3781 _listening = something_listening;
3782 SoloActive (_listening);
3785 _listen_cnt = listeners;
3787 if (isolated != _solo_isolated_cnt) {
3788 _solo_isolated_cnt = isolated;
3789 IsolatedChanged (); /* EMIT SIGNAL */
3792 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3793 something_soloed, listeners, isolated));
3796 boost::shared_ptr<RouteList>
3797 Session::get_routes_with_internal_returns() const
3799 boost::shared_ptr<RouteList> r = routes.reader ();
3800 boost::shared_ptr<RouteList> rl (new RouteList);
3802 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3803 if ((*i)->internal_return ()) {
3811 Session::io_name_is_legal (const std::string& name)
3813 boost::shared_ptr<RouteList> r = routes.reader ();
3815 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
3816 if (name == *reserved) {
3817 if (!route_by_name (*reserved)) {
3818 /* first instance of a reserved name is allowed */
3821 /* all other instances of a reserved name are not allowed */
3826 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3827 if ((*i)->name() == name) {
3831 if ((*i)->has_io_processor_named (name)) {
3840 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3843 vector<string> connections;
3845 /* if we are passed only a single route and we're not told to turn
3846 * others off, then just do the simple thing.
3849 if (flip_others == false && rl->size() == 1) {
3850 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3852 mt->set_input_active (onoff);
3857 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3859 PortSet& ps ((*rt)->input()->ports());
3861 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3862 p->get_connections (connections);
3865 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3866 routes_using_input_from (*s, rl2);
3869 /* scan all relevant routes to see if others are on or off */
3871 bool others_are_already_on = false;
3873 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3875 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3881 if ((*r) != (*rt)) {
3882 if (mt->input_active()) {
3883 others_are_already_on = true;
3886 /* this one needs changing */
3887 mt->set_input_active (onoff);
3893 /* globally reverse other routes */
3895 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3896 if ((*r) != (*rt)) {
3897 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3899 mt->set_input_active (!others_are_already_on);
3908 Session::routes_using_input_from (const string& str, RouteList& rl)
3910 boost::shared_ptr<RouteList> r = routes.reader();
3912 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3913 if ((*i)->input()->connected_to (str)) {
3919 boost::shared_ptr<Route>
3920 Session::route_by_name (string name)
3922 boost::shared_ptr<RouteList> r = routes.reader ();
3924 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3925 if ((*i)->name() == name) {
3930 return boost::shared_ptr<Route> ((Route*) 0);
3933 boost::shared_ptr<Route>
3934 Session::route_by_id (PBD::ID id)
3936 boost::shared_ptr<RouteList> r = routes.reader ();
3938 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3939 if ((*i)->id() == id) {
3944 return boost::shared_ptr<Route> ((Route*) 0);
3947 boost::shared_ptr<Track>
3948 Session::track_by_diskstream_id (PBD::ID id)
3950 boost::shared_ptr<RouteList> r = routes.reader ();
3952 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3953 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3954 if (t && t->using_diskstream_id (id)) {
3959 return boost::shared_ptr<Track> ();
3962 boost::shared_ptr<Route>
3963 Session::route_by_remote_id (uint32_t id)
3965 boost::shared_ptr<RouteList> r = routes.reader ();
3967 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3968 if ((*i)->remote_control_id() == id) {
3973 return boost::shared_ptr<Route> ((Route*) 0);
3978 Session::reassign_track_numbers ()
3982 RouteList r (*(routes.reader ()));
3983 SignalOrderRouteSorter sorter;
3986 StateProtector sp (this);
3988 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3989 if (boost::dynamic_pointer_cast<Track> (*i)) {
3990 (*i)->set_track_number(++tn);
3992 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
3993 (*i)->set_track_number(--bn);
3996 const uint32_t decimals = ceilf (log10f (tn + 1));
3997 const bool decimals_changed = _track_number_decimals != decimals;
3998 _track_number_decimals = decimals;
4000 if (decimals_changed && config.get_track_name_number ()) {
4001 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4002 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4004 t->resync_track_name();
4007 // trigger GUI re-layout
4008 config.ParameterChanged("track-name-number");
4013 Session::playlist_region_added (boost::weak_ptr<Region> w)
4015 boost::shared_ptr<Region> r = w.lock ();
4020 /* These are the operations that are currently in progress... */
4021 list<GQuark> curr = _current_trans_quarks;
4024 /* ...and these are the operations during which we want to update
4025 the session range location markers.
4028 ops.push_back (Operations::capture);
4029 ops.push_back (Operations::paste);
4030 ops.push_back (Operations::duplicate_region);
4031 ops.push_back (Operations::insert_file);
4032 ops.push_back (Operations::insert_region);
4033 ops.push_back (Operations::drag_region_brush);
4034 ops.push_back (Operations::region_drag);
4035 ops.push_back (Operations::selection_grab);
4036 ops.push_back (Operations::region_fill);
4037 ops.push_back (Operations::fill_selection);
4038 ops.push_back (Operations::create_region);
4039 ops.push_back (Operations::region_copy);
4040 ops.push_back (Operations::fixed_time_region_copy);
4043 /* See if any of the current operations match the ones that we want */
4045 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4047 /* If so, update the session range markers */
4049 maybe_update_session_range (r->position (), r->last_frame ());
4053 /** Update the session range markers if a is before the current start or
4054 * b is after the current end.
4057 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4059 if (_state_of_the_state & Loading) {
4063 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4065 if (_session_range_location == 0) {
4067 set_session_range_location (a, b + session_end_marker_shift_samples);
4071 if (a < _session_range_location->start()) {
4072 _session_range_location->set_start (a);
4075 if (b > _session_range_location->end()) {
4076 _session_range_location->set_end (b);
4082 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4084 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4085 maybe_update_session_range (i->to, i->to + i->length);
4090 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4092 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4093 maybe_update_session_range (i->from, i->to);
4097 /* Region management */
4099 boost::shared_ptr<Region>
4100 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4102 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4103 RegionFactory::RegionMap::const_iterator i;
4104 boost::shared_ptr<Region> region;
4106 Glib::Threads::Mutex::Lock lm (region_lock);
4108 for (i = regions.begin(); i != regions.end(); ++i) {
4112 if (region->whole_file()) {
4114 if (child->source_equivalent (region)) {
4120 return boost::shared_ptr<Region> ();
4124 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4126 set<boost::shared_ptr<Region> > relevant_regions;
4128 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4129 RegionFactory::get_regions_using_source (*s, relevant_regions);
4132 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4133 set<boost::shared_ptr<Region> >::iterator tmp;
4138 playlists->destroy_region (*r);
4139 RegionFactory::map_remove (*r);
4141 (*r)->drop_sources ();
4142 (*r)->drop_references ();
4144 relevant_regions.erase (r);
4149 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4152 Glib::Threads::Mutex::Lock ls (source_lock);
4153 /* remove from the main source list */
4154 sources.erase ((*s)->id());
4157 (*s)->mark_for_remove ();
4158 (*s)->drop_references ();
4167 Session::remove_last_capture ()
4169 list<boost::shared_ptr<Source> > srcs;
4171 boost::shared_ptr<RouteList> rl = routes.reader ();
4172 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4173 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4178 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4181 srcs.insert (srcs.end(), l.begin(), l.end());
4186 destroy_sources (srcs);
4188 save_state (_current_snapshot_name);
4193 /* Source Management */
4196 Session::add_source (boost::shared_ptr<Source> source)
4198 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4199 pair<SourceMap::iterator,bool> result;
4201 entry.first = source->id();
4202 entry.second = source;
4205 Glib::Threads::Mutex::Lock lm (source_lock);
4206 result = sources.insert (entry);
4209 if (result.second) {
4211 /* yay, new source */
4213 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4216 if (!fs->within_session()) {
4217 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4223 boost::shared_ptr<AudioFileSource> afs;
4225 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4226 if (Config->get_auto_analyse_audio()) {
4227 Analyser::queue_source_for_analysis (source, false);
4231 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4236 Session::remove_source (boost::weak_ptr<Source> src)
4238 if (_state_of_the_state & Deletion) {
4242 SourceMap::iterator i;
4243 boost::shared_ptr<Source> source = src.lock();
4250 Glib::Threads::Mutex::Lock lm (source_lock);
4252 if ((i = sources.find (source->id())) != sources.end()) {
4257 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4259 /* save state so we don't end up with a session file
4260 referring to non-existent sources.
4263 save_state (_current_snapshot_name);
4267 boost::shared_ptr<Source>
4268 Session::source_by_id (const PBD::ID& id)
4270 Glib::Threads::Mutex::Lock lm (source_lock);
4271 SourceMap::iterator i;
4272 boost::shared_ptr<Source> source;
4274 if ((i = sources.find (id)) != sources.end()) {
4281 boost::shared_ptr<AudioFileSource>
4282 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4284 /* Restricted to audio files because only audio sources have channel
4288 Glib::Threads::Mutex::Lock lm (source_lock);
4290 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4291 boost::shared_ptr<AudioFileSource> afs
4292 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4294 if (afs && afs->path() == path && chn == afs->channel()) {
4299 return boost::shared_ptr<AudioFileSource>();
4302 boost::shared_ptr<MidiSource>
4303 Session::midi_source_by_path (const std::string& path) const
4305 /* Restricted to MIDI files because audio sources require a channel
4306 for unique identification, in addition to a path.
4309 Glib::Threads::Mutex::Lock lm (source_lock);
4311 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4312 boost::shared_ptr<MidiSource> ms
4313 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4314 boost::shared_ptr<FileSource> fs
4315 = boost::dynamic_pointer_cast<FileSource>(s->second);
4317 if (ms && fs && fs->path() == path) {
4322 return boost::shared_ptr<MidiSource>();
4326 Session::count_sources_by_origin (const string& path)
4329 Glib::Threads::Mutex::Lock lm (source_lock);
4331 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4332 boost::shared_ptr<FileSource> fs
4333 = boost::dynamic_pointer_cast<FileSource>(i->second);
4335 if (fs && fs->origin() == path) {
4344 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4346 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4347 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4349 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4354 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4356 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4358 if (Glib::path_is_absolute (filepath)) {
4360 /* rip the session dir from the audiofile source */
4362 string session_path;
4363 bool in_another_session = true;
4365 if (filepath.find (interchange_dir_string) != string::npos) {
4367 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4368 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4369 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4370 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4372 /* see if it is within our session */
4374 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4375 if (i->path == session_path) {
4376 in_another_session = false;
4381 in_another_session = false;
4385 if (in_another_session) {
4386 SessionDirectory sd (session_path);
4387 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4391 /* 1) if file belongs to this session
4392 * it may be a relative path (interchange/...)
4393 * or just basename (session_state, remove source)
4394 * -> just use the basename
4396 std::string filename = Glib::path_get_basename (filepath);
4399 /* 2) if the file is outside our session dir:
4400 * (imported but not copied) add the path for check-summming */
4402 path = Glib::path_get_dirname (filepath);
4405 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4409 Session::new_audio_source_path_for_embedded (const std::string& path)
4413 * we know that the filename is already unique because it exists
4414 * out in the filesystem.
4416 * However, when we bring it into the session, we could get a
4419 * Eg. two embedded files:
4424 * When merged into session, these collide.
4426 * There will not be a conflict with in-memory sources
4427 * because when the source was created we already picked
4428 * a unique name for it.
4430 * This collision is not likely to be common, but we have to guard
4431 * against it. So, if there is a collision, take the md5 hash of the
4432 * the path, and use that as the filename instead.
4435 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4436 string base = Glib::path_get_basename (path);
4437 string newpath = Glib::build_filename (sdir.sound_path(), base);
4439 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4443 md5.digestString (path.c_str());
4444 md5.writeToString ();
4445 base = md5.digestChars;
4447 string ext = get_suffix (path);
4454 newpath = Glib::build_filename (sdir.sound_path(), base);
4456 /* if this collides, we're screwed */
4458 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4459 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4468 /** Return true if there are no audio file sources that use @param name as
4469 * the filename component of their path.
4471 * Return false otherwise.
4473 * This method MUST ONLY be used to check in-session, mono files since it
4474 * hard-codes the channel of the audio file source we are looking for as zero.
4476 * If/when Ardour supports native files in non-mono formats, the logic here
4477 * will need to be revisited.
4480 Session::audio_source_name_is_unique (const string& name)
4482 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4483 vector<space_and_path>::iterator i;
4484 uint32_t existing = 0;
4486 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4488 /* note that we search *without* the extension so that
4489 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4490 in the event that this new name is required for
4491 a file format change.
4494 const string spath = *i;
4496 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4501 /* it is possible that we have the path already
4502 * assigned to a source that has not yet been written
4503 * (ie. the write source for a diskstream). we have to
4504 * check this in order to make sure that our candidate
4505 * path isn't used again, because that can lead to
4506 * two Sources point to the same file with different
4507 * notions of their removability.
4511 string possible_path = Glib::build_filename (spath, name);
4513 if (audio_source_by_path_and_channel (possible_path, 0)) {
4519 return (existing == 0);
4523 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)
4526 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4528 if (Profile->get_trx() && destructive) {
4530 sstr << setfill ('0') << setw (4) << cnt;
4531 sstr << legalized_base;
4533 sstr << legalized_base;
4535 if (take_required || related_exists) {
4547 } else if (nchan > 2) {
4552 /* XXX what? more than 26 channels! */
4563 /** Return a unique name based on \a base for a new internal audio source */
4565 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4568 string possible_name;
4569 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4571 bool some_related_source_name_exists = false;
4573 legalized = legalize_for_path (base);
4575 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4577 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4579 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4581 if (audio_source_name_is_unique (possible_name)) {
4585 some_related_source_name_exists = true;
4588 error << string_compose(
4589 _("There are already %1 recordings for %2, which I consider too many."),
4590 limit, base) << endmsg;
4592 throw failed_constructor();
4596 /* We've established that the new name does not exist in any session
4597 * directory, so now find out which one we should use for this new
4601 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4603 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4608 /** Return a unique name based on `base` for a new internal MIDI source */
4610 Session::new_midi_source_path (const string& base)
4613 char buf[PATH_MAX+1];
4614 const uint32_t limit = 10000;
4616 string possible_path;
4617 string possible_name;
4620 legalized = legalize_for_path (base);
4622 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4623 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4625 /* - the main session folder is the first in the vector.
4626 * - after checking all locations for file-name uniqueness,
4627 * we keep the one from the last iteration as new file name
4628 * - midi files are small and should just be kept in the main session-folder
4630 * -> reverse the array, check main session folder last and use that as location
4633 std::reverse(sdirs.begin(), sdirs.end());
4635 for (cnt = 1; cnt <= limit; ++cnt) {
4637 vector<space_and_path>::iterator i;
4638 uint32_t existing = 0;
4640 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4642 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4643 possible_name = buf;
4645 possible_path = Glib::build_filename (*i, possible_name);
4647 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4651 if (midi_source_by_path (possible_path)) {
4656 if (existing == 0) {
4661 error << string_compose(
4662 _("There are already %1 recordings for %2, which I consider too many."),
4663 limit, base) << endmsg;
4669 /* No need to "find best location" for software/app-based RAID, because
4670 MIDI is so small that we always put it in the same place.
4673 return possible_path;
4677 /** Create a new within-session audio source */
4678 boost::shared_ptr<AudioFileSource>
4679 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4681 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4683 if (!path.empty()) {
4684 return boost::dynamic_pointer_cast<AudioFileSource> (
4685 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4687 throw failed_constructor ();
4691 /** Create a new within-session MIDI source */
4692 boost::shared_ptr<MidiSource>
4693 Session::create_midi_source_for_session (string const & basic_name)
4695 const string path = new_midi_source_path (basic_name);
4697 if (!path.empty()) {
4698 return boost::dynamic_pointer_cast<SMFSource> (
4699 SourceFactory::createWritable (
4700 DataType::MIDI, *this, path, false, frame_rate()));
4702 throw failed_constructor ();
4706 /** Create a new within-session MIDI source */
4707 boost::shared_ptr<MidiSource>
4708 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4710 /* the caller passes in the track the source will be used in,
4711 so that we can keep the numbering sane.
4713 Rationale: a track with the name "Foo" that has had N
4714 captures carried out so far will ALREADY have a write source
4715 named "Foo-N+1.mid" waiting to be used for the next capture.
4717 If we call new_midi_source_name() we will get "Foo-N+2". But
4718 there is no region corresponding to "Foo-N+1", so when
4719 "Foo-N+2" appears in the track, the gap presents the user
4720 with odd behaviour - why did it skip past Foo-N+1?
4722 We could explain this to the user in some odd way, but
4723 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4726 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4729 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4731 std::string name = track->steal_write_source_name ();
4734 return boost::shared_ptr<MidiSource>();
4737 /* MIDI files are small, just put them in the first location of the
4738 session source search path.
4741 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4743 return boost::dynamic_pointer_cast<SMFSource> (
4744 SourceFactory::createWritable (
4745 DataType::MIDI, *this, path, false, frame_rate()));
4750 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4752 if (playlist->hidden()) {
4756 playlists->add (playlist);
4759 playlist->release();
4766 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4768 if (_state_of_the_state & Deletion) {
4772 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4778 playlists->remove (playlist);
4784 Session::set_audition (boost::shared_ptr<Region> r)
4786 pending_audition_region = r;
4787 add_post_transport_work (PostTransportAudition);
4788 _butler->schedule_transport_work ();
4792 Session::audition_playlist ()
4794 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4795 ev->region.reset ();
4800 Session::non_realtime_set_audition ()
4802 assert (pending_audition_region);
4803 auditioner->audition_region (pending_audition_region);
4804 pending_audition_region.reset ();
4805 AuditionActive (true); /* EMIT SIGNAL */
4809 Session::audition_region (boost::shared_ptr<Region> r)
4811 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4817 Session::cancel_audition ()
4822 if (auditioner->auditioning()) {
4823 auditioner->cancel_audition ();
4824 AuditionActive (false); /* EMIT SIGNAL */
4829 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
4831 if (a->is_monitor()) {
4834 if (b->is_monitor()) {
4837 return a->order_key () < b->order_key ();
4841 Session::is_auditioning () const
4843 /* can be called before we have an auditioner object */
4845 return auditioner->auditioning();
4852 Session::graph_reordered ()
4854 /* don't do this stuff if we are setting up connections
4855 from a set_state() call or creating new tracks. Ditto for deletion.
4858 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
4862 /* every track/bus asked for this to be handled but it was deferred because
4863 we were connecting. do it now.
4866 request_input_change_handling ();
4870 /* force all diskstreams to update their capture offset values to
4871 reflect any changes in latencies within the graph.
4874 boost::shared_ptr<RouteList> rl = routes.reader ();
4875 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4876 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4878 tr->set_capture_offset ();
4883 /** @return Number of frames that there is disk space available to write,
4886 boost::optional<framecnt_t>
4887 Session::available_capture_duration ()
4889 Glib::Threads::Mutex::Lock lm (space_lock);
4891 if (_total_free_4k_blocks_uncertain) {
4892 return boost::optional<framecnt_t> ();
4895 float sample_bytes_on_disk = 4.0; // keep gcc happy
4897 switch (config.get_native_file_data_format()) {
4899 sample_bytes_on_disk = 4.0;
4903 sample_bytes_on_disk = 3.0;
4907 sample_bytes_on_disk = 2.0;
4911 /* impossible, but keep some gcc versions happy */
4912 fatal << string_compose (_("programming error: %1"),
4913 X_("illegal native file data format"))
4915 abort(); /*NOTREACHED*/
4918 double scale = 4096.0 / sample_bytes_on_disk;
4920 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
4921 return max_framecnt;
4924 return (framecnt_t) floor (_total_free_4k_blocks * scale);
4928 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
4931 RCUWriter<BundleList> writer (_bundles);
4932 boost::shared_ptr<BundleList> b = writer.get_copy ();
4933 b->push_back (bundle);
4937 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4944 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
4946 bool removed = false;
4949 RCUWriter<BundleList> writer (_bundles);
4950 boost::shared_ptr<BundleList> b = writer.get_copy ();
4951 BundleList::iterator i = find (b->begin(), b->end(), bundle);
4953 if (i != b->end()) {
4960 BundleAddedOrRemoved (); /* EMIT SIGNAL */
4966 boost::shared_ptr<Bundle>
4967 Session::bundle_by_name (string name) const
4969 boost::shared_ptr<BundleList> b = _bundles.reader ();
4971 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
4972 if ((*i)->name() == name) {
4977 return boost::shared_ptr<Bundle> ();
4981 Session::tempo_map_changed (const PropertyChange&)
4985 playlists->update_after_tempo_map_change ();
4987 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
4993 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
4995 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
4996 (*i)->recompute_frames_from_bbt ();
5000 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5001 * the given count with the current block size.
5004 Session::ensure_buffers (ChanCount howmany)
5006 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5010 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5012 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5013 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5018 Session::next_insert_id ()
5020 /* this doesn't really loop forever. just think about it */
5023 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
5024 if (!insert_bitset[n]) {
5025 insert_bitset[n] = true;
5031 /* none available, so resize and try again */
5033 insert_bitset.resize (insert_bitset.size() + 16, false);
5038 Session::next_send_id ()
5040 /* this doesn't really loop forever. just think about it */
5043 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
5044 if (!send_bitset[n]) {
5045 send_bitset[n] = true;
5051 /* none available, so resize and try again */
5053 send_bitset.resize (send_bitset.size() + 16, false);
5058 Session::next_aux_send_id ()
5060 /* this doesn't really loop forever. just think about it */
5063 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
5064 if (!aux_send_bitset[n]) {
5065 aux_send_bitset[n] = true;
5071 /* none available, so resize and try again */
5073 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5078 Session::next_return_id ()
5080 /* this doesn't really loop forever. just think about it */
5083 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
5084 if (!return_bitset[n]) {
5085 return_bitset[n] = true;
5091 /* none available, so resize and try again */
5093 return_bitset.resize (return_bitset.size() + 16, false);
5098 Session::mark_send_id (uint32_t id)
5100 if (id >= send_bitset.size()) {
5101 send_bitset.resize (id+16, false);
5103 if (send_bitset[id]) {
5104 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5106 send_bitset[id] = true;
5110 Session::mark_aux_send_id (uint32_t id)
5112 if (id >= aux_send_bitset.size()) {
5113 aux_send_bitset.resize (id+16, false);
5115 if (aux_send_bitset[id]) {
5116 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5118 aux_send_bitset[id] = true;
5122 Session::mark_return_id (uint32_t id)
5124 if (id >= return_bitset.size()) {
5125 return_bitset.resize (id+16, false);
5127 if (return_bitset[id]) {
5128 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5130 return_bitset[id] = true;
5134 Session::mark_insert_id (uint32_t id)
5136 if (id >= insert_bitset.size()) {
5137 insert_bitset.resize (id+16, false);
5139 if (insert_bitset[id]) {
5140 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5142 insert_bitset[id] = true;
5146 Session::unmark_send_id (uint32_t id)
5148 if (id < send_bitset.size()) {
5149 send_bitset[id] = false;
5154 Session::unmark_aux_send_id (uint32_t id)
5156 if (id < aux_send_bitset.size()) {
5157 aux_send_bitset[id] = false;
5162 Session::unmark_return_id (uint32_t id)
5164 if (id < return_bitset.size()) {
5165 return_bitset[id] = false;
5170 Session::unmark_insert_id (uint32_t id)
5172 if (id < insert_bitset.size()) {
5173 insert_bitset[id] = false;
5178 Session::reset_native_file_format ()
5180 boost::shared_ptr<RouteList> rl = routes.reader ();
5182 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5183 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5185 /* don't save state as we do this, there's no point
5187 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5188 tr->reset_write_sources (false);
5189 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5195 Session::route_name_unique (string n) const
5197 boost::shared_ptr<RouteList> r = routes.reader ();
5199 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5200 if ((*i)->name() == n) {
5209 Session::route_name_internal (string n) const
5211 if (auditioner && auditioner->name() == n) {
5215 if (_click_io && _click_io->name() == n) {
5223 Session::freeze_all (InterThreadInfo& itt)
5225 boost::shared_ptr<RouteList> r = routes.reader ();
5227 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5229 boost::shared_ptr<Track> t;
5231 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5232 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5242 boost::shared_ptr<Region>
5243 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5244 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5245 InterThreadInfo& itt,
5246 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5247 bool for_export, bool for_freeze)
5249 boost::shared_ptr<Region> result;
5250 boost::shared_ptr<Playlist> playlist;
5251 boost::shared_ptr<Source> source;
5252 ChanCount diskstream_channels (track.n_channels());
5253 framepos_t position;
5254 framecnt_t this_chunk;
5256 framepos_t latency_skip;
5258 framepos_t len = end - start;
5259 bool need_block_size_reset = false;
5260 ChanCount const max_proc = track.max_processor_streams ();
5261 string legal_playlist_name;
5262 string possible_path;
5265 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5266 end, start) << endmsg;
5270 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5271 include_endpoint, for_export, for_freeze);
5273 if (diskstream_channels.n(track.data_type()) < 1) {
5274 error << _("Cannot write a range with no data.") << endmsg;
5278 // block all process callback handling
5280 block_processing ();
5283 // synchronize with AudioEngine::process_callback()
5284 // make sure processing is not currently running
5285 // and processing_blocked() is honored before
5286 // acquiring thread buffers
5287 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5290 _bounce_processing_active = true;
5292 /* call tree *MUST* hold route_lock */
5294 if ((playlist = track.playlist()) == 0) {
5298 legal_playlist_name = legalize_for_path (playlist->name());
5300 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5302 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5303 string path = ((track.data_type() == DataType::AUDIO)
5304 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5305 : new_midi_source_path (legal_playlist_name));
5312 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5315 catch (failed_constructor& err) {
5316 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5320 srcs.push_back (source);
5323 /* tell redirects that care that we are about to use a much larger
5324 * blocksize. this will flush all plugins too, so that they are ready
5325 * to be used for this process.
5328 need_block_size_reset = true;
5329 track.set_block_size (bounce_chunk_size);
5330 _engine.main_thread()->get_buffers ();
5334 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5336 /* create a set of reasonably-sized buffers */
5337 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5338 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5340 buffers.set_count (max_proc);
5342 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5343 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5344 boost::shared_ptr<MidiSource> ms;
5346 afs->prepare_for_peakfile_writes ();
5347 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5348 Source::Lock lock(ms->mutex());
5349 ms->mark_streaming_write_started(lock);
5353 while (to_do && !itt.cancel) {
5355 this_chunk = min (to_do, bounce_chunk_size);
5357 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5361 start += this_chunk;
5362 to_do -= this_chunk;
5363 itt.progress = (float) (1.0 - ((double) to_do / len));
5365 if (latency_skip >= bounce_chunk_size) {
5366 latency_skip -= bounce_chunk_size;
5370 const framecnt_t current_chunk = this_chunk - latency_skip;
5373 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5374 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5375 boost::shared_ptr<MidiSource> ms;
5378 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5381 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5382 Source::Lock lock(ms->mutex());
5384 const MidiBuffer& buf = buffers.get_midi(0);
5385 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5386 Evoral::Event<framepos_t> ev = *i;
5387 ev.set_time(ev.time() - position);
5388 ms->append_event_frames(lock, ev, ms->timeline_position());
5395 /* post-roll, pick up delayed processor output */
5396 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5398 while (latency_skip && !itt.cancel) {
5399 this_chunk = min (latency_skip, bounce_chunk_size);
5400 latency_skip -= this_chunk;
5402 buffers.silence (this_chunk, 0);
5403 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5406 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5407 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5410 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5422 xnow = localtime (&now);
5424 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5425 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5426 boost::shared_ptr<MidiSource> ms;
5429 afs->update_header (position, *xnow, now);
5430 afs->flush_header ();
5431 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5432 Source::Lock lock(ms->mutex());
5433 ms->mark_streaming_write_completed(lock);
5437 /* construct a region to represent the bounced material */
5441 plist.add (Properties::start, 0);
5442 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5443 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5445 result = RegionFactory::create (srcs, plist);
5451 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5452 (*src)->mark_for_remove ();
5453 (*src)->drop_references ();
5457 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5458 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5461 afs->done_with_peakfile_writes ();
5465 _bounce_processing_active = false;
5467 if (need_block_size_reset) {
5468 _engine.main_thread()->drop_buffers ();
5469 track.set_block_size (get_block_size());
5472 unblock_processing ();
5478 Session::gain_automation_buffer() const
5480 return ProcessThread::gain_automation_buffer ();
5484 Session::trim_automation_buffer() const
5486 return ProcessThread::trim_automation_buffer ();
5490 Session::send_gain_automation_buffer() const
5492 return ProcessThread::send_gain_automation_buffer ();
5496 Session::pan_automation_buffer() const
5498 return ProcessThread::pan_automation_buffer ();
5502 Session::get_silent_buffers (ChanCount count)
5504 return ProcessThread::get_silent_buffers (count);
5508 Session::get_scratch_buffers (ChanCount count, bool silence)
5510 return ProcessThread::get_scratch_buffers (count, silence);
5514 Session::get_route_buffers (ChanCount count, bool silence)
5516 return ProcessThread::get_route_buffers (count, silence);
5521 Session::get_mix_buffers (ChanCount count)
5523 return ProcessThread::get_mix_buffers (count);
5527 Session::ntracks () const
5530 boost::shared_ptr<RouteList> r = routes.reader ();
5532 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5533 if (boost::dynamic_pointer_cast<Track> (*i)) {
5542 Session::nbusses () const
5545 boost::shared_ptr<RouteList> r = routes.reader ();
5547 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5548 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5557 Session::add_automation_list(AutomationList *al)
5559 automation_lists[al->id()] = al;
5562 /** @return true if there is at least one record-enabled track, otherwise false */
5564 Session::have_rec_enabled_track () const
5566 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
5570 Session::have_rec_disabled_track () const
5572 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
5575 /** Update the state of our rec-enabled tracks flag */
5577 Session::update_route_record_state ()
5579 boost::shared_ptr<RouteList> rl = routes.reader ();
5580 RouteList::iterator i = rl->begin();
5581 while (i != rl->end ()) {
5583 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5584 if (tr && tr->record_enabled ()) {
5591 int const old = g_atomic_int_get (&_have_rec_enabled_track);
5593 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5595 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5596 RecordStateChanged (); /* EMIT SIGNAL */
5599 for (i = rl->begin(); i != rl->end (); ++i) {
5600 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5601 if (tr && !tr->record_enabled ()) {
5606 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
5608 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
5610 if (record_status() == Recording && record_arm_state_changed ) {
5611 RecordArmStateChanged ();
5617 Session::listen_position_changed ()
5619 boost::shared_ptr<RouteList> r = routes.reader ();
5621 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5622 (*i)->listen_position_changed ();
5627 Session::solo_control_mode_changed ()
5629 /* cancel all solo or all listen when solo control mode changes */
5632 set_solo (get_routes(), false);
5633 } else if (listening()) {
5634 set_listen (get_routes(), false);
5638 /** Called when a property of one of our route groups changes */
5640 Session::route_group_property_changed (RouteGroup* rg)
5642 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
5645 /** Called when a route is added to one of our route groups */
5647 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5649 RouteAddedToRouteGroup (rg, r);
5652 /** Called when a route is removed from one of our route groups */
5654 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
5656 update_route_record_state ();
5657 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
5660 boost::shared_ptr<RouteList>
5661 Session::get_tracks () const
5663 boost::shared_ptr<RouteList> rl = routes.reader ();
5664 boost::shared_ptr<RouteList> tl (new RouteList);
5666 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
5667 if (boost::dynamic_pointer_cast<Track> (*r)) {
5668 if (!(*r)->is_auditioner()) {
5676 boost::shared_ptr<RouteList>
5677 Session::get_routes_with_regions_at (framepos_t const p) const
5679 boost::shared_ptr<RouteList> r = routes.reader ();
5680 boost::shared_ptr<RouteList> rl (new RouteList);
5682 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5683 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5688 boost::shared_ptr<Playlist> pl = tr->playlist ();
5693 if (pl->has_region_at (p)) {
5702 Session::goto_end ()
5704 if (_session_range_location) {
5705 request_locate (_session_range_location->end(), false);
5707 request_locate (0, false);
5712 Session::goto_start ()
5714 if (_session_range_location) {
5715 request_locate (_session_range_location->start(), false);
5717 request_locate (0, false);
5722 Session::current_start_frame () const
5724 return _session_range_location ? _session_range_location->start() : 0;
5728 Session::current_end_frame () const
5730 return _session_range_location ? _session_range_location->end() : 0;
5734 Session::set_session_range_location (framepos_t start, framepos_t end)
5736 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
5737 _locations->add (_session_range_location);
5741 Session::step_edit_status_change (bool yn)
5747 send = (_step_editors == 0);
5752 send = (_step_editors == 1);
5755 if (_step_editors > 0) {
5761 StepEditStatusChange (val);
5767 Session::start_time_changed (framepos_t old)
5769 /* Update the auto loop range to match the session range
5770 (unless the auto loop range has been changed by the user)
5773 Location* s = _locations->session_range_location ();
5778 Location* l = _locations->auto_loop_location ();
5780 if (l && l->start() == old) {
5781 l->set_start (s->start(), true);
5786 Session::end_time_changed (framepos_t old)
5788 /* Update the auto loop range to match the session range
5789 (unless the auto loop range has been changed by the user)
5792 Location* s = _locations->session_range_location ();
5797 Location* l = _locations->auto_loop_location ();
5799 if (l && l->end() == old) {
5800 l->set_end (s->end(), true);
5804 std::vector<std::string>
5805 Session::source_search_path (DataType type) const
5809 if (session_dirs.size() == 1) {
5811 case DataType::AUDIO:
5812 sp.push_back (_session_dir->sound_path());
5814 case DataType::MIDI:
5815 sp.push_back (_session_dir->midi_path());
5819 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
5820 SessionDirectory sdir (i->path);
5822 case DataType::AUDIO:
5823 sp.push_back (sdir.sound_path());
5825 case DataType::MIDI:
5826 sp.push_back (sdir.midi_path());
5832 if (type == DataType::AUDIO) {
5833 const string sound_path_2X = _session_dir->sound_path_2X();
5834 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
5835 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
5836 sp.push_back (sound_path_2X);
5841 // now check the explicit (possibly user-specified) search path
5844 case DataType::AUDIO:
5845 sp += Searchpath(config.get_audio_search_path ());
5847 case DataType::MIDI:
5848 sp += Searchpath(config.get_midi_search_path ());
5856 Session::ensure_search_path_includes (const string& path, DataType type)
5865 case DataType::AUDIO:
5866 sp += Searchpath(config.get_audio_search_path ());
5868 case DataType::MIDI:
5869 sp += Searchpath (config.get_midi_search_path ());
5873 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
5874 /* No need to add this new directory if it has the same inode as
5875 an existing one; checking inode rather than name prevents duplicated
5876 directories when we are using symlinks.
5878 On Windows, I think we could just do if (*i == path) here.
5880 if (PBD::equivalent_paths (*i, path)) {
5888 case DataType::AUDIO:
5889 config.set_audio_search_path (sp.to_string());
5891 case DataType::MIDI:
5892 config.set_midi_search_path (sp.to_string());
5898 Session::remove_dir_from_search_path (const string& dir, DataType type)
5903 case DataType::AUDIO:
5904 sp = Searchpath(config.get_audio_search_path ());
5906 case DataType::MIDI:
5907 sp = Searchpath (config.get_midi_search_path ());
5914 case DataType::AUDIO:
5915 config.set_audio_search_path (sp.to_string());
5917 case DataType::MIDI:
5918 config.set_midi_search_path (sp.to_string());
5924 boost::shared_ptr<Speakers>
5925 Session::get_speakers()
5931 Session::unknown_processors () const
5935 boost::shared_ptr<RouteList> r = routes.reader ();
5936 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5937 list<string> t = (*i)->unknown_processors ();
5938 copy (t.begin(), t.end(), back_inserter (p));
5948 Session::update_latency (bool playback)
5950 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
5952 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
5956 boost::shared_ptr<RouteList> r = routes.reader ();
5957 framecnt_t max_latency = 0;
5960 /* reverse the list so that we work backwards from the last route to run to the first */
5961 RouteList* rl = routes.reader().get();
5962 r.reset (new RouteList (*rl));
5963 reverse (r->begin(), r->end());
5966 /* compute actual latency values for the given direction and store them all in per-port
5967 structures. this will also publish the same values (to JACK) so that computation of latency
5968 for routes can consistently use public latency values.
5971 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5972 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
5975 /* because we latency compensate playback, our published playback latencies should
5976 be the same for all output ports - all material played back by ardour has
5977 the same latency, whether its caused by plugins or by latency compensation. since
5978 these may differ from the values computed above, reset all playback port latencies
5982 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
5984 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5985 (*i)->set_public_port_latencies (max_latency, playback);
5990 post_playback_latency ();
5994 post_capture_latency ();
5997 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6001 Session::post_playback_latency ()
6003 set_worst_playback_latency ();
6005 boost::shared_ptr<RouteList> r = routes.reader ();
6007 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6008 if (!(*i)->is_auditioner() && ((*i)->active())) {
6009 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6013 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6014 (*i)->set_latency_compensation (_worst_track_latency);
6019 Session::post_capture_latency ()
6021 set_worst_capture_latency ();
6023 /* reflect any changes in capture latencies into capture offsets
6026 boost::shared_ptr<RouteList> rl = routes.reader();
6027 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6028 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6030 tr->set_capture_offset ();
6036 Session::initialize_latencies ()
6039 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6040 update_latency (false);
6041 update_latency (true);
6044 set_worst_io_latencies ();
6048 Session::set_worst_io_latencies ()
6050 set_worst_playback_latency ();
6051 set_worst_capture_latency ();
6055 Session::set_worst_playback_latency ()
6057 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6061 _worst_output_latency = 0;
6063 if (!_engine.connected()) {
6067 boost::shared_ptr<RouteList> r = routes.reader ();
6069 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6070 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6073 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6077 Session::set_worst_capture_latency ()
6079 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6083 _worst_input_latency = 0;
6085 if (!_engine.connected()) {
6089 boost::shared_ptr<RouteList> r = routes.reader ();
6091 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6092 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6095 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6099 Session::update_latency_compensation (bool force_whole_graph)
6101 bool some_track_latency_changed = false;
6103 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6107 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6109 _worst_track_latency = 0;
6111 boost::shared_ptr<RouteList> r = routes.reader ();
6113 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6114 if (!(*i)->is_auditioner() && ((*i)->active())) {
6116 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6117 some_track_latency_changed = true;
6119 _worst_track_latency = max (tl, _worst_track_latency);
6123 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6124 (some_track_latency_changed ? "yes" : "no")));
6126 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6128 if (some_track_latency_changed || force_whole_graph) {
6129 _engine.update_latencies ();
6133 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6134 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6138 tr->set_capture_offset ();
6143 Session::session_name_is_legal (const string& path)
6145 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6147 for (int i = 0; illegal_chars[i]; ++i) {
6148 if (path.find (illegal_chars[i]) != string::npos) {
6149 return illegal_chars[i];
6157 Session::next_control_id () const
6161 /* the monitor bus remote ID is in a different
6162 * "namespace" than regular routes. its existence doesn't
6163 * affect normal (low) numbered routes.
6170 /* the same about masterbus in Waves Tracks */
6172 if (Profile->get_trx() && _master_out) {
6176 return nroutes() - subtract;
6180 Session::notify_remote_id_change ()
6182 if (deletion_in_progress()) {
6186 switch (Config->get_remote_model()) {
6188 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6194 #ifdef USE_TRACKS_CODE_FEATURES
6195 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6196 * if track order has been changed by user
6198 reconnect_existing_routes(true, true);
6204 Session::sync_order_keys ()
6206 if (deletion_in_progress()) {
6210 /* tell everyone that something has happened to the sort keys
6211 and let them sync up with the change(s)
6212 this will give objects that manage the sort order keys the
6213 opportunity to keep them in sync if they wish to.
6216 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6218 reassign_track_numbers();
6220 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6222 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6226 Session::operation_in_progress (GQuark op) const
6228 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6231 boost::shared_ptr<Port>
6232 Session::ltc_input_port () const
6234 return _ltc_input->nth (0);
6237 boost::shared_ptr<Port>
6238 Session::ltc_output_port () const
6240 return _ltc_output->nth (0);
6244 Session::reconnect_ltc_input ()
6248 string src = Config->get_ltc_source_port();
6250 _ltc_input->disconnect (this);
6252 if (src != _("None") && !src.empty()) {
6253 _ltc_input->nth (0)->connect (src);
6256 if ( ARDOUR::Profile->get_trx () ) {
6257 // Tracks need this signal to update timecode_source_dropdown
6258 MtcOrLtcInputPortChanged (); //emit signal
6264 Session::reconnect_ltc_output ()
6268 string src = Config->get_ltc_output_port();
6270 _ltc_output->disconnect (this);
6272 if (src != _("None") && !src.empty()) {
6273 _ltc_output->nth (0)->connect (src);
6279 Session::set_range_selection (framepos_t start, framepos_t end)
6281 _range_selection = Evoral::Range<framepos_t> (start, end);
6282 #ifdef USE_TRACKS_CODE_FEATURES
6283 follow_playhead_priority ();
6288 Session::set_object_selection (framepos_t start, framepos_t end)
6290 _object_selection = Evoral::Range<framepos_t> (start, end);
6291 #ifdef USE_TRACKS_CODE_FEATURES
6292 follow_playhead_priority ();
6297 Session::clear_range_selection ()
6299 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6300 #ifdef USE_TRACKS_CODE_FEATURES
6301 follow_playhead_priority ();
6306 Session::clear_object_selection ()
6308 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6309 #ifdef USE_TRACKS_CODE_FEATURES
6310 follow_playhead_priority ();