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/pthread_utils.h"
46 #include "pbd/search_path.h"
47 #include "pbd/stacktrace.h"
48 #include "pbd/stl_delete.h"
49 #include "pbd/replace_all.h"
50 #include "pbd/unwind.h"
52 #include "ardour/amp.h"
53 #include "ardour/analyser.h"
54 #include "ardour/async_midi_port.h"
55 #include "ardour/audio_buffer.h"
56 #include "ardour/audio_diskstream.h"
57 #include "ardour/audio_port.h"
58 #include "ardour/audio_track.h"
59 #include "ardour/audioengine.h"
60 #include "ardour/audiofilesource.h"
61 #include "ardour/auditioner.h"
62 #include "ardour/buffer_manager.h"
63 #include "ardour/buffer_set.h"
64 #include "ardour/bundle.h"
65 #include "ardour/butler.h"
66 #include "ardour/click.h"
67 #include "ardour/control_protocol_manager.h"
68 #include "ardour/data_type.h"
69 #include "ardour/debug.h"
70 #include "ardour/directory_names.h"
71 #ifdef USE_TRACKS_CODE_FEATURES
72 #include "ardour/engine_state_controller.h"
74 #include "ardour/filename_extensions.h"
75 #include "ardour/gain_control.h"
76 #include "ardour/graph.h"
77 #include "ardour/luabindings.h"
78 #include "ardour/midiport_manager.h"
79 #include "ardour/scene_changer.h"
80 #include "ardour/midi_patch_manager.h"
81 #include "ardour/midi_track.h"
82 #include "ardour/midi_ui.h"
83 #include "ardour/operations.h"
84 #include "ardour/playlist.h"
85 #include "ardour/plugin.h"
86 #include "ardour/plugin_insert.h"
87 #include "ardour/process_thread.h"
88 #include "ardour/profile.h"
89 #include "ardour/rc_configuration.h"
90 #include "ardour/recent_sessions.h"
91 #include "ardour/region.h"
92 #include "ardour/region_factory.h"
93 #include "ardour/route_graph.h"
94 #include "ardour/route_group.h"
95 #include "ardour/route_sorters.h"
96 #include "ardour/send.h"
97 #include "ardour/session.h"
98 #include "ardour/session_directory.h"
99 #include "ardour/session_playlists.h"
100 #include "ardour/smf_source.h"
101 #include "ardour/source_factory.h"
102 #include "ardour/speakers.h"
103 #include "ardour/tempo.h"
104 #include "ardour/track.h"
105 #include "ardour/user_bundle.h"
106 #include "ardour/utils.h"
108 #include "midi++/port.h"
109 #include "midi++/mmc.h"
111 #include "LuaBridge/LuaBridge.h"
115 #include <glibmm/checksum.h>
124 using namespace ARDOUR;
127 bool Session::_disable_all_loaded_plugins = false;
128 bool Session::_bypass_all_loaded_plugins = false;
129 guint Session::_name_id_counter = 0;
131 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
132 PBD::Signal1<void,std::string> Session::Dialog;
133 PBD::Signal0<int> Session::AskAboutPendingState;
134 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
135 PBD::Signal2<void, framecnt_t, framecnt_t> Session::NotifyAboutSampleRateMismatch;
136 PBD::Signal0<void> Session::SendFeedback;
137 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
139 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
140 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
141 PBD::Signal2<void,std::string, std::string> Session::Exported;
142 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
143 PBD::Signal0<void> Session::Quit;
144 PBD::Signal0<void> Session::FeedbackDetected;
145 PBD::Signal0<void> Session::SuccessfulGraphSort;
146 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
148 const framecnt_t Session::bounce_chunk_size = 8192;
149 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
150 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
152 // seconds should be added after the region exceeds end marker
153 #ifdef USE_TRACKS_CODE_FEATURES
154 const uint32_t Session::session_end_shift = 5;
156 const uint32_t Session::session_end_shift = 0;
159 /** @param snapshot_name Snapshot name, without .ardour suffix */
160 Session::Session (AudioEngine &eng,
161 const string& fullpath,
162 const string& snapshot_name,
163 BusProfile* bus_profile,
165 : playlists (new SessionPlaylists)
167 , process_function (&Session::process_with_events)
168 , _bounce_processing_active (false)
169 , waiting_for_sync_offset (false)
170 , _base_frame_rate (0)
171 , _nominal_frame_rate (0)
172 , _current_frame_rate (0)
173 , transport_sub_state (0)
174 , _record_status (Disabled)
175 , _transport_frame (0)
176 , _session_range_location (0)
179 , _transport_speed (0)
180 , _default_transport_speed (1.0)
181 , _last_transport_speed (0)
182 , _target_transport_speed (0.0)
183 , auto_play_legal (false)
184 , _last_slave_transport_frame (0)
185 , maximum_output_latency (0)
186 , _requested_return_frame (-1)
187 , current_block_size (0)
188 , _worst_output_latency (0)
189 , _worst_input_latency (0)
190 , _worst_track_latency (0)
191 , _have_captured (false)
192 , _non_soloed_outs_muted (false)
195 , _solo_isolated_cnt (0)
197 , _was_seamless (Config->get_seamless_loop ())
198 , _under_nsm_control (false)
200 , delta_accumulator_cnt (0)
201 , average_slave_delta (1800) // !!! why 1800 ???
203 , have_first_delta_accumulator (false)
204 , _slave_state (Stopped)
205 , _mtc_active (false)
206 , _ltc_active (false)
207 , post_export_sync (false)
208 , post_export_position (0)
210 , _export_rolling (false)
211 , _export_preroll (0)
212 , _pre_export_mmc_enabled (false)
213 , _name (snapshot_name)
215 , _send_qf_mtc (false)
216 , _pframes_since_last_mtc (0)
217 , session_midi_feedback (0)
219 , loop_changing (false)
221 , _session_dir (new SessionDirectory (fullpath))
222 , _current_snapshot_name (snapshot_name)
224 , state_was_pending (false)
225 , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
227 , _save_queued (false)
228 , _last_roll_location (0)
229 , _last_roll_or_reversal_location (0)
230 , _last_record_location (0)
231 , pending_locate_roll (false)
232 , pending_locate_frame (0)
233 , pending_locate_flush (false)
234 , pending_abort (false)
235 , pending_auto_loop (false)
236 , _mempool ("Session", 1048576)
237 , lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
239 , _butler (new Butler (*this))
240 , _post_transport_work (0)
241 , cumulative_rf_motion (0)
243 , _locations (new Locations (*this))
244 , _ignore_skips_updates (false)
245 , _rt_thread_active (false)
246 , _rt_emit_pending (false)
247 , _ac_thread_active (false)
249 , outbound_mtc_timecode_frame (0)
250 , next_quarter_frame_to_send (-1)
251 , _frames_per_timecode_frame (0)
252 , _frames_per_hour (0)
253 , _timecode_frames_per_hour (0)
254 , last_timecode_valid (false)
255 , last_timecode_when (0)
256 , _send_timecode_update (false)
268 , ltc_timecode_offset (0)
269 , ltc_timecode_negative_offset (false)
270 , midi_control_ui (0)
272 , _all_route_group (new RouteGroup (*this, "all"))
273 , routes (new RouteList)
274 , _adding_routes_in_progress (false)
275 , _reconnecting_routes_in_progress (false)
276 , _route_deletion_in_progress (false)
277 , destructive_index (0)
278 , _track_number_decimals(1)
279 , default_fade_steepness (0)
280 , default_fade_msecs (0)
281 , _total_free_4k_blocks (0)
282 , _total_free_4k_blocks_uncertain (false)
283 , no_questions_about_missing_files (false)
286 , _bundles (new BundleList)
287 , _bundle_xml_node (0)
291 , click_emphasis_data (0)
293 , click_emphasis_length (0)
294 , _clicks_cleared (0)
295 , _play_range (false)
296 , _range_selection (-1,-1)
297 , _object_selection (-1,-1)
299 , first_file_data_format_reset (true)
300 , first_file_header_format_reset (true)
301 , have_looped (false)
302 , _have_rec_enabled_track (false)
303 , _have_rec_disabled_track (true)
305 , _suspend_timecode_transmission (0)
306 , _speakers (new Speakers)
308 , ignore_route_processor_changes (false)
315 pthread_mutex_init (&_rt_emit_mutex, 0);
316 pthread_cond_init (&_rt_emit_cond, 0);
318 pthread_mutex_init (&_auto_connect_mutex, 0);
319 pthread_cond_init (&_auto_connect_cond, 0);
321 init_name_id_counter (1); // reset for new sessions, start at 1
323 pre_engine_init (fullpath);
329 Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
331 #ifdef USE_TRACKS_CODE_FEATURES
332 sr = EngineStateController::instance()->get_current_sample_rate();
334 if (ensure_engine (sr)) {
336 throw SessionException (_("Cannot connect to audio/midi engine"));
339 // set samplerate for plugins added early
340 // e.g from templates or MB channelstrip
341 set_block_size (_engine.samples_per_cycle());
342 set_frame_rate (_engine.sample_rate());
344 if (create (mix_template, bus_profile)) {
346 throw SessionException (_("Session initialization failed"));
349 /* if a mix template was provided, then ::create() will
350 * have copied it into the session and we need to load it
351 * so that we have the state ready for ::set_state()
352 * after the engine is started.
354 * Note that we do NOT try to get the sample rate from
355 * the template at this time, though doing so would
356 * be easy if we decided this was an appropriate part
360 if (!mix_template.empty()) {
361 if (load_state (_current_snapshot_name)) {
362 throw SessionException (_("Failed to load template/snapshot state"));
364 store_recent_templates (mix_template);
367 /* load default session properties - if any */
372 if (load_state (_current_snapshot_name)) {
373 throw SessionException (_("Failed to load state"));
376 /* try to get sample rate from XML state so that we
377 * can influence the SR if we set up the audio
382 const XMLProperty* prop;
383 if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {
384 sr = atoi (prop->value());
388 if (ensure_engine (sr)) {
390 throw SessionException (_("Cannot connect to audio/midi engine"));
394 if (post_engine_init ()) {
396 throw SessionException (_("Cannot configure audio/midi engine with session parameters"));
399 store_recent_sessions (_name, _path);
401 bool was_dirty = dirty();
403 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
405 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
406 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
409 DirtyChanged (); /* EMIT SIGNAL */
412 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
413 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
415 emit_thread_start ();
416 auto_connect_thread_start ();
418 /* hook us up to the engine since we are now completely constructed */
420 BootMessage (_("Connect to engine"));
422 _engine.set_session (this);
423 _engine.reset_timebase ();
425 #ifdef USE_TRACKS_CODE_FEATURES
427 EngineStateController::instance()->set_session(this);
430 if ( ARDOUR::Profile->get_trx () ) {
432 /* Waves Tracks: fill session with tracks basing on the amount of inputs.
433 * each available input must have corresponding track when session starts.
436 uint32_t how_many (0);
438 std::vector<std::string> inputs;
439 EngineStateController::instance()->get_physical_audio_inputs(inputs);
441 how_many = inputs.size();
443 list<boost::shared_ptr<AudioTrack> > tracks;
445 // Track names after driver
446 if (Config->get_tracks_auto_naming() == NameAfterDriver) {
447 string track_name = "";
448 for (std::vector<string>::size_type i = 0; i < inputs.size(); ++i) {
450 track_name = inputs[i];
451 replace_all (track_name, "system:capture", "");
453 list<boost::shared_ptr<AudioTrack> > single_track = new_audio_track (1, 1, Normal, 0, 1, track_name);
454 tracks.insert(tracks.begin(), single_track.front());
456 } else { // Default track names
457 tracks = new_audio_track (1, 1, Normal, 0, how_many, string());
460 if (tracks.size() != how_many) {
462 throw failed_constructor ();
471 BootMessage (_("Session loading complete"));
483 Session::next_name_id ()
485 return g_atomic_int_add (&_name_id_counter, 1);
489 Session::name_id_counter ()
491 return g_atomic_int_get (&_name_id_counter);
495 Session::init_name_id_counter (guint n)
497 g_atomic_int_set (&_name_id_counter, n);
501 Session::ensure_engine (uint32_t desired_sample_rate)
503 if (_engine.current_backend() == 0) {
504 /* backend is unknown ... */
505 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
506 if (r.get_value_or (-1) != 0) {
509 } else if (_engine.setup_required()) {
510 /* backend is known, but setup is needed */
511 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
512 if (r.get_value_or (-1) != 0) {
515 } else if (!_engine.running()) {
516 if (_engine.start()) {
521 /* at this point the engine should be running
524 if (!_engine.running()) {
528 return immediately_post_engine ();
533 Session::immediately_post_engine ()
535 /* Do various initializations that should take place directly after we
536 * know that the engine is running, but before we either create a
537 * session or set state for an existing one.
540 if (how_many_dsp_threads () > 1) {
541 /* For now, only create the graph if we are using >1 DSP threads, as
542 it is a bit slower than the old code with 1 thread.
544 _process_graph.reset (new Graph (*this));
547 /* every time we reconnect, recompute worst case output latencies */
549 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
551 if (synced_to_engine()) {
552 _engine.transport_stop ();
555 if (config.get_jack_time_master()) {
556 _engine.transport_locate (_transport_frame);
560 BootMessage (_("Set up LTC"));
562 BootMessage (_("Set up Click"));
564 BootMessage (_("Set up standard connections"));
568 catch (failed_constructor& err) {
572 /* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
574 _engine.PortRegisteredOrUnregistered.connect_same_thread (*this, boost::bind (&Session::setup_bundles, this));
582 vector<void*> debug_pointers;
584 /* if we got to here, leaving pending capture state around
588 remove_pending_capture_state ();
592 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
594 /* disconnect from any and all signals that we are connected to */
598 /* shutdown control surface protocols while we still have ports
599 and the engine to move data to any devices.
602 ControlProtocolManager::instance().drop_protocols ();
604 MIDI::Name::MidiPatchManager::instance().remove_search_path(session_directory().midi_patch_path());
606 _engine.remove_session ();
608 #ifdef USE_TRACKS_CODE_FEATURES
609 EngineStateController::instance()->remove_session();
612 /* deregister all ports - there will be no process or any other
613 * callbacks from the engine any more.
616 Port::PortDrop (); /* EMIT SIGNAL */
620 /* clear history so that no references to objects are held any more */
624 /* clear state tree so that no references to objects are held any more */
629 // unregister all lua functions, drop held references (if any)
631 lua.do_command ("Session = nil");
639 lua.collect_garbage ();
641 /* reset dynamic state version back to default */
642 Stateful::loading_state_version = 0;
644 _butler->drop_references ();
648 delete _all_route_group;
650 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
651 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
655 if (click_data != default_click) {
656 delete [] click_data;
659 if (click_emphasis_data != default_click_emphasis) {
660 delete [] click_emphasis_data;
665 /* need to remove auditioner before monitoring section
666 * otherwise it is re-connected */
669 /* drop references to routes held by the monitoring section
670 * specifically _monitor_out aux/listen references */
671 remove_monitor_section();
673 /* clear out any pending dead wood from RCU managed objects */
678 AudioDiskstream::free_working_buffers();
680 /* tell everyone who is still standing that we're about to die */
683 /* tell everyone to drop references and delete objects as we go */
685 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
686 RegionFactory::delete_all_regions ();
688 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
690 /* reset these three references to special routes before we do the usual route delete thing */
692 _master_out.reset ();
693 _monitor_out.reset ();
696 RCUWriter<RouteList> writer (routes);
697 boost::shared_ptr<RouteList> r = writer.get_copy ();
699 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
700 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
701 (*i)->drop_references ();
705 /* writer goes out of scope and updates master */
710 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
711 Glib::Threads::Mutex::Lock lm (source_lock);
712 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
713 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
714 i->second->drop_references ();
720 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
723 emit_thread_terminate ();
725 pthread_cond_destroy (&_rt_emit_cond);
726 pthread_mutex_destroy (&_rt_emit_mutex);
728 auto_connect_thread_terminate ();
730 pthread_cond_destroy (&_auto_connect_cond);
731 pthread_mutex_destroy (&_auto_connect_mutex);
733 delete _scene_changer; _scene_changer = 0;
734 delete midi_control_ui; midi_control_ui = 0;
736 delete _mmc; _mmc = 0;
737 delete _midi_ports; _midi_ports = 0;
738 delete _locations; _locations = 0;
742 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
744 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
745 boost_debug_list_ptrs ();
750 Session::setup_ltc ()
754 _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
755 _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
757 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
758 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
761 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
762 _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
764 reconnect_ltc_input ();
767 if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
768 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
771 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
772 _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
774 reconnect_ltc_output ();
777 /* fix up names of LTC ports because we don't want the normal
778 * IO style of NAME/TYPE-{in,out}N
781 _ltc_input->nth (0)->set_name (X_("LTC-in"));
782 _ltc_output->nth (0)->set_name (X_("LTC-out"));
786 Session::setup_click ()
790 boost::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation)));
791 boost::shared_ptr<GainControl> gain_control = boost::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
793 _click_io.reset (new ClickIO (*this, X_("Click")));
794 _click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
795 _click_gain->activate ();
797 setup_click_state (state_tree->root());
799 setup_click_state (0);
804 Session::setup_click_state (const XMLNode* node)
806 const XMLNode* child = 0;
808 if (node && (child = find_named_node (*node, "Click")) != 0) {
810 /* existing state for Click */
813 if (Stateful::loading_state_version < 3000) {
814 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
816 const XMLNodeList& children (child->children());
817 XMLNodeList::const_iterator i = children.begin();
818 if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
820 if (i != children.end()) {
821 c = _click_gain->set_state (**i, Stateful::loading_state_version);
827 _clicking = Config->get_clicking ();
831 error << _("could not setup Click I/O") << endmsg;
838 /* default state for Click: dual-mono to first 2 physical outputs */
841 _engine.get_physical_outputs (DataType::AUDIO, outs);
843 for (uint32_t physport = 0; physport < 2; ++physport) {
844 if (outs.size() > physport) {
845 if (_click_io->add_port (outs[physport], this)) {
846 // relax, even though its an error
851 if (_click_io->n_ports () > ChanCount::ZERO) {
852 _clicking = Config->get_clicking ();
858 Session::setup_bundles ()
862 RCUWriter<BundleList> writer (_bundles);
863 boost::shared_ptr<BundleList> b = writer.get_copy ();
864 for (BundleList::iterator i = b->begin(); i != b->end();) {
865 if (boost::dynamic_pointer_cast<UserBundle>(*i)) {
873 vector<string> inputs[DataType::num_types];
874 vector<string> outputs[DataType::num_types];
875 for (uint32_t i = 0; i < DataType::num_types; ++i) {
876 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
877 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
880 /* Create a set of Bundle objects that map
881 to the physical I/O currently available. We create both
882 mono and stereo bundles, so that the common cases of mono
883 and stereo tracks get bundles to put in their mixer strip
884 in / out menus. There may be a nicer way of achieving that;
885 it doesn't really scale that well to higher channel counts
888 /* mono output bundles */
890 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
892 std::string pn = _engine.get_pretty_name_by_name (outputs[DataType::AUDIO][np]);
894 snprintf (buf, sizeof (buf), _("out %s"), pn.c_str());
896 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
899 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
900 c->add_channel (_("mono"), DataType::AUDIO);
901 c->set_port (0, outputs[DataType::AUDIO][np]);
903 add_bundle (c, false);
906 /* stereo output bundles */
908 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
909 if (np + 1 < outputs[DataType::AUDIO].size()) {
911 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
912 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
913 c->add_channel (_("L"), DataType::AUDIO);
914 c->set_port (0, outputs[DataType::AUDIO][np]);
915 c->add_channel (_("R"), DataType::AUDIO);
916 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
918 add_bundle (c, false);
922 /* mono input bundles */
924 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
926 std::string pn = _engine.get_pretty_name_by_name (inputs[DataType::AUDIO][np]);
928 snprintf (buf, sizeof (buf), _("in %s"), pn.c_str());
930 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
933 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
934 c->add_channel (_("mono"), DataType::AUDIO);
935 c->set_port (0, inputs[DataType::AUDIO][np]);
937 add_bundle (c, false);
940 /* stereo input bundles */
942 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
943 if (np + 1 < inputs[DataType::AUDIO].size()) {
945 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
947 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
948 c->add_channel (_("L"), DataType::AUDIO);
949 c->set_port (0, inputs[DataType::AUDIO][np]);
950 c->add_channel (_("R"), DataType::AUDIO);
951 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
953 add_bundle (c, false);
957 /* MIDI input bundles */
959 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
960 string n = inputs[DataType::MIDI][np];
961 std::string pn = _engine.get_pretty_name_by_name (n);
965 boost::erase_first (n, X_("alsa_pcm:"));
967 boost::shared_ptr<Bundle> c (new Bundle (n, false));
968 c->add_channel ("", DataType::MIDI);
969 c->set_port (0, inputs[DataType::MIDI][np]);
970 add_bundle (c, false);
973 /* MIDI output bundles */
975 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
976 string n = outputs[DataType::MIDI][np];
977 std::string pn = _engine.get_pretty_name_by_name (n);
981 boost::erase_first (n, X_("alsa_pcm:"));
983 boost::shared_ptr<Bundle> c (new Bundle (n, true));
984 c->add_channel ("", DataType::MIDI);
985 c->set_port (0, outputs[DataType::MIDI][np]);
986 add_bundle (c, false);
989 // we trust the backend to only calls us if there's a change
990 BundleAddedOrRemoved (); /* EMIT SIGNAL */
994 Session::auto_connect_master_bus ()
996 if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
1000 // Waves Tracks: Do not connect master bas for Tracks if AutoConnectMaster option is not set
1001 // In this case it means "Multi Out" output mode
1002 if (ARDOUR::Profile->get_trx() && !(Config->get_output_auto_connect() & AutoConnectMaster) ) {
1006 /* if requested auto-connect the outputs to the first N physical ports.
1009 uint32_t limit = _master_out->n_outputs().n_total();
1010 vector<string> outputs[DataType::num_types];
1012 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1013 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1016 for (uint32_t n = 0; n < limit; ++n) {
1017 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
1019 if (outputs[p->type()].size() > n) {
1020 connect_to = outputs[p->type()][n];
1023 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
1024 if (_master_out->output()->connect (p, connect_to, this)) {
1025 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
1034 Session::remove_monitor_section ()
1036 if (!_monitor_out || Profile->get_trx()) {
1040 /* force reversion to Solo-In-Place */
1041 Config->set_solo_control_is_listen_control (false);
1043 /* if we are auditioning, cancel it ... this is a workaround
1044 to a problem (auditioning does not execute the process graph,
1045 which is needed to remove routes when using >1 core for processing)
1050 /* Hold process lock while doing this so that we don't hear bits and
1051 * pieces of audio as we work on each route.
1054 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1056 /* Connect tracks to monitor section. Note that in an
1057 existing session, the internal sends will already exist, but we want the
1058 routes to notice that they connect to the control out specifically.
1062 boost::shared_ptr<RouteList> r = routes.reader ();
1063 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1065 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
1067 if ((*x)->is_monitor()) {
1069 } else if ((*x)->is_master()) {
1072 (*x)->remove_aux_or_listen (_monitor_out);
1077 remove_route (_monitor_out);
1078 auto_connect_master_bus ();
1081 auditioner->connect ();
1083 Config->ParameterChanged ("use-monitor-bus");
1087 Session::add_monitor_section ()
1091 if (_monitor_out || !_master_out || Profile->get_trx()) {
1095 boost::shared_ptr<Route> r (new Route (*this, _("Monitor"), Route::MonitorOut, DataType::AUDIO));
1101 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1102 // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
1105 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1106 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1107 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1109 error << _("Cannot create monitor section. 'Monitor' Port name is not unique.") << endmsg;
1114 add_routes (rl, false, false, false);
1116 assert (_monitor_out);
1118 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
1119 are undefined, at best.
1122 uint32_t limit = _monitor_out->n_inputs().n_audio();
1126 /* connect the inputs to the master bus outputs. this
1127 * represents a separate data feed from the internal sends from
1128 * each route. as of jan 2011, it allows the monitor section to
1129 * conditionally ignore either the internal sends or the normal
1130 * input feed, but we should really find a better way to do
1134 _master_out->output()->disconnect (this);
1136 for (uint32_t n = 0; n < limit; ++n) {
1137 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1138 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1141 string connect_to = o->name();
1142 if (_monitor_out->input()->connect (p, connect_to, this)) {
1143 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1151 /* if monitor section is not connected, connect it to physical outs
1154 if ((Config->get_auto_connect_standard_busses () || Profile->get_mixbus ()) && !_monitor_out->output()->connected ()) {
1156 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1158 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1161 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1163 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1164 Config->get_monitor_bus_preferred_bundle())
1170 /* Monitor bus is audio only */
1172 vector<string> outputs[DataType::num_types];
1174 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1175 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1178 uint32_t mod = outputs[DataType::AUDIO].size();
1179 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1183 for (uint32_t n = 0; n < limit; ++n) {
1185 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1187 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1188 connect_to = outputs[DataType::AUDIO][n % mod];
1191 if (!connect_to.empty()) {
1192 if (_monitor_out->output()->connect (p, connect_to, this)) {
1193 error << string_compose (
1194 _("cannot connect control output %1 to %2"),
1205 /* Hold process lock while doing this so that we don't hear bits and
1206 * pieces of audio as we work on each route.
1209 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1211 /* Connect tracks to monitor section. Note that in an
1212 existing session, the internal sends will already exist, but we want the
1213 routes to notice that they connect to the control out specifically.
1217 boost::shared_ptr<RouteList> rls = routes.reader ();
1219 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1221 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1223 if ((*x)->is_monitor()) {
1225 } else if ((*x)->is_master()) {
1228 (*x)->enable_monitor_send ();
1233 auditioner->connect ();
1235 Config->ParameterChanged ("use-monitor-bus");
1239 Session::reset_monitor_section ()
1241 /* Process lock should be held by the caller.*/
1243 if (!_monitor_out || Profile->get_trx()) {
1247 uint32_t limit = _master_out->n_outputs().n_audio();
1249 /* connect the inputs to the master bus outputs. this
1250 * represents a separate data feed from the internal sends from
1251 * each route. as of jan 2011, it allows the monitor section to
1252 * conditionally ignore either the internal sends or the normal
1253 * input feed, but we should really find a better way to do
1257 _master_out->output()->disconnect (this);
1258 _monitor_out->output()->disconnect (this);
1260 _monitor_out->input()->ensure_io (_master_out->output()->n_ports(), false, this);
1261 _monitor_out->output()->ensure_io (_master_out->output()->n_ports(), false, this);
1263 for (uint32_t n = 0; n < limit; ++n) {
1264 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
1265 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
1268 string connect_to = o->name();
1269 if (_monitor_out->input()->connect (p, connect_to, this)) {
1270 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
1277 /* connect monitor section to physical outs
1280 if (Config->get_auto_connect_standard_busses()) {
1282 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
1284 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
1287 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
1289 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
1290 Config->get_monitor_bus_preferred_bundle())
1296 /* Monitor bus is audio only */
1298 vector<string> outputs[DataType::num_types];
1300 for (uint32_t i = 0; i < DataType::num_types; ++i) {
1301 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
1304 uint32_t mod = outputs[DataType::AUDIO].size();
1305 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
1309 for (uint32_t n = 0; n < limit; ++n) {
1311 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
1313 if (outputs[DataType::AUDIO].size() > (n % mod)) {
1314 connect_to = outputs[DataType::AUDIO][n % mod];
1317 if (!connect_to.empty()) {
1318 if (_monitor_out->output()->connect (p, connect_to, this)) {
1319 error << string_compose (
1320 _("cannot connect control output %1 to %2"),
1331 /* Connect tracks to monitor section. Note that in an
1332 existing session, the internal sends will already exist, but we want the
1333 routes to notice that they connect to the control out specifically.
1337 boost::shared_ptr<RouteList> rls = routes.reader ();
1339 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1341 for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1343 if ((*x)->is_monitor()) {
1345 } else if ((*x)->is_master()) {
1348 (*x)->enable_monitor_send ();
1354 Session::hookup_io ()
1356 /* stop graph reordering notifications from
1357 causing resorts, etc.
1360 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1364 /* we delay creating the auditioner till now because
1365 it makes its own connections to ports.
1369 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1371 throw failed_constructor ();
1373 a->use_new_diskstream ();
1377 catch (failed_constructor& err) {
1378 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1382 /* load bundles, which we may have postponed earlier on */
1383 if (_bundle_xml_node) {
1384 load_bundles (*_bundle_xml_node);
1385 delete _bundle_xml_node;
1388 /* Tell all IO objects to connect themselves together */
1390 IO::enable_connecting ();
1392 /* Now tell all "floating" ports to connect to whatever
1393 they should be connected to.
1396 AudioEngine::instance()->reconnect_ports ();
1398 /* Anyone who cares about input state, wake up and do something */
1400 IOConnectionsComplete (); /* EMIT SIGNAL */
1402 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1404 /* now handle the whole enchilada as if it was one
1405 graph reorder event.
1410 /* update the full solo state, which can't be
1411 correctly determined on a per-route basis, but
1412 needs the global overview that only the session
1416 update_route_solo_state ();
1420 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1422 boost::shared_ptr<Track> track = wp.lock ();
1427 boost::shared_ptr<Playlist> playlist;
1429 if ((playlist = track->playlist()) != 0) {
1430 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1431 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1432 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1437 Session::record_enabling_legal () const
1439 /* this used to be in here, but survey says.... we don't need to restrict it */
1440 // if (record_status() == Recording) {
1444 if (Config->get_all_safe()) {
1451 Session::set_track_monitor_input_status (bool yn)
1453 boost::shared_ptr<RouteList> rl = routes.reader ();
1454 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1455 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1456 if (tr && tr->record_enabled ()) {
1457 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1458 tr->request_input_monitoring (yn);
1464 Session::auto_punch_start_changed (Location* location)
1466 replace_event (SessionEvent::PunchIn, location->start());
1468 if (get_record_enabled() && config.get_punch_in()) {
1469 /* capture start has been changed, so save new pending state */
1470 save_state ("", true);
1475 Session::auto_punch_end_changed (Location* location)
1477 framepos_t when_to_stop = location->end();
1478 // when_to_stop += _worst_output_latency + _worst_input_latency;
1479 replace_event (SessionEvent::PunchOut, when_to_stop);
1483 Session::auto_punch_changed (Location* location)
1485 framepos_t when_to_stop = location->end();
1487 replace_event (SessionEvent::PunchIn, location->start());
1488 //when_to_stop += _worst_output_latency + _worst_input_latency;
1489 replace_event (SessionEvent::PunchOut, when_to_stop);
1492 /** @param loc A loop location.
1493 * @param pos Filled in with the start time of the required fade-out (in session frames).
1494 * @param length Filled in with the length of the required fade-out.
1497 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1499 pos = max (loc->start(), loc->end() - 64);
1500 length = loc->end() - pos;
1504 Session::auto_loop_changed (Location* location)
1506 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1509 auto_loop_declick_range (location, dcp, dcl);
1511 if (transport_rolling() && play_loop) {
1513 replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1515 // if (_transport_frame > location->end()) {
1517 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1518 // relocate to beginning of loop
1519 clear_events (SessionEvent::LocateRoll);
1521 request_locate (location->start(), true);
1524 else if (Config->get_seamless_loop() && !loop_changing) {
1526 // schedule a locate-roll to refill the diskstreams at the
1527 // previous loop end
1528 loop_changing = true;
1530 if (location->end() > last_loopend) {
1531 clear_events (SessionEvent::LocateRoll);
1532 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1538 clear_events (SessionEvent::AutoLoopDeclick);
1539 clear_events (SessionEvent::AutoLoop);
1542 /* possibly move playhead if not rolling; if we are rolling we'll move
1543 to the loop start on stop if that is appropriate.
1548 if (!transport_rolling() && select_playhead_priority_target (pos)) {
1549 if (pos == location->start()) {
1550 request_locate (pos);
1555 last_loopend = location->end();
1560 Session::set_auto_punch_location (Location* location)
1564 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1565 punch_connections.drop_connections();
1566 existing->set_auto_punch (false, this);
1567 remove_event (existing->start(), SessionEvent::PunchIn);
1568 clear_events (SessionEvent::PunchOut);
1569 auto_punch_location_changed (0);
1574 if (location == 0) {
1578 if (location->end() <= location->start()) {
1579 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1583 punch_connections.drop_connections ();
1585 location->StartChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, location));
1586 location->EndChanged.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, location));
1587 location->Changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, location));
1589 location->set_auto_punch (true, this);
1591 auto_punch_changed (location);
1593 auto_punch_location_changed (location);
1597 Session::set_session_extents (framepos_t start, framepos_t end)
1600 if ((existing = _locations->session_range_location()) == 0) {
1601 //if there is no existing session, we need to make a new session location (should never happen)
1602 existing = new Location (*this, 0, 0, _("session"), Location::IsSessionRange);
1606 error << _("Session: you can't use that location for session start/end)") << endmsg;
1610 existing->set( start, end );
1616 Session::set_auto_loop_location (Location* location)
1620 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1621 loop_connections.drop_connections ();
1622 existing->set_auto_loop (false, this);
1623 remove_event (existing->end(), SessionEvent::AutoLoop);
1626 auto_loop_declick_range (existing, dcp, dcl);
1627 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1628 auto_loop_location_changed (0);
1633 if (location == 0) {
1637 if (location->end() <= location->start()) {
1638 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1642 last_loopend = location->end();
1644 loop_connections.drop_connections ();
1646 location->StartChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1647 location->EndChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1648 location->Changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1649 location->FlagsChanged.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, location));
1651 location->set_auto_loop (true, this);
1653 if (Config->get_loop_is_mode() && play_loop && Config->get_seamless_loop()) {
1654 // set all tracks to use internal looping
1655 boost::shared_ptr<RouteList> rl = routes.reader ();
1656 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1657 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1658 if (tr && !tr->hidden()) {
1659 tr->set_loop (location);
1664 /* take care of our stuff first */
1666 auto_loop_changed (location);
1668 /* now tell everyone else */
1670 auto_loop_location_changed (location);
1674 Session::update_marks (Location*)
1680 Session::update_skips (Location* loc, bool consolidate)
1682 if (_ignore_skips_updates) {
1686 Locations::LocationList skips;
1689 PBD::Unwinder<bool> uw (_ignore_skips_updates, true);
1690 consolidate_skips (loc);
1693 sync_locations_to_skips ();
1699 Session::consolidate_skips (Location* loc)
1701 Locations::LocationList all_locations = _locations->list ();
1703 for (Locations::LocationList::iterator l = all_locations.begin(); l != all_locations.end(); ) {
1705 if (!(*l)->is_skip ()) {
1710 /* don't test against self */
1717 switch (Evoral::coverage ((*l)->start(), (*l)->end(), loc->start(), loc->end())) {
1718 case Evoral::OverlapInternal:
1719 case Evoral::OverlapExternal:
1720 case Evoral::OverlapStart:
1721 case Evoral::OverlapEnd:
1722 /* adjust new location to cover existing one */
1723 loc->set_start (min (loc->start(), (*l)->start()));
1724 loc->set_end (max (loc->end(), (*l)->end()));
1725 /* we don't need this one any more */
1726 _locations->remove (*l);
1727 /* the location has been deleted, so remove reference to it in our local list */
1728 l = all_locations.erase (l);
1731 case Evoral::OverlapNone:
1739 Session::sync_locations_to_skips ()
1741 /* This happens asynchronously (in the audioengine thread). After the clear is done, we will call
1742 * Session::_sync_locations_to_skips() from the audioengine thread.
1744 clear_events (SessionEvent::Skip, boost::bind (&Session::_sync_locations_to_skips, this));
1748 Session::_sync_locations_to_skips ()
1750 /* called as a callback after existing Skip events have been cleared from a realtime audioengine thread */
1752 Locations::LocationList const & locs (_locations->list());
1754 for (Locations::LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1756 Location* location = *i;
1758 if (location->is_skip() && location->is_skipping()) {
1759 SessionEvent* ev = new SessionEvent (SessionEvent::Skip, SessionEvent::Add, location->start(), location->end(), 1.0);
1767 Session::location_added (Location *location)
1769 if (location->is_auto_punch()) {
1770 set_auto_punch_location (location);
1773 if (location->is_auto_loop()) {
1774 set_auto_loop_location (location);
1777 if (location->is_session_range()) {
1778 /* no need for any signal handling or event setting with the session range,
1779 because we keep a direct reference to it and use its start/end directly.
1781 _session_range_location = location;
1784 if (location->is_mark()) {
1785 /* listen for per-location signals that require us to do any * global updates for marks */
1787 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1788 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1789 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1790 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_marks, this, location));
1793 if (location->is_skip()) {
1794 /* listen for per-location signals that require us to update skip-locate events */
1796 location->StartChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1797 location->EndChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1798 location->Changed.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, true));
1799 location->FlagsChanged.connect_same_thread (skip_update_connections, boost::bind (&Session::update_skips, this, location, false));
1801 update_skips (location, true);
1808 Session::location_removed (Location *location)
1810 if (location->is_auto_loop()) {
1811 set_auto_loop_location (0);
1812 set_track_loop (false);
1815 if (location->is_auto_punch()) {
1816 set_auto_punch_location (0);
1819 if (location->is_session_range()) {
1820 /* this is never supposed to happen */
1821 error << _("programming error: session range removed!") << endl;
1824 if (location->is_skip()) {
1826 update_skips (location, false);
1833 Session::locations_changed ()
1835 _locations->apply (*this, &Session::_locations_changed);
1839 Session::_locations_changed (const Locations::LocationList& locations)
1841 /* There was some mass-change in the Locations object.
1843 We might be re-adding a location here but it doesn't actually matter
1844 for all the locations that the Session takes an interest in.
1848 PBD::Unwinder<bool> protect_ignore_skip_updates (_ignore_skips_updates, true);
1849 for (Locations::LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1850 location_added (*i);
1854 update_skips (NULL, false);
1858 Session::enable_record ()
1860 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1861 /* no recording at anything except normal speed */
1866 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1868 if (rs == Recording) {
1872 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1874 _last_record_location = _transport_frame;
1875 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1877 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1878 set_track_monitor_input_status (true);
1881 RecordStateChanged ();
1888 Session::set_all_tracks_record_enabled (bool enable )
1890 boost::shared_ptr<RouteList> rl = routes.reader();
1891 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1892 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1894 tr->set_record_enabled (enable, Controllable::NoGroup);
1901 Session::disable_record (bool rt_context, bool force)
1905 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1907 if (!Config->get_latched_record_enable () || force) {
1908 g_atomic_int_set (&_record_status, Disabled);
1909 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1911 if (rs == Recording) {
1912 g_atomic_int_set (&_record_status, Enabled);
1916 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1917 set_track_monitor_input_status (false);
1920 RecordStateChanged (); /* emit signal */
1923 remove_pending_capture_state ();
1929 Session::step_back_from_record ()
1931 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1933 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1934 set_track_monitor_input_status (false);
1937 RecordStateChanged (); /* emit signal */
1942 Session::maybe_enable_record ()
1944 if (_step_editors > 0) {
1948 g_atomic_int_set (&_record_status, Enabled);
1950 /* This function is currently called from somewhere other than an RT thread.
1951 This save_state() call therefore doesn't impact anything. Doing it here
1952 means that we save pending state of which sources the next record will use,
1953 which gives us some chance of recovering from a crash during the record.
1956 save_state ("", true);
1958 if (_transport_speed) {
1959 if (!config.get_punch_in()) {
1963 send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1964 RecordStateChanged (); /* EMIT SIGNAL */
1971 Session::audible_frame () const
1977 offset = worst_playback_latency ();
1979 if (synced_to_engine()) {
1980 /* Note: this is basically just sync-to-JACK */
1981 tf = _engine.transport_frame();
1983 tf = _transport_frame;
1988 if (!non_realtime_work_pending()) {
1992 /* Check to see if we have passed the first guaranteed
1993 audible frame past our last start position. if not,
1994 return that last start point because in terms
1995 of audible frames, we have not moved yet.
1997 `Start position' in this context means the time we last
1998 either started, located, or changed transport direction.
2001 if (_transport_speed > 0.0f) {
2003 if (!play_loop || !have_looped) {
2004 if (tf < _last_roll_or_reversal_location + offset) {
2005 return _last_roll_or_reversal_location;
2013 } else if (_transport_speed < 0.0f) {
2015 /* XXX wot? no backward looping? */
2017 if (tf > _last_roll_or_reversal_location - offset) {
2018 return _last_roll_or_reversal_location;
2030 Session::set_frame_rate (framecnt_t frames_per_second)
2032 /** \fn void Session::set_frame_size(framecnt_t)
2033 the AudioEngine object that calls this guarantees
2034 that it will not be called while we are also in
2035 ::process(). Its fine to do things that block
2039 if (_base_frame_rate == 0) {
2040 _base_frame_rate = frames_per_second;
2042 else if (_base_frame_rate != frames_per_second && frames_per_second != _nominal_frame_rate) {
2043 NotifyAboutSampleRateMismatch (_base_frame_rate, frames_per_second);
2045 _nominal_frame_rate = frames_per_second;
2050 reset_write_sources (false);
2052 // XXX we need some equivalent to this, somehow
2053 // SndFileSource::setup_standard_crossfades (frames_per_second);
2057 /* XXX need to reset/reinstantiate all LADSPA plugins */
2061 Session::set_block_size (pframes_t nframes)
2063 /* the AudioEngine guarantees
2064 that it will not be called while we are also in
2065 ::process(). It is therefore fine to do things that block
2070 current_block_size = nframes;
2074 boost::shared_ptr<RouteList> r = routes.reader ();
2076 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2077 (*i)->set_block_size (nframes);
2080 boost::shared_ptr<RouteList> rl = routes.reader ();
2081 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2082 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2084 tr->set_block_size (nframes);
2088 set_worst_io_latencies ();
2094 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
2096 boost::shared_ptr<Route> r2;
2098 if (r1->feeds (rbase) && rbase->feeds (r1)) {
2099 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
2103 /* make a copy of the existing list of routes that feed r1 */
2105 Route::FedBy existing (r1->fed_by());
2107 /* for each route that feeds r1, recurse, marking it as feeding
2111 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
2112 if (!(r2 = i->r.lock ())) {
2113 /* (*i) went away, ignore it */
2117 /* r2 is a route that feeds r1 which somehow feeds base. mark
2118 base as being fed by r2
2121 rbase->add_fed_by (r2, i->sends_only);
2125 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
2129 if (r1->feeds (r2) && r2->feeds (r1)) {
2133 /* now recurse, so that we can mark base as being fed by
2134 all routes that feed r2
2137 trace_terminal (r2, rbase);
2144 Session::resort_routes ()
2146 /* don't do anything here with signals emitted
2147 by Routes during initial setup or while we
2148 are being destroyed.
2151 if (_state_of_the_state & (InitialConnecting | Deletion)) {
2155 if (_route_deletion_in_progress) {
2160 RCUWriter<RouteList> writer (routes);
2161 boost::shared_ptr<RouteList> r = writer.get_copy ();
2162 resort_routes_using (r);
2163 /* writer goes out of scope and forces update */
2167 boost::shared_ptr<RouteList> rl = routes.reader ();
2168 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2169 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
2171 const Route::FedBy& fb ((*i)->fed_by());
2173 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
2174 boost::shared_ptr<Route> sf = f->r.lock();
2176 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
2184 /** This is called whenever we need to rebuild the graph of how we will process
2186 * @param r List of routes, in any order.
2190 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
2192 /* We are going to build a directed graph of our routes;
2193 this is where the edges of that graph are put.
2198 /* Go through all routes doing two things:
2200 * 1. Collect the edges of the route graph. Each of these edges
2201 * is a pair of routes, one of which directly feeds the other
2202 * either by a JACK connection or by an internal send.
2204 * 2. Begin the process of making routes aware of which other
2205 * routes directly or indirectly feed them. This information
2206 * is used by the solo code.
2209 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2211 /* Clear out the route's list of direct or indirect feeds */
2212 (*i)->clear_fed_by ();
2214 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
2216 bool via_sends_only;
2218 /* See if this *j feeds *i according to the current state of the JACK
2219 connections and internal sends.
2221 if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
2222 /* add the edge to the graph (part #1) */
2223 edges.add (*j, *i, via_sends_only);
2224 /* tell the route (for part #2) */
2225 (*i)->add_fed_by (*j, via_sends_only);
2230 /* Attempt a topological sort of the route graph */
2231 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
2233 if (sorted_routes) {
2234 /* We got a satisfactory topological sort, so there is no feedback;
2237 Note: the process graph rechain does not require a
2238 topologically-sorted list, but hey ho.
2240 if (_process_graph) {
2241 _process_graph->rechain (sorted_routes, edges);
2244 _current_route_graph = edges;
2246 /* Complete the building of the routes' lists of what directly
2247 or indirectly feeds them.
2249 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2250 trace_terminal (*i, *i);
2253 *r = *sorted_routes;
2256 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
2257 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2258 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
2259 (*i)->name(), (*i)->order_key ()));
2263 SuccessfulGraphSort (); /* EMIT SIGNAL */
2266 /* The topological sort failed, so we have a problem. Tell everyone
2267 and stick to the old graph; this will continue to be processed, so
2268 until the feedback is fixed, what is played back will not quite
2269 reflect what is actually connected. Note also that we do not
2270 do trace_terminal here, as it would fail due to an endless recursion,
2271 so the solo code will think that everything is still connected
2275 FeedbackDetected (); /* EMIT SIGNAL */
2280 /** Find a route name starting with \a base, maybe followed by the
2281 * lowest \a id. \a id will always be added if \a definitely_add_number
2282 * is true on entry; otherwise it will only be added if required
2283 * to make the name unique.
2285 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
2286 * The available route name with the lowest ID will be used, and \a id
2287 * will be set to the ID.
2289 * \return false if a route name could not be found, and \a track_name
2290 * and \a id do not reflect a free route name.
2293 Session::find_route_name (string const & base, uint32_t& id, string& name, bool definitely_add_number)
2295 /* the base may conflict with ports that do not belong to existing
2296 routes, but hidden objects like the click track. So check port names
2297 before anything else.
2300 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
2301 if (base == *reserved) {
2302 /* Check if this reserved name already exists, and if
2303 so, disallow it without a numeric suffix.
2305 if (route_by_name (*reserved)) {
2306 definitely_add_number = true;
2315 if (!definitely_add_number && route_by_name (base) == 0) {
2316 /* juse use the base */
2322 name = string_compose ("%1 %2", base, id);
2324 if (route_by_name (name) == 0) {
2330 } while (id < (UINT_MAX-1));
2335 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
2337 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
2339 in = ChanCount::ZERO;
2340 out = ChanCount::ZERO;
2342 boost::shared_ptr<RouteList> r = routes.reader ();
2344 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2345 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2346 if (tr && !tr->is_auditioner()) {
2347 in += tr->n_inputs();
2348 out += tr->n_outputs();
2354 Session::default_track_name_pattern (DataType t)
2357 case DataType::AUDIO:
2358 if (Profile->get_trx()) {
2365 case DataType::MIDI:
2372 /** Caller must not hold process lock
2373 * @param name_template string to use for the start of the name, or "" to use "MIDI".
2374 * @param instrument plugin info for the instrument to insert pre-fader, if any
2376 list<boost::shared_ptr<MidiTrack> >
2377 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument,
2378 TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
2381 uint32_t track_id = 0;
2383 RouteList new_routes;
2384 list<boost::shared_ptr<MidiTrack> > ret;
2386 const string name_pattern = default_track_name_pattern (DataType::MIDI);
2387 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2390 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, use_number)) {
2391 error << "cannot find name for new midi track" << endmsg;
2395 boost::shared_ptr<MidiTrack> track;
2398 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
2400 if (track->init ()) {
2404 if (Profile->get_mixbus ()) {
2405 track->set_strict_io (true);
2408 track->use_new_diskstream();
2410 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2411 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2414 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2415 if (track->input()->ensure_io (input, false, this)) {
2416 error << "cannot configure " << input << " out configuration for new midi track" << endmsg;
2420 if (track->output()->ensure_io (output, false, this)) {
2421 error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
2426 track->non_realtime_input_change();
2429 route_group->add (track);
2432 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2434 if (Config->get_remote_model() == UserOrdered) {
2435 track->set_remote_control_id (next_control_id());
2438 new_routes.push_back (track);
2439 ret.push_back (track);
2441 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2444 catch (failed_constructor &err) {
2445 error << _("Session: could not create new midi track.") << endmsg;
2449 catch (AudioEngine::PortRegistrationFailure& pfe) {
2451 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;
2459 if (!new_routes.empty()) {
2460 StateProtector sp (this);
2461 if (Profile->get_trx()) {
2462 add_routes (new_routes, false, false, false);
2464 add_routes (new_routes, true, true, false);
2468 for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
2469 PluginPtr plugin = instrument->load (*this);
2470 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2471 (*r)->add_processor (p, PreFader);
2481 Session::new_midi_route (RouteGroup* route_group, uint32_t how_many, string name_template, boost::shared_ptr<PluginInfo> instrument)
2484 uint32_t bus_id = 0;
2488 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi Bus");
2491 if (!find_route_name (name_template.empty () ? _("Midi Bus") : name_template, ++bus_id, bus_name, use_number)) {
2492 error << "cannot find name for new midi bus" << endmsg;
2497 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO)); // XXX Editor::add_routes is not ready for ARDOUR::DataType::MIDI
2503 if (Profile->get_mixbus ()) {
2504 bus->set_strict_io (true);
2507 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2508 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2511 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2513 if (bus->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2514 error << _("cannot configure new midi bus input") << endmsg;
2519 if (bus->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
2520 error << _("cannot configure new midi bus output") << endmsg;
2526 route_group->add (bus);
2528 if (Config->get_remote_model() == UserOrdered) {
2529 bus->set_remote_control_id (next_control_id());
2532 ret.push_back (bus);
2533 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2537 catch (failed_constructor &err) {
2538 error << _("Session: could not create new audio route.") << endmsg;
2542 catch (AudioEngine::PortRegistrationFailure& pfe) {
2543 error << pfe.what() << endmsg;
2553 StateProtector sp (this);
2554 add_routes (ret, false, false, false);
2557 for (RouteList::iterator r = ret.begin(); r != ret.end(); ++r) {
2558 PluginPtr plugin = instrument->load (*this);
2559 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
2560 (*r)->add_processor (p, PreFader);
2571 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
2573 boost::shared_ptr<Route> midi_track (wmt.lock());
2579 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
2581 if (change.after.n_audio() <= change.before.n_audio()) {
2585 /* new audio ports: make sure the audio goes somewhere useful,
2586 * unless the user has no-auto-connect selected.
2588 * The existing ChanCounts don't matter for this call as they are only
2589 * to do with matching input and output indices, and we are only changing
2592 auto_connect_route (midi_track, false, ChanCount(), change.before);
2596 #ifdef USE_TRACKS_CODE_FEATURES
2599 compare_routes_by_remote_id (const boost::shared_ptr<Route>& route1, const boost::shared_ptr<Route>& route2)
2601 return route1->remote_control_id() < route2->remote_control_id();
2605 Session::reconnect_existing_routes (bool withLock, bool reconnect_master, bool reconnect_inputs, bool reconnect_outputs)
2607 // it is not allowed to perform connection
2608 if (!IO::connecting_legal) {
2612 // if we are deleting routes we will call this once at the end
2613 if (_route_deletion_in_progress) {
2617 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
2623 // We need to disconnect the route's inputs and outputs first
2624 // basing on autoconnect configuration
2625 bool reconnectIputs = !(Config->get_input_auto_connect() & ManualConnect) && reconnect_inputs;
2626 bool reconnectOutputs = !(Config->get_output_auto_connect() & ManualConnect) && reconnect_outputs;
2628 ChanCount existing_inputs;
2629 ChanCount existing_outputs;
2630 count_existing_track_channels (existing_inputs, existing_outputs);
2632 //ChanCount inputs = ChanCount::ZERO;
2633 //ChanCount outputs = ChanCount::ZERO;
2635 RouteList existing_routes = *routes.reader ();
2636 existing_routes.sort (compare_routes_by_remote_id);
2639 PBD::Unwinder<bool> protect_ignore_changes (_reconnecting_routes_in_progress, true);
2641 vector<string> physinputs;
2642 vector<string> physoutputs;
2644 EngineStateController::instance()->get_physical_audio_outputs(physoutputs);
2645 EngineStateController::instance()->get_physical_audio_inputs(physinputs);
2647 uint32_t input_n = 0;
2648 uint32_t output_n = 0;
2649 RouteList::iterator rIter = existing_routes.begin();
2650 const AutoConnectOption current_input_auto_connection (Config->get_input_auto_connect());
2651 const AutoConnectOption current_output_auto_connection (Config->get_output_auto_connect());
2652 for (; rIter != existing_routes.end(); ++rIter) {
2653 if (*rIter == _master_out || *rIter == _monitor_out ) {
2657 if (current_output_auto_connection == AutoConnectPhysical) {
2658 (*rIter)->amp()->deactivate();
2659 } else if (current_output_auto_connection == AutoConnectMaster) {
2660 (*rIter)->amp()->activate();
2663 if (reconnectIputs) {
2664 (*rIter)->input()->disconnect (this); //GZ: check this; could be heavy
2666 for (uint32_t route_input_n = 0; route_input_n < (*rIter)->n_inputs().get(DataType::AUDIO); ++route_input_n) {
2668 if (current_input_auto_connection & AutoConnectPhysical) {
2670 if ( input_n == physinputs.size() ) {
2674 string port = physinputs[input_n];
2676 if (port.empty() ) {
2677 error << "Physical Input number "<< input_n << " is unavailable and cannot be connected" << endmsg;
2680 //GZ: check this; could be heavy
2681 (*rIter)->input()->connect ((*rIter)->input()->ports().port(DataType::AUDIO, route_input_n), port, this);
2687 if (reconnectOutputs) {
2689 //normalize route ouptuts: reduce the amount outputs to be equal to the amount of inputs
2690 if (current_output_auto_connection & AutoConnectPhysical) {
2692 //GZ: check this; could be heavy
2693 (*rIter)->output()->disconnect (this);
2694 size_t route_inputs_count = (*rIter)->n_inputs().get(DataType::AUDIO);
2696 //GZ: check this; could be heavy
2697 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, route_inputs_count), false, this );
2699 } else if (current_output_auto_connection & AutoConnectMaster){
2701 if (!reconnect_master) {
2705 //GZ: check this; could be heavy
2706 (*rIter)->output()->disconnect (this);
2709 uint32_t master_inputs_count = _master_out->n_inputs().get(DataType::AUDIO);
2710 (*rIter)->output()->ensure_io(ChanCount(DataType::AUDIO, master_inputs_count), false, this );
2712 error << error << "Master bus is not available" << endmsg;
2717 for (uint32_t route_output_n = 0; route_output_n < (*rIter)->n_outputs().get(DataType::AUDIO); ++route_output_n) {
2718 if (current_output_auto_connection & AutoConnectPhysical) {
2720 if ( output_n == physoutputs.size() ) {
2724 string port = physoutputs[output_n];
2726 if (port.empty() ) {
2727 error << "Physical Output number "<< output_n << " is unavailable and cannot be connected" << endmsg;
2730 //GZ: check this; could be heavy
2731 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2734 } else if (current_output_auto_connection & AutoConnectMaster) {
2736 if ( route_output_n == _master_out->n_inputs().get(DataType::AUDIO) ) {
2740 // connect to master bus
2741 string port = _master_out->input()->ports().port(DataType::AUDIO, route_output_n)->name();
2743 if (port.empty() ) {
2744 error << "MasterBus Input number "<< route_output_n << " is unavailable and cannot be connected" << endmsg;
2748 //GZ: check this; could be heavy
2749 (*rIter)->output()->connect ((*rIter)->output()->ports().port(DataType::AUDIO, route_output_n), port, this);
2756 _master_out->output()->disconnect (this);
2757 auto_connect_master_bus ();
2762 session_routes_reconnected (); /* EMIT SIGNAL */
2766 Session::reconnect_midi_scene_ports(bool inputs)
2770 boost::shared_ptr<MidiPort> scene_in_ptr = scene_in();
2772 scene_in_ptr->disconnect_all ();
2774 std::vector<EngineStateController::MidiPortState> midi_port_states;
2775 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2777 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2779 for (; state_iter != midi_port_states.end(); ++state_iter) {
2780 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2781 scene_in_ptr->connect (state_iter->name);
2788 boost::shared_ptr<MidiPort> scene_out_ptr = scene_out();
2790 if (scene_out_ptr ) {
2791 scene_out_ptr->disconnect_all ();
2793 std::vector<EngineStateController::MidiPortState> midi_port_states;
2794 EngineStateController::instance()->get_physical_midi_output_states (midi_port_states);
2796 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2798 for (; state_iter != midi_port_states.end(); ++state_iter) {
2799 if (state_iter->active && state_iter->available && state_iter->scene_connected) {
2800 scene_out_ptr->connect (state_iter->name);
2808 Session::reconnect_mtc_ports ()
2810 boost::shared_ptr<MidiPort> mtc_in_ptr = _midi_ports->mtc_input_port();
2816 mtc_in_ptr->disconnect_all ();
2818 std::vector<EngineStateController::MidiPortState> midi_port_states;
2819 EngineStateController::instance()->get_physical_midi_input_states (midi_port_states);
2821 std::vector<EngineStateController::MidiPortState>::iterator state_iter = midi_port_states.begin();
2823 for (; state_iter != midi_port_states.end(); ++state_iter) {
2824 if (state_iter->available && state_iter->mtc_in) {
2825 mtc_in_ptr->connect (state_iter->name);
2829 if (!_midi_ports->mtc_input_port ()->connected () &&
2830 config.get_external_sync () &&
2831 (Config->get_sync_source () == MTC) ) {
2832 config.set_external_sync (false);
2835 if ( ARDOUR::Profile->get_trx () ) {
2836 // Tracks need this signal to update timecode_source_dropdown
2837 MtcOrLtcInputPortChanged (); //emit signal
2842 Session::reconnect_mmc_ports(bool inputs)
2844 if (inputs ) { // get all enabled midi input ports
2846 boost::shared_ptr<MidiPort> mmc_in_ptr = _midi_ports->mmc_in();
2848 mmc_in_ptr->disconnect_all ();
2849 std::vector<std::string> enabled_midi_inputs;
2850 EngineStateController::instance()->get_physical_midi_inputs (enabled_midi_inputs);
2852 std::vector<std::string>::iterator port_iter = enabled_midi_inputs.begin();
2854 for (; port_iter != enabled_midi_inputs.end(); ++port_iter) {
2855 mmc_in_ptr->connect (*port_iter);
2859 } else { // get all enabled midi output ports
2861 boost::shared_ptr<MidiPort> mmc_out_ptr = _midi_ports->mmc_out();
2863 mmc_out_ptr->disconnect_all ();
2864 std::vector<std::string> enabled_midi_outputs;
2865 EngineStateController::instance()->get_physical_midi_outputs (enabled_midi_outputs);
2867 std::vector<std::string>::iterator port_iter = enabled_midi_outputs.begin();
2869 for (; port_iter != enabled_midi_outputs.end(); ++port_iter) {
2870 mmc_out_ptr->connect (*port_iter);
2878 /** Caller must not hold process lock
2879 * @param name_template string to use for the start of the name, or "" to use "Audio".
2881 list< boost::shared_ptr<AudioTrack> >
2882 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group,
2883 uint32_t how_many, string name_template)
2886 uint32_t track_id = 0;
2888 RouteList new_routes;
2889 list<boost::shared_ptr<AudioTrack> > ret;
2891 const string name_pattern = default_track_name_pattern (DataType::AUDIO);
2892 bool const use_number = (how_many != 1) || name_template.empty () || (name_template == name_pattern);
2896 if (!find_route_name (name_template.empty() ? _(name_pattern.c_str()) : name_template, ++track_id, track_name, use_number)) {
2897 error << "cannot find name for new audio track" << endmsg;
2901 boost::shared_ptr<AudioTrack> track;
2904 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2906 if (track->init ()) {
2910 if (Profile->get_mixbus ()) {
2911 track->set_strict_io (true);
2915 if (ARDOUR::Profile->get_trx ()) {
2916 // TRACKS considers it's not a USE CASE, it's
2917 // a piece of behavior of the session model:
2919 // Gain for a newly created route depends on
2920 // the current output_auto_connect mode:
2922 // 0 for Stereo Out mode
2924 if (Config->get_output_auto_connect() & AutoConnectMaster) {
2925 track->set_gain (dB_to_coefficient (0), Controllable::NoGroup);
2929 track->use_new_diskstream();
2931 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2932 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2935 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2937 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2938 error << string_compose (
2939 _("cannot configure %1 in/%2 out configuration for new audio track"),
2940 input_channels, output_channels)
2945 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2946 error << string_compose (
2947 _("cannot configure %1 in/%2 out configuration for new audio track"),
2948 input_channels, output_channels)
2955 route_group->add (track);
2958 track->non_realtime_input_change();
2960 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2961 if (Config->get_remote_model() == UserOrdered) {
2962 track->set_remote_control_id (next_control_id());
2965 new_routes.push_back (track);
2966 ret.push_back (track);
2968 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
2971 catch (failed_constructor &err) {
2972 error << _("Session: could not create new audio track.") << endmsg;
2976 catch (AudioEngine::PortRegistrationFailure& pfe) {
2978 error << pfe.what() << endmsg;
2986 if (!new_routes.empty()) {
2987 StateProtector sp (this);
2988 if (Profile->get_trx()) {
2989 add_routes (new_routes, false, false, false);
2991 add_routes (new_routes, true, true, false);
2998 /** Caller must not hold process lock.
2999 * @param name_template string to use for the start of the name, or "" to use "Bus".
3002 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
3005 uint32_t bus_id = 0;
3009 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
3012 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, use_number)) {
3013 error << "cannot find name for new audio bus" << endmsg;
3018 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
3024 if (Profile->get_mixbus ()) {
3025 bus->set_strict_io (true);
3028 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
3029 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
3032 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3034 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
3035 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3036 input_channels, output_channels)
3042 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
3043 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
3044 input_channels, output_channels)
3051 route_group->add (bus);
3053 if (Config->get_remote_model() == UserOrdered) {
3054 bus->set_remote_control_id (next_control_id());
3057 bus->add_internal_return ();
3059 ret.push_back (bus);
3061 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3067 catch (failed_constructor &err) {
3068 error << _("Session: could not create new audio route.") << endmsg;
3072 catch (AudioEngine::PortRegistrationFailure& pfe) {
3073 error << pfe.what() << endmsg;
3083 StateProtector sp (this);
3084 if (Profile->get_trx()) {
3085 add_routes (ret, false, false, false);
3087 add_routes (ret, false, true, true); // autoconnect // outputs only
3096 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base, PlaylistDisposition pd)
3100 if (!tree.read (template_path.c_str())) {
3104 return new_route_from_template (how_many, *tree.root(), name_base, pd);
3108 Session::new_route_from_template (uint32_t how_many, XMLNode& node, const std::string& name_base, PlaylistDisposition pd)
3111 uint32_t control_id;
3112 uint32_t number = 0;
3113 const uint32_t being_added = how_many;
3114 /* This will prevent the use of any existing XML-provided PBD::ID
3117 Stateful::ForceIDRegeneration force_ids;
3118 IO::disable_connecting ();
3120 control_id = next_control_id ();
3124 /* We're going to modify the node contents a bit so take a
3125 * copy. The node may be re-used when duplicating more than once.
3128 XMLNode node_copy (node);
3133 if (!name_base.empty()) {
3135 /* if we're adding more than one routes, force
3136 * all the names of the new routes to be
3137 * numbered, via the final parameter.
3140 if (!find_route_name (name_base.c_str(), ++number, name, (being_added > 1))) {
3141 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3147 string const route_name = node_copy.property(X_("name"))->value ();
3149 /* generate a new name by adding a number to the end of the template name */
3150 if (!find_route_name (route_name.c_str(), ++number, name, true)) {
3151 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
3152 abort(); /*NOTREACHED*/
3156 /* set this name in the XML description that we are about to use */
3158 bool rename_playlist;
3161 rename_playlist = true;
3165 rename_playlist = false;
3168 Route::set_name_in_state (node_copy, name, rename_playlist);
3170 /* trim bitslots from listen sends so that new ones are used */
3171 XMLNodeList children = node_copy.children ();
3172 for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
3173 if ((*i)->name() == X_("Processor")) {
3174 XMLProperty* role = (*i)->property (X_("role"));
3175 if (role && role->value() == X_("Listen")) {
3176 (*i)->remove_property (X_("bitslot"));
3181 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
3184 error << _("Session: cannot create track/bus from template description") << endmsg;
3188 if (boost::dynamic_pointer_cast<Track>(route)) {
3189 /* force input/output change signals so that the new diskstream
3190 picks up the configuration of the route. During session
3191 loading this normally happens in a different way.
3194 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3196 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
3197 change.after = route->input()->n_ports();
3198 route->input()->changed (change, this);
3199 change.after = route->output()->n_ports();
3200 route->output()->changed (change, this);
3203 route->set_remote_control_id (control_id);
3206 boost::shared_ptr<Track> track;
3208 if ((track = boost::dynamic_pointer_cast<Track> (route))) {
3211 track->use_new_playlist ();
3214 track->use_copy_playlist ();
3221 ret.push_back (route);
3223 RouteAddedOrRemoved (true); /* EMIT SIGNAL */
3226 catch (failed_constructor &err) {
3227 error << _("Session: could not create new route from template") << endmsg;
3231 catch (AudioEngine::PortRegistrationFailure& pfe) {
3232 error << pfe.what() << endmsg;
3241 StateProtector sp (this);
3242 if (Profile->get_trx()) {
3243 add_routes (ret, false, false, false);
3245 add_routes (ret, true, true, false);
3247 IO::enable_connecting ();
3254 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
3257 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
3258 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
3261 error << _("Adding new tracks/busses failed") << endmsg;
3266 update_latency (true);
3267 update_latency (false);
3272 save_state (_current_snapshot_name);
3275 reassign_track_numbers();
3277 update_route_record_state ();
3279 RouteAdded (new_routes); /* EMIT SIGNAL */
3283 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
3285 ChanCount existing_inputs;
3286 ChanCount existing_outputs;
3287 uint32_t order = next_control_id();
3290 if (_order_hint > -1) {
3291 order = _order_hint;
3295 count_existing_track_channels (existing_inputs, existing_outputs);
3298 RCUWriter<RouteList> writer (routes);
3299 boost::shared_ptr<RouteList> r = writer.get_copy ();
3300 r->insert (r->end(), new_routes.begin(), new_routes.end());
3302 /* if there is no control out and we're not in the middle of loading,
3303 * resort the graph here. if there is a control out, we will resort
3304 * toward the end of this method. if we are in the middle of loading,
3305 * we will resort when done.
3308 if (!_monitor_out && IO::connecting_legal) {
3309 resort_routes_using (r);
3313 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3315 boost::weak_ptr<Route> wpr (*x);
3316 boost::shared_ptr<Route> r (*x);
3318 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
3319 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
3320 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, wpr));
3321 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this));
3322 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
3323 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
3325 if (r->is_master()) {
3329 if (r->is_monitor()) {
3333 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
3335 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
3336 track_playlist_changed (boost::weak_ptr<Track> (tr));
3337 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_route_record_state, this));
3339 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
3341 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
3342 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
3346 if (input_auto_connect || output_auto_connect) {
3347 auto_connect_route (r, input_auto_connect, ChanCount (), ChanCount (), existing_inputs, existing_outputs);
3348 existing_inputs += r->n_inputs();
3349 existing_outputs += r->n_outputs();
3352 /* order keys are a GUI responsibility but we need to set up
3353 reasonable defaults because they also affect the remote control
3354 ID in most situations.
3357 if (!r->has_order_key ()) {
3358 if (r->is_auditioner()) {
3359 /* use an arbitrarily high value */
3360 r->set_order_key (UINT_MAX);
3362 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
3363 r->set_order_key (order);
3371 if (_monitor_out && IO::connecting_legal) {
3372 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
3374 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
3375 if ((*x)->is_monitor()) {
3377 } else if ((*x)->is_master()) {
3380 (*x)->enable_monitor_send ();
3387 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
3389 boost::shared_ptr<RouteList> r = routes.reader ();
3390 boost::shared_ptr<Send> s;
3392 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3393 if ((s = (*i)->internal_send_for (dest)) != 0) {
3394 s->amp()->gain_control()->set_value (GAIN_COEFF_ZERO, Controllable::NoGroup);
3400 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
3402 boost::shared_ptr<RouteList> r = routes.reader ();
3403 boost::shared_ptr<Send> s;
3405 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3406 if ((s = (*i)->internal_send_for (dest)) != 0) {
3407 s->amp()->gain_control()->set_value (GAIN_COEFF_UNITY, Controllable::NoGroup);
3413 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
3415 boost::shared_ptr<RouteList> r = routes.reader ();
3416 boost::shared_ptr<Send> s;
3418 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3419 if ((s = (*i)->internal_send_for (dest)) != 0) {
3420 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value(), Controllable::NoGroup);
3425 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
3427 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
3429 boost::shared_ptr<RouteList> r = routes.reader ();
3430 boost::shared_ptr<RouteList> t (new RouteList);
3432 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3433 /* no MIDI sends because there are no MIDI busses yet */
3434 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
3439 add_internal_sends (dest, p, t);
3443 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
3445 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
3446 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
3451 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
3453 add_internal_send (dest, sender->before_processor_for_index (index), sender);
3457 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
3459 if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
3463 if (!dest->internal_return()) {
3464 dest->add_internal_return ();
3467 sender->add_aux_send (dest, before);
3474 Session::remove_routes (boost::shared_ptr<RouteList> routes_to_remove)
3476 { // RCU Writer scope
3477 PBD::Unwinder<bool> uw_flag (_route_deletion_in_progress, true);
3478 RCUWriter<RouteList> writer (routes);
3479 boost::shared_ptr<RouteList> rs = writer.get_copy ();
3482 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3484 if (*iter == _master_out) {
3488 (*iter)->set_solo (false, Controllable::NoGroup);
3492 /* deleting the master out seems like a dumb
3493 idea, but its more of a UI policy issue
3497 if (*iter == _master_out) {
3498 _master_out = boost::shared_ptr<Route> ();
3501 if (*iter == _monitor_out) {
3502 _monitor_out.reset ();
3505 // We need to disconnect the route's inputs and outputs
3507 (*iter)->input()->disconnect (0);
3508 (*iter)->output()->disconnect (0);
3510 /* if the route had internal sends sending to it, remove them */
3511 if ((*iter)->internal_return()) {
3513 boost::shared_ptr<RouteList> r = routes.reader ();
3514 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3515 boost::shared_ptr<Send> s = (*i)->internal_send_for (*iter);
3517 (*i)->remove_processor (s);
3522 /* if the monitoring section had a pointer to this route, remove it */
3523 if (_monitor_out && !(*iter)->is_master() && !(*iter)->is_monitor()) {
3524 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3525 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
3526 (*iter)->remove_aux_or_listen (_monitor_out);
3529 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*iter);
3530 if (mt && mt->step_editing()) {
3531 if (_step_editors > 0) {
3537 /* writer goes out of scope, forces route list update */
3539 } // end of RCU Writer scope
3541 update_route_solo_state ();
3542 RouteAddedOrRemoved (false); /* EMIT SIGNAL */
3543 update_latency_compensation ();
3546 /* Re-sort routes to remove the graph's current references to the one that is
3547 * going away, then flush old references out of the graph.
3548 * Wave Tracks: reconnect routes
3551 #ifdef USE_TRACKS_CODE_FEATURES
3552 reconnect_existing_routes(true, false);
3554 routes.flush (); // maybe unsafe, see below.
3558 if (_process_graph) {
3559 _process_graph->clear_other_chain ();
3562 /* get rid of it from the dead wood collection in the route list manager */
3563 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
3567 /* try to cause everyone to drop their references
3568 * and unregister ports from the backend
3571 for (RouteList::iterator iter = routes_to_remove->begin(); iter != routes_to_remove->end(); ++iter) {
3572 (*iter)->drop_references ();
3575 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
3577 /* save the new state of the world */
3579 if (save_state (_current_snapshot_name)) {
3580 save_history (_current_snapshot_name);
3583 reassign_track_numbers();
3584 update_route_record_state ();
3588 Session::remove_route (boost::shared_ptr<Route> route)
3590 boost::shared_ptr<RouteList> rl (new RouteList);
3591 rl->push_back (route);
3596 Session::route_mute_changed ()
3602 Session::route_listen_changed (Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3604 boost::shared_ptr<Route> route = wpr.lock();
3606 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_listen_changed")) << endmsg;
3610 if (route->listening_via_monitor ()) {
3612 if (Config->get_exclusive_solo()) {
3614 RouteGroup* rg = route->route_group ();
3615 const bool group_already_accounted_for = route->use_group (group_override, &RouteGroup::is_solo);
3617 boost::shared_ptr<RouteList> r = routes.reader ();
3619 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3620 if ((*i) == route) {
3621 /* already changed */
3625 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3626 /* route does not get solo propagated to it */
3630 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3631 /* this route is a part of the same solo group as the route
3632 * that was changed. Changing that route did change or will
3633 * change all group members appropriately, so we can ignore it
3638 (*i)->set_listen (false, Controllable::NoGroup);
3644 } else if (_listen_cnt > 0) {
3649 update_route_solo_state ();
3652 Session::route_solo_isolated_changed (boost::weak_ptr<Route> wpr)
3654 boost::shared_ptr<Route> route = wpr.lock ();
3657 /* should not happen */
3658 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_isolated_changed")) << endmsg;
3662 bool send_changed = false;
3664 if (route->solo_isolated()) {
3665 if (_solo_isolated_cnt == 0) {
3666 send_changed = true;
3668 _solo_isolated_cnt++;
3669 } else if (_solo_isolated_cnt > 0) {
3670 _solo_isolated_cnt--;
3671 if (_solo_isolated_cnt == 0) {
3672 send_changed = true;
3677 IsolatedChanged (); /* EMIT SIGNAL */
3682 Session::route_solo_changed (bool self_solo_change, Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route> wpr)
3684 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
3686 if (!self_solo_change) {
3687 // session doesn't care about changes to soloed-by-others
3691 boost::shared_ptr<Route> route = wpr.lock ();
3694 boost::shared_ptr<RouteList> r = routes.reader ();
3697 if (route->self_soloed()) {
3703 /* the route may be a member of a group that has shared-solo
3704 * semantics. If so, then all members of that group should follow the
3705 * solo of the changed route. But ... this is optional, controlled by a
3706 * Controllable::GroupControlDisposition.
3708 * The first argument to the signal that this method is connected to is the
3709 * GroupControlDisposition value that was used to change solo.
3711 * If the solo change was done with group semantics (either InverseGroup
3712 * (force the entire group to change even if the group shared solo is
3713 * disabled) or UseGroup (use the group, which may or may not have the
3714 * shared solo property enabled)) then as we propagate the change to
3715 * the entire session we should IGNORE THE GROUP that the changed route
3719 RouteGroup* rg = route->route_group ();
3720 const bool group_already_accounted_for = (group_override == Controllable::ForGroup);
3722 if (delta == 1 && Config->get_exclusive_solo()) {
3724 /* new solo: disable all other solos, but not the group if its solo-enabled */
3726 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3728 if ((*i) == route) {
3729 /* already changed */
3733 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3734 /* route does not get solo propagated to it */
3738 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3739 /* this route is a part of the same solo group as the route
3740 * that was changed. Changing that route did change or will
3741 * change all group members appropriately, so we can ignore it
3747 (*i)->set_solo (false, group_override);
3751 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
3753 RouteList uninvolved;
3755 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
3757 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3758 bool via_sends_only;
3759 bool in_signal_flow;
3761 if ((*i) == route) {
3762 /* already changed */
3766 if ((*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3767 /* route does not get solo propagated to it */
3771 if ((group_already_accounted_for && (*i)->route_group() && (*i)->route_group() == rg)) {
3772 /* this route is a part of the same solo group as the route
3773 * that was changed. Changing that route did change or will
3774 * change all group members appropriately, so we can ignore it
3780 in_signal_flow = false;
3782 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
3784 if ((*i)->feeds (route, &via_sends_only)) {
3785 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
3786 if (!via_sends_only) {
3787 if (!route->soloed_by_others_upstream()) {
3788 (*i)->mod_solo_by_others_downstream (delta);
3790 DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others upstream\n");
3793 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
3795 in_signal_flow = true;
3797 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
3800 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
3802 if (route->feeds (*i, &via_sends_only)) {
3803 /* propagate solo upstream only if routing other than
3804 sends is involved, but do consider the other route
3805 (*i) to be part of the signal flow even if only
3808 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
3812 route->soloed_by_others_downstream(),
3813 route->soloed_by_others_upstream()));
3814 if (!via_sends_only) {
3815 //NB. Triggers Invert Push, which handles soloed by downstream
3816 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
3817 (*i)->mod_solo_by_others_upstream (delta);
3819 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
3821 in_signal_flow = true;
3823 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
3826 if (!in_signal_flow) {
3827 uninvolved.push_back (*i);
3831 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
3833 update_route_solo_state (r);
3835 /* now notify that the mute state of the routes not involved in the signal
3836 pathway of the just-solo-changed route may have altered.
3839 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
3840 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
3841 (*i)->act_on_mute ();
3842 (*i)->mute_changed ();
3845 SoloChanged (); /* EMIT SIGNAL */
3850 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
3852 /* now figure out if anything that matters is soloed (or is "listening")*/
3854 bool something_soloed = false;
3855 bool something_listening = false;
3856 uint32_t listeners = 0;
3857 uint32_t isolated = 0;
3860 r = routes.reader();
3863 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3864 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
3865 something_soloed = true;
3868 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
3869 if (Config->get_solo_control_is_listen_control()) {
3871 something_listening = true;
3873 (*i)->set_listen (false, Controllable::NoGroup);
3877 if ((*i)->solo_isolated()) {
3882 if (something_soloed != _non_soloed_outs_muted) {
3883 _non_soloed_outs_muted = something_soloed;
3884 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
3887 if (something_listening != _listening) {
3888 _listening = something_listening;
3889 SoloActive (_listening);
3892 _listen_cnt = listeners;
3894 if (isolated != _solo_isolated_cnt) {
3895 _solo_isolated_cnt = isolated;
3896 IsolatedChanged (); /* EMIT SIGNAL */
3899 DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
3900 something_soloed, listeners, isolated));
3903 boost::shared_ptr<RouteList>
3904 Session::get_routes_with_internal_returns() const
3906 boost::shared_ptr<RouteList> r = routes.reader ();
3907 boost::shared_ptr<RouteList> rl (new RouteList);
3909 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3910 if ((*i)->internal_return ()) {
3918 Session::io_name_is_legal (const std::string& name)
3920 boost::shared_ptr<RouteList> r = routes.reader ();
3922 for (vector<string>::const_iterator reserved = reserved_io_names.begin(); reserved != reserved_io_names.end(); ++reserved) {
3923 if (name == *reserved) {
3924 if (!route_by_name (*reserved)) {
3925 /* first instance of a reserved name is allowed */
3928 /* all other instances of a reserved name are not allowed */
3933 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3934 if ((*i)->name() == name) {
3938 if ((*i)->has_io_processor_named (name)) {
3947 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
3950 vector<string> connections;
3952 /* if we are passed only a single route and we're not told to turn
3953 * others off, then just do the simple thing.
3956 if (flip_others == false && rl->size() == 1) {
3957 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
3959 mt->set_input_active (onoff);
3964 for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
3966 PortSet& ps ((*rt)->input()->ports());
3968 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
3969 p->get_connections (connections);
3972 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
3973 routes_using_input_from (*s, rl2);
3976 /* scan all relevant routes to see if others are on or off */
3978 bool others_are_already_on = false;
3980 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
3982 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
3988 if ((*r) != (*rt)) {
3989 if (mt->input_active()) {
3990 others_are_already_on = true;
3993 /* this one needs changing */
3994 mt->set_input_active (onoff);
4000 /* globally reverse other routes */
4002 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
4003 if ((*r) != (*rt)) {
4004 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
4006 mt->set_input_active (!others_are_already_on);
4015 Session::routes_using_input_from (const string& str, RouteList& rl)
4017 boost::shared_ptr<RouteList> r = routes.reader();
4019 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4020 if ((*i)->input()->connected_to (str)) {
4026 boost::shared_ptr<Route>
4027 Session::route_by_name (string name)
4029 boost::shared_ptr<RouteList> r = routes.reader ();
4031 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4032 if ((*i)->name() == name) {
4037 return boost::shared_ptr<Route> ((Route*) 0);
4040 boost::shared_ptr<Route>
4041 Session::route_by_id (PBD::ID id)
4043 boost::shared_ptr<RouteList> r = routes.reader ();
4045 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4046 if ((*i)->id() == id) {
4051 return boost::shared_ptr<Route> ((Route*) 0);
4054 boost::shared_ptr<Processor>
4055 Session::processor_by_id (PBD::ID id) const
4057 boost::shared_ptr<RouteList> r = routes.reader ();
4059 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4060 boost::shared_ptr<Processor> p = (*i)->Route::processor_by_id (id);
4066 return boost::shared_ptr<Processor> ();
4069 boost::shared_ptr<Track>
4070 Session::track_by_diskstream_id (PBD::ID id)
4072 boost::shared_ptr<RouteList> r = routes.reader ();
4074 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4075 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4076 if (t && t->using_diskstream_id (id)) {
4081 return boost::shared_ptr<Track> ();
4084 boost::shared_ptr<Route>
4085 Session::route_by_remote_id (uint32_t id)
4087 boost::shared_ptr<RouteList> r = routes.reader ();
4089 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4090 if ((*i)->remote_control_id() == id) {
4095 return boost::shared_ptr<Route> ((Route*) 0);
4099 boost::shared_ptr<Route>
4100 Session::route_by_selected_count (uint32_t id)
4102 boost::shared_ptr<RouteList> r = routes.reader ();
4104 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4105 /* NOT IMPLEMENTED */
4108 return boost::shared_ptr<Route> ((Route*) 0);
4113 Session::reassign_track_numbers ()
4117 RouteList r (*(routes.reader ()));
4118 SignalOrderRouteSorter sorter;
4121 StateProtector sp (this);
4123 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4124 if (boost::dynamic_pointer_cast<Track> (*i)) {
4125 (*i)->set_track_number(++tn);
4127 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
4128 (*i)->set_track_number(--bn);
4131 const uint32_t decimals = ceilf (log10f (tn + 1));
4132 const bool decimals_changed = _track_number_decimals != decimals;
4133 _track_number_decimals = decimals;
4135 if (decimals_changed && config.get_track_name_number ()) {
4136 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
4137 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
4139 t->resync_track_name();
4142 // trigger GUI re-layout
4143 config.ParameterChanged("track-name-number");
4148 Session::playlist_region_added (boost::weak_ptr<Region> w)
4150 boost::shared_ptr<Region> r = w.lock ();
4155 /* These are the operations that are currently in progress... */
4156 list<GQuark> curr = _current_trans_quarks;
4159 /* ...and these are the operations during which we want to update
4160 the session range location markers.
4163 ops.push_back (Operations::capture);
4164 ops.push_back (Operations::paste);
4165 ops.push_back (Operations::duplicate_region);
4166 ops.push_back (Operations::insert_file);
4167 ops.push_back (Operations::insert_region);
4168 ops.push_back (Operations::drag_region_brush);
4169 ops.push_back (Operations::region_drag);
4170 ops.push_back (Operations::selection_grab);
4171 ops.push_back (Operations::region_fill);
4172 ops.push_back (Operations::fill_selection);
4173 ops.push_back (Operations::create_region);
4174 ops.push_back (Operations::region_copy);
4175 ops.push_back (Operations::fixed_time_region_copy);
4178 /* See if any of the current operations match the ones that we want */
4180 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
4182 /* If so, update the session range markers */
4184 maybe_update_session_range (r->position (), r->last_frame ());
4188 /** Update the session range markers if a is before the current start or
4189 * b is after the current end.
4192 Session::maybe_update_session_range (framepos_t a, framepos_t b)
4194 if (_state_of_the_state & Loading) {
4198 framepos_t session_end_marker_shift_samples = session_end_shift * _nominal_frame_rate;
4200 if (_session_range_location == 0) {
4202 set_session_range_location (a, b + session_end_marker_shift_samples);
4206 if (a < _session_range_location->start()) {
4207 _session_range_location->set_start (a);
4210 if (b > _session_range_location->end()) {
4211 _session_range_location->set_end (b);
4217 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
4219 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4220 maybe_update_session_range (i->to, i->to + i->length);
4225 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
4227 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
4228 maybe_update_session_range (i->from, i->to);
4232 /* Region management */
4234 boost::shared_ptr<Region>
4235 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
4237 const RegionFactory::RegionMap& regions (RegionFactory::regions());
4238 RegionFactory::RegionMap::const_iterator i;
4239 boost::shared_ptr<Region> region;
4241 Glib::Threads::Mutex::Lock lm (region_lock);
4243 for (i = regions.begin(); i != regions.end(); ++i) {
4247 if (region->whole_file()) {
4249 if (child->source_equivalent (region)) {
4255 return boost::shared_ptr<Region> ();
4259 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
4261 set<boost::shared_ptr<Region> > relevant_regions;
4263 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
4264 RegionFactory::get_regions_using_source (*s, relevant_regions);
4267 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
4268 set<boost::shared_ptr<Region> >::iterator tmp;
4273 playlists->destroy_region (*r);
4274 RegionFactory::map_remove (*r);
4276 (*r)->drop_sources ();
4277 (*r)->drop_references ();
4279 relevant_regions.erase (r);
4284 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
4287 Glib::Threads::Mutex::Lock ls (source_lock);
4288 /* remove from the main source list */
4289 sources.erase ((*s)->id());
4292 (*s)->mark_for_remove ();
4293 (*s)->drop_references ();
4302 Session::remove_last_capture ()
4304 list<boost::shared_ptr<Source> > srcs;
4306 boost::shared_ptr<RouteList> rl = routes.reader ();
4307 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4308 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4313 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
4316 srcs.insert (srcs.end(), l.begin(), l.end());
4321 destroy_sources (srcs);
4323 save_state (_current_snapshot_name);
4328 /* Source Management */
4331 Session::add_source (boost::shared_ptr<Source> source)
4333 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
4334 pair<SourceMap::iterator,bool> result;
4336 entry.first = source->id();
4337 entry.second = source;
4340 Glib::Threads::Mutex::Lock lm (source_lock);
4341 result = sources.insert (entry);
4344 if (result.second) {
4346 /* yay, new source */
4348 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
4351 if (!fs->within_session()) {
4352 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
4358 boost::shared_ptr<AudioFileSource> afs;
4360 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
4361 if (Config->get_auto_analyse_audio()) {
4362 Analyser::queue_source_for_analysis (source, false);
4366 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
4371 Session::remove_source (boost::weak_ptr<Source> src)
4373 if (_state_of_the_state & Deletion) {
4377 SourceMap::iterator i;
4378 boost::shared_ptr<Source> source = src.lock();
4385 Glib::Threads::Mutex::Lock lm (source_lock);
4387 if ((i = sources.find (source->id())) != sources.end()) {
4392 if (!(_state_of_the_state & StateOfTheState (InCleanup|Loading))) {
4394 /* save state so we don't end up with a session file
4395 referring to non-existent sources.
4398 save_state (_current_snapshot_name);
4402 boost::shared_ptr<Source>
4403 Session::source_by_id (const PBD::ID& id)
4405 Glib::Threads::Mutex::Lock lm (source_lock);
4406 SourceMap::iterator i;
4407 boost::shared_ptr<Source> source;
4409 if ((i = sources.find (id)) != sources.end()) {
4416 boost::shared_ptr<AudioFileSource>
4417 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
4419 /* Restricted to audio files because only audio sources have channel
4423 Glib::Threads::Mutex::Lock lm (source_lock);
4425 for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
4426 boost::shared_ptr<AudioFileSource> afs
4427 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
4429 if (afs && afs->path() == path && chn == afs->channel()) {
4434 return boost::shared_ptr<AudioFileSource>();
4437 boost::shared_ptr<MidiSource>
4438 Session::midi_source_by_path (const std::string& path) const
4440 /* Restricted to MIDI files because audio sources require a channel
4441 for unique identification, in addition to a path.
4444 Glib::Threads::Mutex::Lock lm (source_lock);
4446 for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
4447 boost::shared_ptr<MidiSource> ms
4448 = boost::dynamic_pointer_cast<MidiSource>(s->second);
4449 boost::shared_ptr<FileSource> fs
4450 = boost::dynamic_pointer_cast<FileSource>(s->second);
4452 if (ms && fs && fs->path() == path) {
4457 return boost::shared_ptr<MidiSource>();
4461 Session::count_sources_by_origin (const string& path)
4464 Glib::Threads::Mutex::Lock lm (source_lock);
4466 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
4467 boost::shared_ptr<FileSource> fs
4468 = boost::dynamic_pointer_cast<FileSource>(i->second);
4470 if (fs && fs->origin() == path) {
4479 peak_file_helper (const string& peak_path, const string& file_path, const string& file_base, bool hash) {
4481 std::string checksum = Glib::Checksum::compute_checksum(Glib::Checksum::CHECKSUM_SHA1, file_path + G_DIR_SEPARATOR + file_base);
4482 return Glib::build_filename (peak_path, checksum + peakfile_suffix);
4484 return Glib::build_filename (peak_path, file_base + peakfile_suffix);
4489 Session::construct_peak_filepath (const string& filepath, const bool in_session, const bool old_peak_name) const
4491 string interchange_dir_string = string (interchange_dir_name) + G_DIR_SEPARATOR;
4493 if (Glib::path_is_absolute (filepath)) {
4495 /* rip the session dir from the audiofile source */
4497 string session_path;
4498 bool in_another_session = true;
4500 if (filepath.find (interchange_dir_string) != string::npos) {
4502 session_path = Glib::path_get_dirname (filepath); /* now ends in audiofiles */
4503 session_path = Glib::path_get_dirname (session_path); /* now ends in session name */
4504 session_path = Glib::path_get_dirname (session_path); /* now ends in interchange */
4505 session_path = Glib::path_get_dirname (session_path); /* now has session path */
4507 /* see if it is within our session */
4509 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4510 if (i->path == session_path) {
4511 in_another_session = false;
4516 in_another_session = false;
4520 if (in_another_session) {
4521 SessionDirectory sd (session_path);
4522 return peak_file_helper (sd.peak_path(), "", Glib::path_get_basename (filepath), !old_peak_name);
4526 /* 1) if file belongs to this session
4527 * it may be a relative path (interchange/...)
4528 * or just basename (session_state, remove source)
4529 * -> just use the basename
4531 std::string filename = Glib::path_get_basename (filepath);
4534 /* 2) if the file is outside our session dir:
4535 * (imported but not copied) add the path for check-summming */
4537 path = Glib::path_get_dirname (filepath);
4540 return peak_file_helper (_session_dir->peak_path(), path, Glib::path_get_basename (filepath), !old_peak_name);
4544 Session::new_audio_source_path_for_embedded (const std::string& path)
4548 * we know that the filename is already unique because it exists
4549 * out in the filesystem.
4551 * However, when we bring it into the session, we could get a
4554 * Eg. two embedded files:
4559 * When merged into session, these collide.
4561 * There will not be a conflict with in-memory sources
4562 * because when the source was created we already picked
4563 * a unique name for it.
4565 * This collision is not likely to be common, but we have to guard
4566 * against it. So, if there is a collision, take the md5 hash of the
4567 * the path, and use that as the filename instead.
4570 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4571 string base = Glib::path_get_basename (path);
4572 string newpath = Glib::build_filename (sdir.sound_path(), base);
4574 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4578 md5.digestString (path.c_str());
4579 md5.writeToString ();
4580 base = md5.digestChars;
4582 string ext = get_suffix (path);
4589 newpath = Glib::build_filename (sdir.sound_path(), base);
4591 /* if this collides, we're screwed */
4593 if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
4594 error << string_compose (_("Merging embedded file %1: name collision AND md5 hash collision!"), path) << endmsg;
4603 /** Return true if there are no audio file sources that use @param name as
4604 * the filename component of their path.
4606 * Return false otherwise.
4608 * This method MUST ONLY be used to check in-session, mono files since it
4609 * hard-codes the channel of the audio file source we are looking for as zero.
4611 * If/when Ardour supports native files in non-mono formats, the logic here
4612 * will need to be revisited.
4615 Session::audio_source_name_is_unique (const string& name)
4617 std::vector<string> sdirs = source_search_path (DataType::AUDIO);
4618 vector<space_and_path>::iterator i;
4619 uint32_t existing = 0;
4621 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4623 /* note that we search *without* the extension so that
4624 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
4625 in the event that this new name is required for
4626 a file format change.
4629 const string spath = *i;
4631 if (matching_unsuffixed_filename_exists_in (spath, name)) {
4636 /* it is possible that we have the path already
4637 * assigned to a source that has not yet been written
4638 * (ie. the write source for a diskstream). we have to
4639 * check this in order to make sure that our candidate
4640 * path isn't used again, because that can lead to
4641 * two Sources point to the same file with different
4642 * notions of their removability.
4646 string possible_path = Glib::build_filename (spath, name);
4648 if (audio_source_by_path_and_channel (possible_path, 0)) {
4654 return (existing == 0);
4658 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)
4661 const string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
4663 if (Profile->get_trx() && destructive) {
4665 sstr << setfill ('0') << setw (4) << cnt;
4666 sstr << legalized_base;
4668 sstr << legalized_base;
4670 if (take_required || related_exists) {
4682 } else if (nchan > 2) {
4687 /* XXX what? more than 26 channels! */
4698 /** Return a unique name based on \a base for a new internal audio source */
4700 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
4703 string possible_name;
4704 const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
4706 bool some_related_source_name_exists = false;
4708 legalized = legalize_for_path (base);
4710 // Find a "version" of the base name that doesn't exist in any of the possible directories.
4712 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
4714 possible_name = format_audio_source_name (legalized, nchan, chan, destructive, take_required, cnt, some_related_source_name_exists);
4716 if (audio_source_name_is_unique (possible_name)) {
4720 some_related_source_name_exists = true;
4723 error << string_compose(
4724 _("There are already %1 recordings for %2, which I consider too many."),
4725 limit, base) << endmsg;
4727 throw failed_constructor();
4731 /* We've established that the new name does not exist in any session
4732 * directory, so now find out which one we should use for this new
4736 SessionDirectory sdir (get_best_session_directory_for_new_audio());
4738 std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
4743 /** Return a unique name based on `base` for a new internal MIDI source */
4745 Session::new_midi_source_path (const string& base)
4748 char buf[PATH_MAX+1];
4749 const uint32_t limit = 10000;
4751 string possible_path;
4752 string possible_name;
4755 legalized = legalize_for_path (base);
4757 // Find a "version" of the file name that doesn't exist in any of the possible directories.
4758 std::vector<string> sdirs = source_search_path(DataType::MIDI);
4760 /* - the main session folder is the first in the vector.
4761 * - after checking all locations for file-name uniqueness,
4762 * we keep the one from the last iteration as new file name
4763 * - midi files are small and should just be kept in the main session-folder
4765 * -> reverse the array, check main session folder last and use that as location
4768 std::reverse(sdirs.begin(), sdirs.end());
4770 for (cnt = 1; cnt <= limit; ++cnt) {
4772 vector<space_and_path>::iterator i;
4773 uint32_t existing = 0;
4775 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
4777 snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
4778 possible_name = buf;
4780 possible_path = Glib::build_filename (*i, possible_name);
4782 if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
4786 if (midi_source_by_path (possible_path)) {
4791 if (existing == 0) {
4796 error << string_compose(
4797 _("There are already %1 recordings for %2, which I consider too many."),
4798 limit, base) << endmsg;
4804 /* No need to "find best location" for software/app-based RAID, because
4805 MIDI is so small that we always put it in the same place.
4808 return possible_path;
4812 /** Create a new within-session audio source */
4813 boost::shared_ptr<AudioFileSource>
4814 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
4816 const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
4818 if (!path.empty()) {
4819 return boost::dynamic_pointer_cast<AudioFileSource> (
4820 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate(), true, true));
4822 throw failed_constructor ();
4826 /** Create a new within-session MIDI source */
4827 boost::shared_ptr<MidiSource>
4828 Session::create_midi_source_for_session (string const & basic_name)
4830 const string path = new_midi_source_path (basic_name);
4832 if (!path.empty()) {
4833 return boost::dynamic_pointer_cast<SMFSource> (
4834 SourceFactory::createWritable (
4835 DataType::MIDI, *this, path, false, frame_rate()));
4837 throw failed_constructor ();
4841 /** Create a new within-session MIDI source */
4842 boost::shared_ptr<MidiSource>
4843 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
4845 /* the caller passes in the track the source will be used in,
4846 so that we can keep the numbering sane.
4848 Rationale: a track with the name "Foo" that has had N
4849 captures carried out so far will ALREADY have a write source
4850 named "Foo-N+1.mid" waiting to be used for the next capture.
4852 If we call new_midi_source_name() we will get "Foo-N+2". But
4853 there is no region corresponding to "Foo-N+1", so when
4854 "Foo-N+2" appears in the track, the gap presents the user
4855 with odd behaviour - why did it skip past Foo-N+1?
4857 We could explain this to the user in some odd way, but
4858 instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
4861 If that attempted rename fails, we get "Foo-N+2.mid" anyway.
4864 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
4866 std::string name = track->steal_write_source_name ();
4869 return boost::shared_ptr<MidiSource>();
4872 /* MIDI files are small, just put them in the first location of the
4873 session source search path.
4876 const string path = Glib::build_filename (source_search_path (DataType::MIDI).front(), name);
4878 return boost::dynamic_pointer_cast<SMFSource> (
4879 SourceFactory::createWritable (
4880 DataType::MIDI, *this, path, false, frame_rate()));
4885 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
4887 if (playlist->hidden()) {
4891 playlists->add (playlist);
4894 playlist->release();
4901 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
4903 if (_state_of_the_state & Deletion) {
4907 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
4913 playlists->remove (playlist);
4919 Session::set_audition (boost::shared_ptr<Region> r)
4921 pending_audition_region = r;
4922 add_post_transport_work (PostTransportAudition);
4923 _butler->schedule_transport_work ();
4927 Session::audition_playlist ()
4929 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
4930 ev->region.reset ();
4936 Session::register_lua_function (
4937 const std::string& name,
4938 const std::string& script,
4939 const LuaScriptParamList& args
4942 Glib::Threads::Mutex::Lock lm (lua_lock);
4944 lua_State* L = lua.getState();
4946 const std::string& bytecode = LuaScripting::get_factory_bytecode (script);
4947 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
4948 for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
4949 if ((*i)->optional && !(*i)->is_set) { continue; }
4950 tbl_arg[(*i)->name] = (*i)->value;
4952 (*_lua_add)(name, bytecode, tbl_arg); // throws luabridge::LuaException
4957 Session::unregister_lua_function (const std::string& name)
4959 Glib::Threads::Mutex::Lock lm (lua_lock);
4960 (*_lua_del)(name); // throws luabridge::LuaException
4961 lua.collect_garbage ();
4965 std::vector<std::string>
4966 Session::registered_lua_functions ()
4968 Glib::Threads::Mutex::Lock lm (lua_lock);
4969 std::vector<std::string> rv;
4972 luabridge::LuaRef list ((*_lua_list)());
4973 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
4974 if (!i.key ().isString ()) { assert(0); continue; }
4975 rv.push_back (i.key ().cast<std::string> ());
4977 } catch (luabridge::LuaException const& e) { }
4982 static void _lua_print (std::string s) {
4983 std::cout << "SessionLua: " << s << "\n";
4988 Session::try_run_lua (pframes_t nframes)
4990 if (_n_lua_scripts == 0) return;
4991 Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
4993 try { (*_lua_run)(nframes); } catch (luabridge::LuaException const& e) { }
4998 Session::setup_lua ()
5001 lua.Print.connect (&_lua_print);
5004 "function ArdourSession ()"
5005 " local self = { scripts = {}, instances = {} }"
5007 " local remove = function (n)"
5008 " self.scripts[n] = nil"
5009 " self.instances[n] = nil"
5010 " Session:scripts_changed()" // call back
5013 " local addinternal = function (n, f, a)"
5014 " assert(type(n) == 'string', 'function-name must be string')"
5015 " assert(type(f) == 'function', 'Given script is a not a function')"
5016 " assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
5017 " assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
5018 " self.scripts[n] = { ['f'] = f, ['a'] = a }"
5019 " local env = _ENV; env.f = nil env.io = nil env.os = nil env.loadfile = nil env.require = nil env.dofile = nil env.package = nil env.debug = nil"
5020 " local env = { print = print, Session = Session, tostring = tostring, assert = assert, ipairs = ipairs, error = error, select = select, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall }"
5021 " self.instances[n] = load (string.dump(f, true), nil, nil, env)(a)"
5022 " Session:scripts_changed()" // call back
5025 " local add = function (n, b, a)"
5026 " assert(type(b) == 'string', 'ByteCode must be string')"
5027 " load (b)()" // assigns f
5028 " assert(type(f) == 'string', 'Assigned ByteCode must be string')"
5029 " addinternal (n, load(f), a)"
5032 " local run = function (...)"
5033 " for n, s in pairs (self.instances) do"
5034 " local status, err = pcall (s, ...)"
5035 " if not status then"
5036 " print ('fn \"'.. n .. '\": ', err)"
5043 " local cleanup = function ()"
5044 " self.scripts = nil"
5045 " self.instances = nil"
5048 " local list = function ()"
5050 " for n, _ in pairs (self.scripts) do"
5056 " local function basic_serialize (o)"
5057 " if type(o) == \"number\" then"
5058 " return tostring(o)"
5060 " return string.format(\"%q\", o)"
5064 " local function serialize (name, value)"
5065 " local rv = name .. ' = '"
5067 " if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
5068 " return rv .. basic_serialize(value) .. ' '"
5069 " elseif type(value) == \"table\" then"
5071 " for k,v in pairs(value) do"
5072 " local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
5073 " rv = rv .. serialize(fieldname, v) .. ' '"
5074 " collectgarbage()" // string concatenation allocates a new string :(
5077 " elseif type(value) == \"function\" then"
5078 " return rv .. string.format(\"%q\", string.dump(value, true))"
5080 " error('cannot save a ' .. type(value))"
5085 " local save = function ()"
5086 " return (serialize('scripts', self.scripts))"
5089 " local restore = function (state)"
5090 " self.scripts = {}"
5092 " for n, s in pairs (scripts) do"
5093 " addinternal (n, load(s['f']), s['a'])"
5097 " return { run = run, add = add, remove = remove,"
5098 " list = list, restore = restore, save = save, cleanup = cleanup}"
5101 " sess = ArdourSession ()"
5102 " ArdourSession = nil"
5104 "function ardour () end"
5107 lua_State* L = lua.getState();
5110 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
5111 lua.do_command ("sess = nil"); // hide it.
5112 lua.do_command ("collectgarbage()");
5114 _lua_run = new luabridge::LuaRef(lua_sess["run"]);
5115 _lua_add = new luabridge::LuaRef(lua_sess["add"]);
5116 _lua_del = new luabridge::LuaRef(lua_sess["remove"]);
5117 _lua_list = new luabridge::LuaRef(lua_sess["list"]);
5118 _lua_save = new luabridge::LuaRef(lua_sess["save"]);
5119 _lua_load = new luabridge::LuaRef(lua_sess["restore"]);
5120 _lua_cleanup = new luabridge::LuaRef(lua_sess["cleanup"]);
5121 } catch (luabridge::LuaException const& e) {
5122 fatal << string_compose (_("programming error: %1"),
5123 X_("Failed to setup Lua interpreter"))
5125 abort(); /*NOTREACHED*/
5128 LuaBindings::stddef (L);
5129 LuaBindings::common (L);
5130 LuaBindings::dsp (L);
5131 luabridge::push <Session *> (L, this);
5132 lua_setglobal (L, "Session");
5136 Session::scripts_changed ()
5138 assert (!lua_lock.trylock()); // must hold lua_lock
5141 luabridge::LuaRef list ((*_lua_list)());
5143 for (luabridge::Iterator i (list); !i.isNil (); ++i) {
5144 if (!i.key ().isString ()) { assert(0); continue; }
5147 _n_lua_scripts = cnt;
5148 } catch (luabridge::LuaException const& e) {
5149 fatal << string_compose (_("programming error: %1"),
5150 X_("Indexing Lua Session Scripts failed."))
5152 abort(); /*NOTREACHED*/
5157 Session::non_realtime_set_audition ()
5159 assert (pending_audition_region);
5160 auditioner->audition_region (pending_audition_region);
5161 pending_audition_region.reset ();
5162 AuditionActive (true); /* EMIT SIGNAL */
5166 Session::audition_region (boost::shared_ptr<Region> r)
5168 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
5174 Session::cancel_audition ()
5179 if (auditioner->auditioning()) {
5180 auditioner->cancel_audition ();
5181 AuditionActive (false); /* EMIT SIGNAL */
5186 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
5188 if (a->is_monitor()) {
5191 if (b->is_monitor()) {
5194 return a->order_key () < b->order_key ();
5198 Session::is_auditioning () const
5200 /* can be called before we have an auditioner object */
5202 return auditioner->auditioning();
5209 Session::graph_reordered ()
5211 /* don't do this stuff if we are setting up connections
5212 from a set_state() call or creating new tracks. Ditto for deletion.
5215 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress || _reconnecting_routes_in_progress || _route_deletion_in_progress) {
5219 /* every track/bus asked for this to be handled but it was deferred because
5220 we were connecting. do it now.
5223 request_input_change_handling ();
5227 /* force all diskstreams to update their capture offset values to
5228 reflect any changes in latencies within the graph.
5231 boost::shared_ptr<RouteList> rl = routes.reader ();
5232 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5233 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5235 tr->set_capture_offset ();
5240 /** @return Number of frames that there is disk space available to write,
5243 boost::optional<framecnt_t>
5244 Session::available_capture_duration ()
5246 Glib::Threads::Mutex::Lock lm (space_lock);
5248 if (_total_free_4k_blocks_uncertain) {
5249 return boost::optional<framecnt_t> ();
5252 float sample_bytes_on_disk = 4.0; // keep gcc happy
5254 switch (config.get_native_file_data_format()) {
5256 sample_bytes_on_disk = 4.0;
5260 sample_bytes_on_disk = 3.0;
5264 sample_bytes_on_disk = 2.0;
5268 /* impossible, but keep some gcc versions happy */
5269 fatal << string_compose (_("programming error: %1"),
5270 X_("illegal native file data format"))
5272 abort(); /*NOTREACHED*/
5275 double scale = 4096.0 / sample_bytes_on_disk;
5277 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
5278 return max_framecnt;
5281 return (framecnt_t) floor (_total_free_4k_blocks * scale);
5285 Session::add_bundle (boost::shared_ptr<Bundle> bundle, bool emit_signal)
5288 RCUWriter<BundleList> writer (_bundles);
5289 boost::shared_ptr<BundleList> b = writer.get_copy ();
5290 b->push_back (bundle);
5294 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5301 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
5303 bool removed = false;
5306 RCUWriter<BundleList> writer (_bundles);
5307 boost::shared_ptr<BundleList> b = writer.get_copy ();
5308 BundleList::iterator i = find (b->begin(), b->end(), bundle);
5310 if (i != b->end()) {
5317 BundleAddedOrRemoved (); /* EMIT SIGNAL */
5323 boost::shared_ptr<Bundle>
5324 Session::bundle_by_name (string name) const
5326 boost::shared_ptr<BundleList> b = _bundles.reader ();
5328 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
5329 if ((*i)->name() == name) {
5334 return boost::shared_ptr<Bundle> ();
5338 Session::tempo_map_changed (const PropertyChange&)
5342 playlists->update_after_tempo_map_change ();
5344 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
5350 Session::update_locations_after_tempo_map_change (const Locations::LocationList& loc)
5352 for (Locations::LocationList::const_iterator i = loc.begin(); i != loc.end(); ++i) {
5353 (*i)->recompute_frames_from_bbt ();
5357 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
5358 * the given count with the current block size.
5361 Session::ensure_buffers (ChanCount howmany)
5363 BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
5367 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
5369 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5370 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
5375 Session::next_insert_id ()
5377 /* this doesn't really loop forever. just think about it */
5380 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < insert_bitset.size(); ++n) {
5381 if (!insert_bitset[n]) {
5382 insert_bitset[n] = true;
5388 /* none available, so resize and try again */
5390 insert_bitset.resize (insert_bitset.size() + 16, false);
5395 Session::next_send_id ()
5397 /* this doesn't really loop forever. just think about it */
5400 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < send_bitset.size(); ++n) {
5401 if (!send_bitset[n]) {
5402 send_bitset[n] = true;
5408 /* none available, so resize and try again */
5410 send_bitset.resize (send_bitset.size() + 16, false);
5415 Session::next_aux_send_id ()
5417 /* this doesn't really loop forever. just think about it */
5420 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < aux_send_bitset.size(); ++n) {
5421 if (!aux_send_bitset[n]) {
5422 aux_send_bitset[n] = true;
5428 /* none available, so resize and try again */
5430 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
5435 Session::next_return_id ()
5437 /* this doesn't really loop forever. just think about it */
5440 for (boost::dynamic_bitset<uint32_t>::size_type n = 1; n < return_bitset.size(); ++n) {
5441 if (!return_bitset[n]) {
5442 return_bitset[n] = true;
5448 /* none available, so resize and try again */
5450 return_bitset.resize (return_bitset.size() + 16, false);
5455 Session::mark_send_id (uint32_t id)
5457 if (id >= send_bitset.size()) {
5458 send_bitset.resize (id+16, false);
5460 if (send_bitset[id]) {
5461 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
5463 send_bitset[id] = true;
5467 Session::mark_aux_send_id (uint32_t id)
5469 if (id >= aux_send_bitset.size()) {
5470 aux_send_bitset.resize (id+16, false);
5472 if (aux_send_bitset[id]) {
5473 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
5475 aux_send_bitset[id] = true;
5479 Session::mark_return_id (uint32_t id)
5481 if (id >= return_bitset.size()) {
5482 return_bitset.resize (id+16, false);
5484 if (return_bitset[id]) {
5485 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
5487 return_bitset[id] = true;
5491 Session::mark_insert_id (uint32_t id)
5493 if (id >= insert_bitset.size()) {
5494 insert_bitset.resize (id+16, false);
5496 if (insert_bitset[id]) {
5497 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
5499 insert_bitset[id] = true;
5503 Session::unmark_send_id (uint32_t id)
5505 if (id < send_bitset.size()) {
5506 send_bitset[id] = false;
5511 Session::unmark_aux_send_id (uint32_t id)
5513 if (id < aux_send_bitset.size()) {
5514 aux_send_bitset[id] = false;
5519 Session::unmark_return_id (uint32_t id)
5521 if (_state_of_the_state & Deletion) { return; }
5522 if (id < return_bitset.size()) {
5523 return_bitset[id] = false;
5528 Session::unmark_insert_id (uint32_t id)
5530 if (id < insert_bitset.size()) {
5531 insert_bitset[id] = false;
5536 Session::reset_native_file_format ()
5538 boost::shared_ptr<RouteList> rl = routes.reader ();
5540 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
5541 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5543 /* don't save state as we do this, there's no point
5545 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
5546 tr->reset_write_sources (false);
5547 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
5553 Session::route_name_unique (string n) const
5555 boost::shared_ptr<RouteList> r = routes.reader ();
5557 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5558 if ((*i)->name() == n) {
5567 Session::route_name_internal (string n) const
5569 if (auditioner && auditioner->name() == n) {
5573 if (_click_io && _click_io->name() == n) {
5581 Session::freeze_all (InterThreadInfo& itt)
5583 boost::shared_ptr<RouteList> r = routes.reader ();
5585 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5587 boost::shared_ptr<Track> t;
5589 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
5590 /* XXX this is wrong because itt.progress will keep returning to zero at the start
5600 boost::shared_ptr<Region>
5601 Session::write_one_track (Track& track, framepos_t start, framepos_t end,
5602 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
5603 InterThreadInfo& itt,
5604 boost::shared_ptr<Processor> endpoint, bool include_endpoint,
5605 bool for_export, bool for_freeze)
5607 boost::shared_ptr<Region> result;
5608 boost::shared_ptr<Playlist> playlist;
5609 boost::shared_ptr<Source> source;
5610 ChanCount diskstream_channels (track.n_channels());
5611 framepos_t position;
5612 framecnt_t this_chunk;
5614 framepos_t latency_skip;
5616 framepos_t len = end - start;
5617 bool need_block_size_reset = false;
5618 ChanCount const max_proc = track.max_processor_streams ();
5619 string legal_playlist_name;
5620 string possible_path;
5623 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
5624 end, start) << endmsg;
5628 diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
5629 include_endpoint, for_export, for_freeze);
5631 if (diskstream_channels.n(track.data_type()) < 1) {
5632 error << _("Cannot write a range with no data.") << endmsg;
5636 // block all process callback handling
5638 block_processing ();
5641 // synchronize with AudioEngine::process_callback()
5642 // make sure processing is not currently running
5643 // and processing_blocked() is honored before
5644 // acquiring thread buffers
5645 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
5648 _bounce_processing_active = true;
5650 /* call tree *MUST* hold route_lock */
5652 if ((playlist = track.playlist()) == 0) {
5656 legal_playlist_name = legalize_for_path (playlist->name());
5658 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n(track.data_type()); ++chan_n) {
5660 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
5661 string path = ((track.data_type() == DataType::AUDIO)
5662 ? new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true)
5663 : new_midi_source_path (legal_playlist_name));
5670 source = SourceFactory::createWritable (track.data_type(), *this, path, false, frame_rate());
5673 catch (failed_constructor& err) {
5674 error << string_compose (_("cannot create new file \"%1\" for %2"), path, track.name()) << endmsg;
5678 srcs.push_back (source);
5681 /* tell redirects that care that we are about to use a much larger
5682 * blocksize. this will flush all plugins too, so that they are ready
5683 * to be used for this process.
5686 need_block_size_reset = true;
5687 track.set_block_size (bounce_chunk_size);
5688 _engine.main_thread()->get_buffers ();
5692 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5694 /* create a set of reasonably-sized buffers */
5695 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
5696 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
5698 buffers.set_count (max_proc);
5700 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5701 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5702 boost::shared_ptr<MidiSource> ms;
5704 afs->prepare_for_peakfile_writes ();
5705 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5706 Source::Lock lock(ms->mutex());
5707 ms->mark_streaming_write_started(lock);
5711 while (to_do && !itt.cancel) {
5713 this_chunk = min (to_do, bounce_chunk_size);
5715 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
5719 start += this_chunk;
5720 to_do -= this_chunk;
5721 itt.progress = (float) (1.0 - ((double) to_do / len));
5723 if (latency_skip >= bounce_chunk_size) {
5724 latency_skip -= bounce_chunk_size;
5728 const framecnt_t current_chunk = this_chunk - latency_skip;
5731 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5732 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5733 boost::shared_ptr<MidiSource> ms;
5736 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
5739 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5740 Source::Lock lock(ms->mutex());
5742 const MidiBuffer& buf = buffers.get_midi(0);
5743 for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
5744 Evoral::Event<framepos_t> ev = *i;
5745 ev.set_time(ev.time() - position);
5746 ms->append_event_frames(lock, ev, ms->timeline_position());
5753 /* post-roll, pick up delayed processor output */
5754 latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
5756 while (latency_skip && !itt.cancel) {
5757 this_chunk = min (latency_skip, bounce_chunk_size);
5758 latency_skip -= this_chunk;
5760 buffers.silence (this_chunk, 0);
5761 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
5764 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
5765 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5768 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
5780 xnow = localtime (&now);
5782 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
5783 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5784 boost::shared_ptr<MidiSource> ms;
5787 afs->update_header (position, *xnow, now);
5788 afs->flush_header ();
5789 } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(*src))) {
5790 Source::Lock lock(ms->mutex());
5791 ms->mark_streaming_write_completed(lock);
5795 /* construct a region to represent the bounced material */
5799 plist.add (Properties::start, 0);
5800 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
5801 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
5803 result = RegionFactory::create (srcs, plist);
5809 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5810 (*src)->mark_for_remove ();
5811 (*src)->drop_references ();
5815 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
5816 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
5819 afs->done_with_peakfile_writes ();
5823 _bounce_processing_active = false;
5825 if (need_block_size_reset) {
5826 _engine.main_thread()->drop_buffers ();
5827 track.set_block_size (get_block_size());
5830 unblock_processing ();
5837 Session::gain_automation_buffer() const
5839 return ProcessThread::gain_automation_buffer ();
5843 Session::trim_automation_buffer() const
5845 return ProcessThread::trim_automation_buffer ();
5849 Session::send_gain_automation_buffer() const
5851 return ProcessThread::send_gain_automation_buffer ();
5855 Session::pan_automation_buffer() const
5857 return ProcessThread::pan_automation_buffer ();
5861 Session::get_silent_buffers (ChanCount count)
5863 return ProcessThread::get_silent_buffers (count);
5867 Session::get_scratch_buffers (ChanCount count, bool silence)
5869 return ProcessThread::get_scratch_buffers (count, silence);
5873 Session::get_noinplace_buffers (ChanCount count)
5875 return ProcessThread::get_noinplace_buffers (count);
5879 Session::get_route_buffers (ChanCount count, bool silence)
5881 return ProcessThread::get_route_buffers (count, silence);
5886 Session::get_mix_buffers (ChanCount count)
5888 return ProcessThread::get_mix_buffers (count);
5892 Session::ntracks () const
5895 boost::shared_ptr<RouteList> r = routes.reader ();
5897 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5898 if (boost::dynamic_pointer_cast<Track> (*i)) {
5907 Session::nbusses () const
5910 boost::shared_ptr<RouteList> r = routes.reader ();
5912 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5913 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
5922 Session::add_automation_list(AutomationList *al)
5924 automation_lists[al->id()] = al;
5927 /** @return true if there is at least one record-enabled track, otherwise false */
5929 Session::have_rec_enabled_track () const
5931 return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
5935 Session::have_rec_disabled_track () const
5937 return g_atomic_int_get (const_cast<gint*>(&_have_rec_disabled_track)) == 1;
5940 /** Update the state of our rec-enabled tracks flag */
5942 Session::update_route_record_state ()
5944 boost::shared_ptr<RouteList> rl = routes.reader ();
5945 RouteList::iterator i = rl->begin();
5946 while (i != rl->end ()) {
5948 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5949 if (tr && tr->record_enabled ()) {
5956 int const old = g_atomic_int_get (&_have_rec_enabled_track);
5958 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
5960 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
5961 RecordStateChanged (); /* EMIT SIGNAL */
5964 for (i = rl->begin(); i != rl->end (); ++i) {
5965 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
5966 if (tr && !tr->record_enabled ()) {
5971 g_atomic_int_set (&_have_rec_disabled_track, i != rl->end () ? 1 : 0);
5973 bool record_arm_state_changed = (old != g_atomic_int_get (&_have_rec_enabled_track) );
5975 if (record_status() == Recording && record_arm_state_changed ) {
5976 RecordArmStateChanged ();
5982 Session::listen_position_changed ()
5984 boost::shared_ptr<RouteList> r = routes.reader ();
5986 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
5987 (*i)->listen_position_changed ();
5992 Session::solo_control_mode_changed ()
5994 /* cancel all solo or all listen when solo control mode changes */
5997 set_solo (get_routes(), false);
5998 } else if (listening()) {
5999 set_listen (get_routes(), false);
6003 /** Called when a property of one of our route groups changes */
6005 Session::route_group_property_changed (RouteGroup* rg)
6007 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
6010 /** Called when a route is added to one of our route groups */
6012 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6014 RouteAddedToRouteGroup (rg, r);
6017 /** Called when a route is removed from one of our route groups */
6019 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
6021 update_route_record_state ();
6022 RouteRemovedFromRouteGroup (rg, r); /* EMIT SIGNAL */
6025 boost::shared_ptr<RouteList>
6026 Session::get_tracks () const
6028 boost::shared_ptr<RouteList> rl = routes.reader ();
6029 boost::shared_ptr<RouteList> tl (new RouteList);
6031 for (RouteList::const_iterator r = rl->begin(); r != rl->end(); ++r) {
6032 if (boost::dynamic_pointer_cast<Track> (*r)) {
6033 if (!(*r)->is_auditioner()) {
6041 boost::shared_ptr<RouteList>
6042 Session::get_routes_with_regions_at (framepos_t const p) const
6044 boost::shared_ptr<RouteList> r = routes.reader ();
6045 boost::shared_ptr<RouteList> rl (new RouteList);
6047 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6048 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6053 boost::shared_ptr<Playlist> pl = tr->playlist ();
6058 if (pl->has_region_at (p)) {
6067 Session::goto_end ()
6069 if (_session_range_location) {
6070 request_locate (_session_range_location->end(), false);
6072 request_locate (0, false);
6077 Session::goto_start ()
6079 if (_session_range_location) {
6080 request_locate (_session_range_location->start(), false);
6082 request_locate (0, false);
6087 Session::current_start_frame () const
6089 return _session_range_location ? _session_range_location->start() : 0;
6093 Session::current_end_frame () const
6095 return _session_range_location ? _session_range_location->end() : 0;
6099 Session::set_session_range_location (framepos_t start, framepos_t end)
6101 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
6102 _locations->add (_session_range_location);
6106 Session::step_edit_status_change (bool yn)
6112 send = (_step_editors == 0);
6117 send = (_step_editors == 1);
6120 if (_step_editors > 0) {
6126 StepEditStatusChange (val);
6132 Session::start_time_changed (framepos_t old)
6134 /* Update the auto loop range to match the session range
6135 (unless the auto loop range has been changed by the user)
6138 Location* s = _locations->session_range_location ();
6143 Location* l = _locations->auto_loop_location ();
6145 if (l && l->start() == old) {
6146 l->set_start (s->start(), true);
6151 Session::end_time_changed (framepos_t old)
6153 /* Update the auto loop range to match the session range
6154 (unless the auto loop range has been changed by the user)
6157 Location* s = _locations->session_range_location ();
6162 Location* l = _locations->auto_loop_location ();
6164 if (l && l->end() == old) {
6165 l->set_end (s->end(), true);
6169 std::vector<std::string>
6170 Session::source_search_path (DataType type) const
6174 if (session_dirs.size() == 1) {
6176 case DataType::AUDIO:
6177 sp.push_back (_session_dir->sound_path());
6179 case DataType::MIDI:
6180 sp.push_back (_session_dir->midi_path());
6184 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
6185 SessionDirectory sdir (i->path);
6187 case DataType::AUDIO:
6188 sp.push_back (sdir.sound_path());
6190 case DataType::MIDI:
6191 sp.push_back (sdir.midi_path());
6197 if (type == DataType::AUDIO) {
6198 const string sound_path_2X = _session_dir->sound_path_2X();
6199 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
6200 if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
6201 sp.push_back (sound_path_2X);
6206 // now check the explicit (possibly user-specified) search path
6209 case DataType::AUDIO:
6210 sp += Searchpath(config.get_audio_search_path ());
6212 case DataType::MIDI:
6213 sp += Searchpath(config.get_midi_search_path ());
6221 Session::ensure_search_path_includes (const string& path, DataType type)
6230 case DataType::AUDIO:
6231 sp += Searchpath(config.get_audio_search_path ());
6233 case DataType::MIDI:
6234 sp += Searchpath (config.get_midi_search_path ());
6238 for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
6239 /* No need to add this new directory if it has the same inode as
6240 an existing one; checking inode rather than name prevents duplicated
6241 directories when we are using symlinks.
6243 On Windows, I think we could just do if (*i == path) here.
6245 if (PBD::equivalent_paths (*i, path)) {
6253 case DataType::AUDIO:
6254 config.set_audio_search_path (sp.to_string());
6256 case DataType::MIDI:
6257 config.set_midi_search_path (sp.to_string());
6263 Session::remove_dir_from_search_path (const string& dir, DataType type)
6268 case DataType::AUDIO:
6269 sp = Searchpath(config.get_audio_search_path ());
6271 case DataType::MIDI:
6272 sp = Searchpath (config.get_midi_search_path ());
6279 case DataType::AUDIO:
6280 config.set_audio_search_path (sp.to_string());
6282 case DataType::MIDI:
6283 config.set_midi_search_path (sp.to_string());
6289 boost::shared_ptr<Speakers>
6290 Session::get_speakers()
6296 Session::unknown_processors () const
6300 boost::shared_ptr<RouteList> r = routes.reader ();
6301 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6302 list<string> t = (*i)->unknown_processors ();
6303 copy (t.begin(), t.end(), back_inserter (p));
6313 Session::update_latency (bool playback)
6315 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
6317 if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
6321 boost::shared_ptr<RouteList> r = routes.reader ();
6322 framecnt_t max_latency = 0;
6325 /* reverse the list so that we work backwards from the last route to run to the first */
6326 RouteList* rl = routes.reader().get();
6327 r.reset (new RouteList (*rl));
6328 reverse (r->begin(), r->end());
6331 /* compute actual latency values for the given direction and store them all in per-port
6332 structures. this will also publish the same values (to JACK) so that computation of latency
6333 for routes can consistently use public latency values.
6336 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6337 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
6340 /* because we latency compensate playback, our published playback latencies should
6341 be the same for all output ports - all material played back by ardour has
6342 the same latency, whether its caused by plugins or by latency compensation. since
6343 these may differ from the values computed above, reset all playback port latencies
6347 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
6349 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6350 (*i)->set_public_port_latencies (max_latency, playback);
6355 post_playback_latency ();
6359 post_capture_latency ();
6362 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
6366 Session::post_playback_latency ()
6368 set_worst_playback_latency ();
6370 boost::shared_ptr<RouteList> r = routes.reader ();
6372 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6373 if (!(*i)->is_auditioner() && ((*i)->active())) {
6374 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
6378 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6379 (*i)->set_latency_compensation (_worst_track_latency);
6384 Session::post_capture_latency ()
6386 set_worst_capture_latency ();
6388 /* reflect any changes in capture latencies into capture offsets
6391 boost::shared_ptr<RouteList> rl = routes.reader();
6392 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
6393 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6395 tr->set_capture_offset ();
6401 Session::initialize_latencies ()
6404 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
6405 update_latency (false);
6406 update_latency (true);
6409 set_worst_io_latencies ();
6413 Session::set_worst_io_latencies ()
6415 set_worst_playback_latency ();
6416 set_worst_capture_latency ();
6420 Session::set_worst_playback_latency ()
6422 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6426 _worst_output_latency = 0;
6428 if (!_engine.connected()) {
6432 boost::shared_ptr<RouteList> r = routes.reader ();
6434 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6435 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
6438 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
6442 Session::set_worst_capture_latency ()
6444 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6448 _worst_input_latency = 0;
6450 if (!_engine.connected()) {
6454 boost::shared_ptr<RouteList> r = routes.reader ();
6456 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6457 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
6460 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
6464 Session::update_latency_compensation (bool force_whole_graph)
6466 bool some_track_latency_changed = false;
6468 if (_state_of_the_state & (InitialConnecting|Deletion)) {
6472 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
6474 _worst_track_latency = 0;
6476 boost::shared_ptr<RouteList> r = routes.reader ();
6478 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6479 if (!(*i)->is_auditioner() && ((*i)->active())) {
6481 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
6482 some_track_latency_changed = true;
6484 _worst_track_latency = max (tl, _worst_track_latency);
6488 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
6489 (some_track_latency_changed ? "yes" : "no")));
6491 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
6493 if (some_track_latency_changed || force_whole_graph) {
6494 _engine.update_latencies ();
6498 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
6499 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
6503 tr->set_capture_offset ();
6508 Session::session_name_is_legal (const string& path)
6510 char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
6512 for (int i = 0; illegal_chars[i]; ++i) {
6513 if (path.find (illegal_chars[i]) != string::npos) {
6514 return illegal_chars[i];
6522 Session::next_control_id () const
6526 /* the monitor bus remote ID is in a different
6527 * "namespace" than regular routes. its existence doesn't
6528 * affect normal (low) numbered routes.
6535 /* the same about masterbus in Waves Tracks */
6537 if (Profile->get_trx() && _master_out) {
6541 return nroutes() - subtract;
6545 Session::notify_remote_id_change ()
6547 if (deletion_in_progress()) {
6551 switch (Config->get_remote_model()) {
6553 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
6559 #ifdef USE_TRACKS_CODE_FEATURES
6560 /* Waves Tracks: for Waves Tracks session it's required to reconnect their IOs
6561 * if track order has been changed by user
6563 reconnect_existing_routes(true, true);
6569 Session::sync_order_keys ()
6571 if (deletion_in_progress()) {
6575 /* tell everyone that something has happened to the sort keys
6576 and let them sync up with the change(s)
6577 this will give objects that manage the sort order keys the
6578 opportunity to keep them in sync if they wish to.
6581 DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
6583 reassign_track_numbers();
6585 Route::SyncOrderKeys (); /* EMIT SIGNAL */
6587 DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
6591 Session::operation_in_progress (GQuark op) const
6593 return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
6596 boost::shared_ptr<Port>
6597 Session::ltc_input_port () const
6599 return _ltc_input->nth (0);
6602 boost::shared_ptr<Port>
6603 Session::ltc_output_port () const
6605 return _ltc_output->nth (0);
6609 Session::reconnect_ltc_input ()
6613 string src = Config->get_ltc_source_port();
6615 _ltc_input->disconnect (this);
6617 if (src != _("None") && !src.empty()) {
6618 _ltc_input->nth (0)->connect (src);
6621 if ( ARDOUR::Profile->get_trx () ) {
6622 // Tracks need this signal to update timecode_source_dropdown
6623 MtcOrLtcInputPortChanged (); //emit signal
6629 Session::reconnect_ltc_output ()
6633 string src = Config->get_ltc_output_port();
6635 _ltc_output->disconnect (this);
6637 if (src != _("None") && !src.empty()) {
6638 _ltc_output->nth (0)->connect (src);
6644 Session::set_range_selection (framepos_t start, framepos_t end)
6646 _range_selection = Evoral::Range<framepos_t> (start, end);
6647 #ifdef USE_TRACKS_CODE_FEATURES
6648 follow_playhead_priority ();
6653 Session::set_object_selection (framepos_t start, framepos_t end)
6655 _object_selection = Evoral::Range<framepos_t> (start, end);
6656 #ifdef USE_TRACKS_CODE_FEATURES
6657 follow_playhead_priority ();
6662 Session::clear_range_selection ()
6664 _range_selection = Evoral::Range<framepos_t> (-1,-1);
6665 #ifdef USE_TRACKS_CODE_FEATURES
6666 follow_playhead_priority ();
6671 Session::clear_object_selection ()
6673 _object_selection = Evoral::Range<framepos_t> (-1,-1);
6674 #ifdef USE_TRACKS_CODE_FEATURES
6675 follow_playhead_priority ();
6680 Session::auto_connect_route (boost::shared_ptr<Route> route, bool connect_inputs,
6681 const ChanCount& input_start,
6682 const ChanCount& output_start,
6683 const ChanCount& input_offset,
6684 const ChanCount& output_offset)
6686 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6687 _auto_connect_queue.push (AutoConnectRequest (route, connect_inputs,
6688 input_start, output_start,
6689 input_offset, output_offset));
6691 if (pthread_mutex_trylock (&_auto_connect_mutex) == 0) {
6692 pthread_cond_signal (&_auto_connect_cond);
6693 pthread_mutex_unlock (&_auto_connect_mutex);
6698 Session::auto_connect (const AutoConnectRequest& ar)
6700 boost::shared_ptr<Route> route = ar.route.lock();
6702 if (!route) { return; }
6704 if (!IO::connecting_legal) {
6708 //why would we need the process lock ??
6709 //Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
6711 /* If both inputs and outputs are auto-connected to physical ports,
6712 * use the max of input and output offsets to ensure auto-connected
6713 * port numbers always match up (e.g. the first audio input and the
6714 * first audio output of the route will have the same physical
6715 * port number). Otherwise just use the lowest input or output
6719 const bool in_out_physical =
6720 (Config->get_input_auto_connect() & AutoConnectPhysical)
6721 && (Config->get_output_auto_connect() & AutoConnectPhysical)
6722 && ar.connect_inputs;
6724 const ChanCount in_offset = in_out_physical
6725 ? ChanCount::max(ar.input_offset, ar.output_offset)
6728 const ChanCount out_offset = in_out_physical
6729 ? ChanCount::max(ar.input_offset, ar.output_offset)
6732 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
6733 vector<string> physinputs;
6734 vector<string> physoutputs;
6736 _engine.get_physical_outputs (*t, physoutputs);
6737 _engine.get_physical_inputs (*t, physinputs);
6739 if (!physinputs.empty() && ar.connect_inputs) {
6740 uint32_t nphysical_in = physinputs.size();
6742 for (uint32_t i = ar.input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
6745 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
6746 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
6749 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
6755 if (!physoutputs.empty()) {
6756 uint32_t nphysical_out = physoutputs.size();
6757 for (uint32_t i = ar.output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
6761 * do not create new connections if we reached the limit of physical outputs
6764 if (!(Config->get_output_auto_connect() & AutoConnectMaster) &&
6765 ARDOUR::Profile->get_trx () &&
6766 ar.output_offset.get(*t) == nphysical_out ) {
6770 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
6771 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
6772 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
6773 /* master bus is audio only */
6774 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
6775 port = _master_out->input()->ports().port(*t,
6776 i % _master_out->input()->n_ports().get(*t))->name();
6780 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
6789 Session::auto_connect_thread_start ()
6791 if (_ac_thread_active) {
6794 _ac_thread_active = true;
6796 while (!_auto_connect_queue.empty ()) {
6797 _auto_connect_queue.pop ();
6800 if (pthread_create (&_auto_connect_thread, NULL, auto_connect_thread, this)) {
6801 _ac_thread_active = false;
6806 Session::auto_connect_thread_terminate ()
6808 if (!_ac_thread_active) {
6811 _ac_thread_active = false;
6813 if (pthread_mutex_lock (&_auto_connect_mutex) == 0) {
6814 pthread_cond_signal (&_auto_connect_cond);
6815 pthread_mutex_unlock (&_auto_connect_mutex);
6819 pthread_join (_auto_connect_thread, &status);
6823 Session::auto_connect_thread (void *arg)
6825 Session *s = static_cast<Session *>(arg);
6826 s->auto_connect_thread_run ();
6832 Session::auto_connect_thread_run ()
6834 pthread_set_name (X_("autoconnect"));
6835 SessionEvent::create_per_thread_pool (X_("autoconnect"), 256);
6836 PBD::notify_event_loops_about_thread_creation (pthread_self(), X_("autoconnect"), 256);
6837 pthread_mutex_lock (&_auto_connect_mutex);
6838 while (_ac_thread_active) {
6840 while (!_auto_connect_queue.empty ()) {
6841 Glib::Threads::Mutex::Lock lx (_auto_connect_queue_lock);
6842 if (_auto_connect_queue.empty ()) { break; } // re-check with lock
6843 const AutoConnectRequest ar (_auto_connect_queue.front());
6844 _auto_connect_queue.pop ();
6849 pthread_cond_wait (&_auto_connect_cond, &_auto_connect_mutex);
6851 pthread_mutex_unlock (&_auto_connect_mutex);