2 Copyright (C) 1999-2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <cstdio> /* sprintf(3) ... grrr */
33 #include <glibmm/thread.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
37 #include <boost/algorithm/string/erase.hpp>
39 #include "pbd/error.h"
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/strsplit.h"
49 #include "ardour/amp.h"
50 #include "ardour/analyser.h"
51 #include "ardour/audio_buffer.h"
52 #include "ardour/audio_diskstream.h"
53 #include "ardour/audio_port.h"
54 #include "ardour/audio_track.h"
55 #include "ardour/audioengine.h"
56 #include "ardour/audiofilesource.h"
57 #include "ardour/audioplaylist.h"
58 #include "ardour/audioregion.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/configuration.h"
66 #include "ardour/control_protocol_manager.h"
67 #include "ardour/crossfade.h"
68 #include "ardour/cycle_timer.h"
69 #include "ardour/data_type.h"
70 #include "ardour/debug.h"
71 #include "ardour/filename_extensions.h"
72 #include "ardour/internal_send.h"
73 #include "ardour/io_processor.h"
74 #include "ardour/midi_diskstream.h"
75 #include "ardour/midi_playlist.h"
76 #include "ardour/midi_region.h"
77 #include "ardour/midi_track.h"
78 #include "ardour/midi_ui.h"
79 #include "ardour/named_selection.h"
80 #include "ardour/process_thread.h"
81 #include "ardour/playlist.h"
82 #include "ardour/plugin_insert.h"
83 #include "ardour/port_insert.h"
84 #include "ardour/processor.h"
85 #include "ardour/rc_configuration.h"
86 #include "ardour/recent_sessions.h"
87 #include "ardour/region_factory.h"
88 #include "ardour/return.h"
89 #include "ardour/route_dag.h"
90 #include "ardour/route_group.h"
91 #include "ardour/send.h"
92 #include "ardour/session.h"
93 #include "ardour/session_directory.h"
94 #include "ardour/session_directory.h"
95 #include "ardour/session_metadata.h"
96 #include "ardour/session_playlists.h"
97 #include "ardour/slave.h"
98 #include "ardour/smf_source.h"
99 #include "ardour/source_factory.h"
100 #include "ardour/tape_file_matcher.h"
101 #include "ardour/tempo.h"
102 #include "ardour/utils.h"
103 #include "ardour/graph.h"
104 #include "ardour/speakers.h"
105 #include "ardour/operations.h"
107 #include "midi++/port.h"
108 #include "midi++/mmc.h"
109 #include "midi++/manager.h"
114 using namespace ARDOUR;
117 bool Session::_disable_all_loaded_plugins = false;
119 PBD::Signal1<void,std::string> Session::Dialog;
120 PBD::Signal0<int> Session::AskAboutPendingState;
121 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
122 PBD::Signal0<void> Session::SendFeedback;
123 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
125 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
126 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
127 PBD::Signal0<void> Session::AutoBindingOn;
128 PBD::Signal0<void> Session::AutoBindingOff;
129 PBD::Signal2<void,std::string, std::string> Session::Exported;
130 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
131 PBD::Signal0<void> Session::Quit;
133 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
134 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
136 /** @param snapshot_name Snapshot name, without .ardour prefix */
137 Session::Session (AudioEngine &eng,
138 const string& fullpath,
139 const string& snapshot_name,
140 BusProfile* bus_profile,
143 , _target_transport_speed (0.0)
144 , _requested_return_frame (-1)
145 , _session_dir (new SessionDirectory(fullpath))
147 , _state_of_the_state (Clean)
148 , _butler (new Butler (*this))
149 , _post_transport_work (0)
150 , _send_timecode_update (false)
151 , _all_route_group (new RouteGroup (*this, "all"))
152 , route_graph (new Graph(*this))
153 , routes (new RouteList)
154 , _total_free_4k_blocks (0)
155 , _bundles (new BundleList)
156 , _bundle_xml_node (0)
158 , _click_io ((IO*) 0)
160 , click_emphasis_data (0)
162 , _metadata (new SessionMetadata())
163 , _have_rec_enabled_track (false)
164 , _suspend_timecode_transmission (0)
166 _locations = new Locations (*this);
168 playlists.reset (new SessionPlaylists);
170 _all_route_group->set_active (true, this);
172 interpolation.add_channel_to (0, 0);
174 if (!eng.connected()) {
175 throw failed_constructor();
178 n_physical_outputs = _engine.n_physical_outputs ();
179 n_physical_inputs = _engine.n_physical_inputs ();
181 first_stage_init (fullpath, snapshot_name);
183 _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
186 if (create (mix_template, bus_profile)) {
188 throw failed_constructor ();
192 if (second_stage_init ()) {
194 throw failed_constructor ();
197 store_recent_sessions(_name, _path);
199 bool was_dirty = dirty();
201 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
203 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
204 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
207 DirtyChanged (); /* EMIT SIGNAL */
210 StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
211 EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
224 vector<void*> debug_pointers;
226 /* if we got to here, leaving pending capture state around
230 remove_pending_capture_state ();
232 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
234 _engine.remove_session ();
236 /* clear history so that no references to objects are held any more */
240 /* clear state tree so that no references to objects are held any more */
244 /* reset dynamic state version back to default */
246 Stateful::loading_state_version = 0;
248 _butler->drop_references ();
250 delete midi_control_ui;
251 delete _all_route_group;
253 if (click_data != default_click) {
254 delete [] click_data;
257 if (click_emphasis_data != default_click_emphasis) {
258 delete [] click_emphasis_data;
263 /* clear out any pending dead wood from RCU managed objects */
268 AudioDiskstream::free_working_buffers();
270 /* tell everyone who is still standing that we're about to die */
273 /* tell everyone to drop references and delete objects as we go */
275 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
276 named_selections.clear ();
278 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
279 RegionFactory::delete_all_regions ();
281 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
283 /* reset these three references to special routes before we do the usual route delete thing */
286 _master_out.reset ();
287 _monitor_out.reset ();
290 RCUWriter<RouteList> writer (routes);
291 boost::shared_ptr<RouteList> r = writer.get_copy ();
293 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
294 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
295 (*i)->drop_references ();
299 /* writer goes out of scope and updates master */
303 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
304 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
305 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
306 i->second->drop_references ();
311 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
312 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
317 Crossfade::set_buffer_size (0);
319 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
324 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
326 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
327 boost_debug_list_ptrs ();
332 Session::when_engine_running ()
334 string first_physical_output;
336 BootMessage (_("Set block size and sample rate"));
338 set_block_size (_engine.frames_per_cycle());
339 set_frame_rate (_engine.frame_rate());
341 BootMessage (_("Using configuration"));
343 boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
344 boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
346 Config->map_parameters (ff);
347 config.map_parameters (ft);
349 /* every time we reconnect, recompute worst case output latencies */
351 _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
353 if (synced_to_jack()) {
354 _engine.transport_stop ();
357 if (config.get_jack_time_master()) {
358 _engine.transport_locate (_transport_frame);
366 _click_io.reset (new ClickIO (*this, "click"));
368 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
370 /* existing state for Click */
373 if (Stateful::loading_state_version < 3000) {
374 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
376 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
381 _clicking = Config->get_clicking ();
385 error << _("could not setup Click I/O") << endmsg;
392 /* default state for Click: dual-mono to first 2 physical outputs */
395 _engine.get_physical_outputs (DataType::AUDIO, outs);
397 for (uint32_t physport = 0; physport < 2; ++physport) {
398 if (outs.size() > physport) {
399 if (_click_io->add_port (outs[physport], this)) {
400 // relax, even though its an error
405 if (_click_io->n_ports () > ChanCount::ZERO) {
406 _clicking = Config->get_clicking ();
411 catch (failed_constructor& err) {
412 error << _("cannot setup Click I/O") << endmsg;
415 BootMessage (_("Compute I/O Latencies"));
418 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
421 BootMessage (_("Set up standard connections"));
423 vector<string> inputs[DataType::num_types];
424 vector<string> outputs[DataType::num_types];
425 for (uint32_t i = 0; i < DataType::num_types; ++i) {
426 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
427 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
430 /* Create a set of Bundle objects that map
431 to the physical I/O currently available. We create both
432 mono and stereo bundles, so that the common cases of mono
433 and stereo tracks get bundles to put in their mixer strip
434 in / out menus. There may be a nicer way of achieving that;
435 it doesn't really scale that well to higher channel counts
438 /* mono output bundles */
440 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
442 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
444 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
445 c->add_channel (_("mono"), DataType::AUDIO);
446 c->set_port (0, outputs[DataType::AUDIO][np]);
451 /* stereo output bundles */
453 for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
454 if (np + 1 < outputs[DataType::AUDIO].size()) {
456 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
457 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
458 c->add_channel (_("L"), DataType::AUDIO);
459 c->set_port (0, outputs[DataType::AUDIO][np]);
460 c->add_channel (_("R"), DataType::AUDIO);
461 c->set_port (1, outputs[DataType::AUDIO][np + 1]);
467 /* mono input bundles */
469 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
471 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
473 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
474 c->add_channel (_("mono"), DataType::AUDIO);
475 c->set_port (0, inputs[DataType::AUDIO][np]);
480 /* stereo input bundles */
482 for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
483 if (np + 1 < inputs[DataType::AUDIO].size()) {
485 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
487 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
488 c->add_channel (_("L"), DataType::AUDIO);
489 c->set_port (0, inputs[DataType::AUDIO][np]);
490 c->add_channel (_("R"), DataType::AUDIO);
491 c->set_port (1, inputs[DataType::AUDIO][np + 1]);
497 /* MIDI input bundles */
499 for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
500 string n = inputs[DataType::MIDI][np];
501 boost::erase_first (n, X_("alsa_pcm:"));
503 boost::shared_ptr<Bundle> c (new Bundle (n, false));
504 c->add_channel ("", DataType::MIDI);
505 c->set_port (0, inputs[DataType::MIDI][np]);
509 /* MIDI output bundles */
511 for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
512 string n = outputs[DataType::MIDI][np];
513 boost::erase_first (n, X_("alsa_pcm:"));
515 boost::shared_ptr<Bundle> c (new Bundle (n, true));
516 c->add_channel ("", DataType::MIDI);
517 c->set_port (0, outputs[DataType::MIDI][np]);
521 BootMessage (_("Setup signal flow and plugins"));
523 ControlProtocolManager::instance().set_session (this);
525 /* This must be done after the ControlProtocolManager set_session above,
526 as it will set states for ports which the ControlProtocolManager creates.
528 MIDI::Manager::instance()->set_port_states (Config->midi_port_states ());
530 /* And this must be done after the MIDI::Manager::set_port_states as
531 * it will try to make connections whose details are loaded by set_port_states.
536 if (_is_new && !no_auto_connect()) {
538 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock());
540 /* don't connect the master bus outputs if there is a monitor bus */
542 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
544 /* if requested auto-connect the outputs to the first N physical ports.
547 uint32_t limit = _master_out->n_outputs().n_total();
549 for (uint32_t n = 0; n < limit; ++n) {
550 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
552 if (outputs[p->type()].size() > n) {
553 connect_to = outputs[p->type()][n];
556 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
557 if (_master_out->output()->connect (p, connect_to, this)) {
558 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
568 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
569 are undefined, at best.
572 /* control out listens to master bus (but ignores it
573 under some conditions)
576 uint32_t limit = _monitor_out->n_inputs().n_audio();
579 for (uint32_t n = 0; n < limit; ++n) {
580 boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
581 boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
584 string connect_to = o->name();
585 if (_monitor_out->input()->connect (p, connect_to, this)) {
586 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
594 /* if control out is not connected, connect control out to physical outs
597 if (!_monitor_out->output()->connected ()) {
599 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
601 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
604 _monitor_out->output()->connect_ports_to_bundle (b, this);
606 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
607 Config->get_monitor_bus_preferred_bundle())
613 /* Monitor bus is audio only */
614 uint32_t mod = n_physical_outputs.get (DataType::AUDIO);
615 uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
619 for (uint32_t n = 0; n < limit; ++n) {
621 boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
623 if (outputs[DataType::AUDIO].size() > (n % mod)) {
624 connect_to = outputs[DataType::AUDIO][n % mod];
627 if (!connect_to.empty()) {
628 if (_monitor_out->output()->connect (p, connect_to, this)) {
629 error << string_compose (
630 _("cannot connect control output %1 to %2"),
643 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
645 /* update latencies */
647 initialize_latencies ();
649 /* hook us up to the engine */
651 BootMessage (_("Connect to engine"));
652 _engine.set_session (this);
656 Session::hookup_io ()
658 /* stop graph reordering notifications from
659 causing resorts, etc.
662 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
666 /* we delay creating the auditioner till now because
667 it makes its own connections to ports.
671 boost::shared_ptr<Auditioner> a (new Auditioner (*this));
673 throw failed_constructor ();
675 a->use_new_diskstream ();
679 catch (failed_constructor& err) {
680 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
684 /* load bundles, which we may have postponed earlier on */
685 if (_bundle_xml_node) {
686 load_bundles (*_bundle_xml_node);
687 delete _bundle_xml_node;
690 /* Tell all IO objects to connect themselves together */
692 IO::enable_connecting ();
693 MIDI::Port::MakeConnections ();
695 /* Now reset all panners */
697 Delivery::reset_panners ();
699 /* Connect tracks to monitor/listen bus if there is one. Note that in an
700 existing session, the internal sends will already exist, but we want the
701 routes to notice that they connect to the control out specifically.
705 boost::shared_ptr<RouteList> r = routes.reader ();
706 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
708 if ((*x)->is_monitor()) {
712 } else if ((*x)->is_master()) {
718 (*x)->listen_via_monitor ();
723 /* Anyone who cares about input state, wake up and do something */
725 IOConnectionsComplete (); /* EMIT SIGNAL */
727 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
729 /* now handle the whole enchilada as if it was one
735 /* update the full solo state, which can't be
736 correctly determined on a per-route basis, but
737 needs the global overview that only the session
741 update_route_solo_state ();
745 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
747 boost::shared_ptr<Track> track = wp.lock ();
752 boost::shared_ptr<Playlist> playlist;
754 if ((playlist = track->playlist()) != 0) {
755 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
756 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
757 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
762 Session::record_enabling_legal () const
764 /* this used to be in here, but survey says.... we don't need to restrict it */
765 // if (record_status() == Recording) {
769 if (Config->get_all_safe()) {
776 Session::set_track_monitor_input_status (bool yn)
778 boost::shared_ptr<RouteList> rl = routes.reader ();
779 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
780 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
781 if (tr && tr->record_enabled ()) {
782 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
783 tr->monitor_input (yn);
789 Session::reset_input_monitor_state ()
791 if (transport_rolling()) {
792 set_track_monitor_input_status (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
794 set_track_monitor_input_status (Config->get_monitoring_model() == HardwareMonitoring);
799 Session::auto_punch_start_changed (Location* location)
801 replace_event (SessionEvent::PunchIn, location->start());
803 if (get_record_enabled() && config.get_punch_in()) {
804 /* capture start has been changed, so save new pending state */
805 save_state ("", true);
810 Session::auto_punch_end_changed (Location* location)
812 framepos_t when_to_stop = location->end();
813 // when_to_stop += _worst_output_latency + _worst_input_latency;
814 replace_event (SessionEvent::PunchOut, when_to_stop);
818 Session::auto_punch_changed (Location* location)
820 framepos_t when_to_stop = location->end();
822 replace_event (SessionEvent::PunchIn, location->start());
823 //when_to_stop += _worst_output_latency + _worst_input_latency;
824 replace_event (SessionEvent::PunchOut, when_to_stop);
828 Session::auto_loop_changed (Location* location)
830 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
832 if (transport_rolling() && play_loop) {
835 // if (_transport_frame > location->end()) {
837 if (_transport_frame < location->start() || _transport_frame > location->end()) {
838 // relocate to beginning of loop
839 clear_events (SessionEvent::LocateRoll);
841 request_locate (location->start(), true);
844 else if (Config->get_seamless_loop() && !loop_changing) {
846 // schedule a locate-roll to refill the diskstreams at the
848 loop_changing = true;
850 if (location->end() > last_loopend) {
851 clear_events (SessionEvent::LocateRoll);
852 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
859 last_loopend = location->end();
863 Session::set_auto_punch_location (Location* location)
867 if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
868 punch_connections.drop_connections();
869 existing->set_auto_punch (false, this);
870 remove_event (existing->start(), SessionEvent::PunchIn);
871 clear_events (SessionEvent::PunchOut);
872 auto_punch_location_changed (0);
881 if (location->end() <= location->start()) {
882 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
886 punch_connections.drop_connections ();
888 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
889 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
890 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
892 location->set_auto_punch (true, this);
894 auto_punch_changed (location);
896 auto_punch_location_changed (location);
900 Session::set_auto_loop_location (Location* location)
904 if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
905 loop_connections.drop_connections ();
906 existing->set_auto_loop (false, this);
907 remove_event (existing->end(), SessionEvent::AutoLoop);
908 auto_loop_location_changed (0);
917 if (location->end() <= location->start()) {
918 error << _("Session: you can't use a mark for auto loop") << endmsg;
922 last_loopend = location->end();
924 loop_connections.drop_connections ();
926 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
927 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
928 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
930 location->set_auto_loop (true, this);
932 /* take care of our stuff first */
934 auto_loop_changed (location);
936 /* now tell everyone else */
938 auto_loop_location_changed (location);
942 Session::locations_added (Location *)
948 Session::locations_changed ()
950 _locations->apply (*this, &Session::handle_locations_changed);
954 Session::handle_locations_changed (Locations::LocationList& locations)
956 Locations::LocationList::iterator i;
958 bool set_loop = false;
959 bool set_punch = false;
961 for (i = locations.begin(); i != locations.end(); ++i) {
965 if (location->is_auto_punch()) {
966 set_auto_punch_location (location);
969 if (location->is_auto_loop()) {
970 set_auto_loop_location (location);
974 if (location->is_session_range()) {
975 _session_range_location = location;
980 set_auto_loop_location (0);
983 set_auto_punch_location (0);
990 Session::enable_record ()
992 if (_transport_speed != 0.0 && _transport_speed != 1.0) {
993 /* no recording at anything except normal speed */
998 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1000 if (rs == Recording) {
1004 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1006 _last_record_location = _transport_frame;
1007 MIDI::Manager::instance()->mmc()->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1009 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1010 set_track_monitor_input_status (true);
1013 RecordStateChanged ();
1020 Session::disable_record (bool rt_context, bool force)
1024 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1026 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1027 g_atomic_int_set (&_record_status, Disabled);
1028 MIDI::Manager::instance()->mmc()->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1030 if (rs == Recording) {
1031 g_atomic_int_set (&_record_status, Enabled);
1035 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1036 set_track_monitor_input_status (false);
1039 RecordStateChanged (); /* emit signal */
1042 remove_pending_capture_state ();
1048 Session::step_back_from_record ()
1050 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1052 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1053 set_track_monitor_input_status (false);
1056 RecordStateChanged (); /* emit signal */
1061 Session::maybe_enable_record ()
1063 if (_step_editors > 0) {
1067 g_atomic_int_set (&_record_status, Enabled);
1069 /* This function is currently called from somewhere other than an RT thread.
1070 This save_state() call therefore doesn't impact anything. Doing it here
1071 means that we save pending state of which sources the next record will use,
1072 which gives us some chance of recovering from a crash during the record.
1075 save_state ("", true);
1077 if (_transport_speed) {
1078 if (!config.get_punch_in()) {
1082 MIDI::Manager::instance()->mmc()->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1083 RecordStateChanged (); /* EMIT SIGNAL */
1090 Session::audible_frame () const
1096 /* the first of these two possible settings for "offset"
1097 mean that the audible frame is stationary until
1098 audio emerges from the latency compensation
1101 the second means that the audible frame is stationary
1102 until audio would emerge from a physical port
1103 in the absence of any plugin latency compensation
1106 offset = worst_playback_latency ();
1108 if (offset > current_block_size) {
1109 offset -= current_block_size;
1111 /* XXX is this correct? if we have no external
1112 physical connections and everything is internal
1113 then surely this is zero? still, how
1114 likely is that anyway?
1116 offset = current_block_size;
1119 if (synced_to_jack()) {
1120 tf = _engine.transport_frame();
1122 tf = _transport_frame;
1127 if (!non_realtime_work_pending()) {
1131 /* Check to see if we have passed the first guaranteed
1132 audible frame past our last start position. if not,
1133 return that last start point because in terms
1134 of audible frames, we have not moved yet.
1136 `Start position' in this context means the time we last
1137 either started or changed transport direction.
1140 if (_transport_speed > 0.0f) {
1142 if (!play_loop || !have_looped) {
1143 if (tf < _last_roll_or_reversal_location + offset) {
1144 return _last_roll_or_reversal_location;
1152 } else if (_transport_speed < 0.0f) {
1154 /* XXX wot? no backward looping? */
1156 if (tf > _last_roll_or_reversal_location - offset) {
1157 return _last_roll_or_reversal_location;
1169 Session::set_frame_rate (framecnt_t frames_per_second)
1171 /** \fn void Session::set_frame_size(framecnt_t)
1172 the AudioEngine object that calls this guarantees
1173 that it will not be called while we are also in
1174 ::process(). Its fine to do things that block
1178 _base_frame_rate = frames_per_second;
1182 Automatable::set_automation_interval (ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1186 // XXX we need some equivalent to this, somehow
1187 // SndFileSource::setup_standard_crossfades (frames_per_second);
1191 /* XXX need to reset/reinstantiate all LADSPA plugins */
1195 Session::set_block_size (pframes_t nframes)
1197 /* the AudioEngine guarantees
1198 that it will not be called while we are also in
1199 ::process(). It is therefore fine to do things that block
1204 current_block_size = nframes;
1208 boost::shared_ptr<RouteList> r = routes.reader ();
1210 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1211 (*i)->set_block_size (nframes);
1214 boost::shared_ptr<RouteList> rl = routes.reader ();
1215 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1216 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1218 tr->set_block_size (nframes);
1222 set_worst_io_latencies ();
1228 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1230 boost::shared_ptr<Route> r2;
1232 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1233 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1237 /* make a copy of the existing list of routes that feed r1 */
1239 Route::FedBy existing (r1->fed_by());
1241 /* for each route that feeds r1, recurse, marking it as feeding
1245 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1246 if (!(r2 = i->r.lock ())) {
1247 /* (*i) went away, ignore it */
1251 /* r2 is a route that feeds r1 which somehow feeds base. mark
1252 base as being fed by r2
1255 rbase->add_fed_by (r2, i->sends_only);
1259 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1263 if (r1->feeds (r2) && r2->feeds (r1)) {
1267 /* now recurse, so that we can mark base as being fed by
1268 all routes that feed r2
1271 trace_terminal (r2, rbase);
1278 Session::resort_routes ()
1280 /* don't do anything here with signals emitted
1281 by Routes during initial setup or while we
1282 are being destroyed.
1285 if (_state_of_the_state & (InitialConnecting | Deletion)) {
1290 RCUWriter<RouteList> writer (routes);
1291 boost::shared_ptr<RouteList> r = writer.get_copy ();
1292 resort_routes_using (r);
1293 /* writer goes out of scope and forces update */
1296 //route_graph->dump(1);
1299 boost::shared_ptr<RouteList> rl = routes.reader ();
1300 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1301 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1303 const Route::FedBy& fb ((*i)->fed_by());
1305 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1306 boost::shared_ptr<Route> sf = f->r.lock();
1308 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1317 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1321 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1323 (*i)->clear_fed_by ();
1325 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1327 /* although routes can feed themselves, it will
1328 cause an endless recursive descent if we
1329 detect it. so don't bother checking for
1337 bool via_sends_only;
1339 if ((*j)->direct_feeds (*i, &via_sends_only)) {
1341 (*i)->add_fed_by (*j, via_sends_only);
1346 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1347 trace_terminal (*i, *i);
1350 boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1351 route_graph->rechain (sorted_routes);
1354 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1355 for (RouteList::iterator i = sorted_routes->begin(); i != sorted_routes->end(); ++i) {
1356 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1357 (*i)->name(), (*i)->order_key ("signal")));
1363 /** Find a route name starting with \a base, maybe followed by the
1364 * lowest \a id. \a id will always be added if \a definitely_add_number
1365 * is true on entry; otherwise it will only be added if required
1366 * to make the name unique.
1368 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1369 * The available route name with the lowest ID will be used, and \a id
1370 * will be set to the ID.
1372 * \return false if a route name could not be found, and \a track_name
1373 * and \a id do not reflect a free route name.
1376 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1378 if (!definitely_add_number && route_by_name (base) == 0) {
1379 /* juse use the base */
1380 snprintf (name, name_len, "%s", base.c_str());
1385 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1387 if (route_by_name (name) == 0) {
1393 } while (id < (UINT_MAX-1));
1398 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1400 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1402 in = ChanCount::ZERO;
1403 out = ChanCount::ZERO;
1405 boost::shared_ptr<RouteList> r = routes.reader ();
1407 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1408 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1409 if (tr && !tr->is_hidden()) {
1410 in += tr->n_inputs();
1411 out += tr->n_outputs();
1416 /** Caller must not hold process lock
1417 * @param name_template string to use for the start of the name, or "" to use "Midi".
1419 list<boost::shared_ptr<MidiTrack> >
1420 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1422 char track_name[32];
1423 uint32_t track_id = 0;
1425 RouteList new_routes;
1426 list<boost::shared_ptr<MidiTrack> > ret;
1427 uint32_t control_id;
1429 control_id = ntracks() + nbusses();
1431 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Midi");
1434 if (!find_route_name (name_template.empty() ? _("Midi") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1435 error << "cannot find name for new midi track" << endmsg;
1439 boost::shared_ptr<MidiTrack> track;
1442 track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1444 if (track->init ()) {
1448 track->use_new_diskstream();
1450 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1451 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1454 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1455 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1456 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1460 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1461 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1466 track->non_realtime_input_change();
1469 route_group->add (track);
1472 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1473 track->set_remote_control_id (control_id);
1475 new_routes.push_back (track);
1476 ret.push_back (track);
1479 catch (failed_constructor &err) {
1480 error << _("Session: could not create new midi track.") << endmsg;
1484 catch (AudioEngine::PortRegistrationFailure& pfe) {
1486 error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
1494 if (!new_routes.empty()) {
1495 add_routes (new_routes, true, true);
1502 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1504 boost::shared_ptr<Route> midi_track (wmt.lock());
1510 if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1512 if (change.after.n_audio() <= change.before.n_audio()) {
1516 /* new audio ports: make sure the audio goes somewhere useful,
1517 unless the user has no-auto-connect selected.
1519 The existing ChanCounts don't matter for this call as they are only
1520 to do with matching input and output indices, and we are only changing
1526 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1530 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1531 * @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1532 * @param output_start As \a input_start, but for outputs.
1535 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1536 bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1538 if (!IO::connecting_legal) {
1542 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::NOT_LOCK);
1548 /* If both inputs and outputs are auto-connected to physical ports,
1549 use the max of input and output offsets to ensure auto-connected
1550 port numbers always match up (e.g. the first audio input and the
1551 first audio output of the route will have the same physical
1552 port number). Otherwise just use the lowest input or output
1556 DEBUG_TRACE (DEBUG::Graph,
1557 string_compose("Auto-connect: existing in = %1 out = %2\n",
1558 existing_inputs, existing_outputs));
1560 const bool in_out_physical =
1561 (Config->get_input_auto_connect() & AutoConnectPhysical)
1562 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1565 const ChanCount in_offset = in_out_physical
1566 ? ChanCount::max(existing_inputs, existing_outputs)
1569 const ChanCount out_offset = in_out_physical
1570 ? ChanCount::max(existing_inputs, existing_outputs)
1573 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1574 vector<string> physinputs;
1575 vector<string> physoutputs;
1577 _engine.get_physical_outputs (*t, physoutputs);
1578 _engine.get_physical_inputs (*t, physinputs);
1580 if (!physinputs.empty() && connect_inputs) {
1581 uint32_t nphysical_in = physinputs.size();
1583 DEBUG_TRACE (DEBUG::Graph,
1584 string_compose("There are %1 physical inputs of type %2\n",
1587 for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1590 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1591 DEBUG_TRACE (DEBUG::Graph,
1592 string_compose("Get index %1 + %2 % %3 = %4\n",
1593 in_offset.get(*t), i, nphysical_in,
1594 (in_offset.get(*t) + i) % nphysical_in));
1595 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1598 DEBUG_TRACE (DEBUG::Graph,
1599 string_compose("Connect route %1 IN to %2\n",
1600 route->name(), port));
1602 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
1606 ChanCount one_added (*t, 1);
1607 existing_inputs += one_added;
1611 if (!physoutputs.empty()) {
1612 uint32_t nphysical_out = physoutputs.size();
1613 for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
1616 if ((*t) == DataType::MIDI || Config->get_output_auto_connect() & AutoConnectPhysical) {
1617 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1618 } else if ((*t) == DataType::AUDIO && Config->get_output_auto_connect() & AutoConnectMaster) {
1619 /* master bus is audio only */
1620 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1621 port = _master_out->input()->ports().port(*t,
1622 i % _master_out->input()->n_ports().get(*t))->name();
1626 DEBUG_TRACE (DEBUG::Graph,
1627 string_compose("Connect route %1 OUT to %2\n",
1628 route->name(), port));
1630 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
1634 ChanCount one_added (*t, 1);
1635 existing_outputs += one_added;
1641 /** Caller must not hold process lock
1642 * @param name_template string to use for the start of the name, or "" to use "Audio".
1644 list< boost::shared_ptr<AudioTrack> >
1645 Session::new_audio_track (
1646 int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template
1649 char track_name[32];
1650 uint32_t track_id = 0;
1652 RouteList new_routes;
1653 list<boost::shared_ptr<AudioTrack> > ret;
1654 uint32_t control_id;
1656 control_id = ntracks() + nbusses() + 1;
1658 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
1661 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1662 error << "cannot find name for new audio track" << endmsg;
1666 boost::shared_ptr<AudioTrack> track;
1669 track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
1671 if (track->init ()) {
1675 track->use_new_diskstream();
1677 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1678 // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1681 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1683 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1684 error << string_compose (
1685 _("cannot configure %1 in/%2 out configuration for new audio track"),
1686 input_channels, output_channels)
1691 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1692 error << string_compose (
1693 _("cannot configure %1 in/%2 out configuration for new audio track"),
1694 input_channels, output_channels)
1701 route_group->add (track);
1704 track->non_realtime_input_change();
1706 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1707 track->set_remote_control_id (control_id);
1710 new_routes.push_back (track);
1711 ret.push_back (track);
1714 catch (failed_constructor &err) {
1715 error << _("Session: could not create new audio track.") << endmsg;
1719 catch (AudioEngine::PortRegistrationFailure& pfe) {
1721 error << pfe.what() << endmsg;
1729 if (!new_routes.empty()) {
1730 add_routes (new_routes, true, true);
1737 Session::set_remote_control_ids ()
1739 RemoteModel m = Config->get_remote_model();
1740 bool emit_signal = false;
1742 boost::shared_ptr<RouteList> r = routes.reader ();
1744 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1745 if (MixerOrdered == m) {
1746 int32_t order = (*i)->order_key(N_("signal"));
1747 (*i)->set_remote_control_id (order+1, false);
1749 } else if (EditorOrdered == m) {
1750 int32_t order = (*i)->order_key(N_("editor"));
1751 (*i)->set_remote_control_id (order+1, false);
1753 } else if (UserOrdered == m) {
1754 //do nothing ... only changes to remote id's are initiated by user
1759 Route::RemoteControlIDChange();
1763 /** Caller must not hold process lock.
1764 * @param name_template string to use for the start of the name, or "" to use "Bus".
1767 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
1770 uint32_t bus_id = 0;
1773 uint32_t control_id;
1775 control_id = ntracks() + nbusses() + 1;
1777 bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
1780 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
1781 error << "cannot find name for new audio bus" << endmsg;
1786 boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
1792 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1793 // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
1796 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1798 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1799 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1800 input_channels, output_channels)
1806 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1807 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1808 input_channels, output_channels)
1815 route_group->add (bus);
1817 bus->set_remote_control_id (control_id);
1820 bus->add_internal_return ();
1822 ret.push_back (bus);
1826 catch (failed_constructor &err) {
1827 error << _("Session: could not create new audio route.") << endmsg;
1831 catch (AudioEngine::PortRegistrationFailure& pfe) {
1832 error << pfe.what() << endmsg;
1842 add_routes (ret, false, true);
1850 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1854 uint32_t control_id;
1856 uint32_t number = 0;
1858 if (!tree.read (template_path.c_str())) {
1862 XMLNode* node = tree.root();
1864 control_id = ntracks() + nbusses() + 1;
1868 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1870 std::string node_name = IO::name_from_state (*node_copy.children().front());
1872 /* generate a new name by adding a number to the end of the template name */
1873 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name), true)) {
1874 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1878 /* set IO children to use the new name */
1879 XMLNodeList const & children = node_copy.children ();
1880 for (XMLNodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
1881 if ((*i)->name() == IO::state_node_name) {
1882 IO::set_name_in_state (**i, name);
1886 Track::zero_diskstream_id_in_xml (node_copy);
1889 boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1892 error << _("Session: cannot create track/bus from template description") << endmsg;
1896 if (boost::dynamic_pointer_cast<Track>(route)) {
1897 /* force input/output change signals so that the new diskstream
1898 picks up the configuration of the route. During session
1899 loading this normally happens in a different way.
1902 Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1904 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
1905 change.after = route->input()->n_ports();
1906 route->input()->changed (change, this);
1907 change.after = route->output()->n_ports();
1908 route->output()->changed (change, this);
1911 route->set_remote_control_id (control_id);
1914 ret.push_back (route);
1917 catch (failed_constructor &err) {
1918 error << _("Session: could not create new route from template") << endmsg;
1922 catch (AudioEngine::PortRegistrationFailure& pfe) {
1923 error << pfe.what() << endmsg;
1932 add_routes (ret, true, true);
1939 Session::add_routes (RouteList& new_routes, bool auto_connect, bool save)
1941 ChanCount existing_inputs;
1942 ChanCount existing_outputs;
1944 count_existing_track_channels (existing_inputs, existing_outputs);
1947 RCUWriter<RouteList> writer (routes);
1948 boost::shared_ptr<RouteList> r = writer.get_copy ();
1949 r->insert (r->end(), new_routes.begin(), new_routes.end());
1951 /* if there is no control out and we're not in the middle of loading,
1952 resort the graph here. if there is a control out, we will resort
1953 toward the end of this method. if we are in the middle of loading,
1954 we will resort when done.
1957 if (!_monitor_out && IO::connecting_legal) {
1958 resort_routes_using (r);
1962 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1964 boost::weak_ptr<Route> wpr (*x);
1965 boost::shared_ptr<Route> r (*x);
1967 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1968 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
1969 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
1970 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1971 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1972 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1973 r->order_key_changed.connect_same_thread (*this, boost::bind (&Session::route_order_key_changed, this));
1975 if (r->is_master()) {
1979 if (r->is_monitor()) {
1983 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
1985 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
1986 track_playlist_changed (boost::weak_ptr<Track> (tr));
1987 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
1989 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
1991 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
1992 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
1997 auto_connect_route (r, existing_inputs, existing_outputs, true);
2001 if (_monitor_out && IO::connecting_legal) {
2003 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2004 if ((*x)->is_monitor()) {
2006 } else if ((*x)->is_master()) {
2009 (*x)->listen_via_monitor ();
2019 save_state (_current_snapshot_name);
2022 RouteAdded (new_routes); /* EMIT SIGNAL */
2023 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
2027 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2029 boost::shared_ptr<RouteList> r = routes.reader ();
2030 boost::shared_ptr<Send> s;
2032 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2033 if ((s = (*i)->internal_send_for (dest)) != 0) {
2034 s->amp()->gain_control()->set_value (0.0);
2040 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2042 boost::shared_ptr<RouteList> r = routes.reader ();
2043 boost::shared_ptr<Send> s;
2045 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2046 if ((s = (*i)->internal_send_for (dest)) != 0) {
2047 s->amp()->gain_control()->set_value (1.0);
2053 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2055 boost::shared_ptr<RouteList> r = routes.reader ();
2056 boost::shared_ptr<Send> s;
2058 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2059 if ((s = (*i)->internal_send_for (dest)) != 0) {
2060 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2065 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2067 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2069 boost::shared_ptr<RouteList> r = routes.reader ();
2070 boost::shared_ptr<RouteList> t (new RouteList);
2072 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2073 /* no MIDI sends because there are no MIDI busses yet */
2074 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2079 add_internal_sends (dest, p, t);
2083 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2085 if (dest->is_monitor() || dest->is_master()) {
2089 if (!dest->internal_return()) {
2090 dest->add_internal_return();
2093 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2095 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2099 (*i)->listen_via (dest, p);
2106 Session::remove_route (boost::shared_ptr<Route> route)
2108 if (((route == _master_out) || (route == _monitor_out)) && !Config->get_allow_special_bus_removal()) {
2112 route->set_solo (false, this);
2115 RCUWriter<RouteList> writer (routes);
2116 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2120 /* deleting the master out seems like a dumb
2121 idea, but its more of a UI policy issue
2125 if (route == _master_out) {
2126 _master_out = boost::shared_ptr<Route> ();
2129 if (route == _monitor_out) {
2131 /* cancel control outs for all routes */
2133 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2134 (*r)->drop_listen (_monitor_out);
2137 _monitor_out.reset ();
2140 /* writer goes out of scope, forces route list update */
2143 update_route_solo_state ();
2145 // We need to disconnect the route's inputs and outputs
2147 route->input()->disconnect (0);
2148 route->output()->disconnect (0);
2150 /* if the route had internal sends sending to it, remove them */
2151 if (route->internal_return()) {
2153 boost::shared_ptr<RouteList> r = routes.reader ();
2154 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2155 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2157 (*i)->remove_processor (s);
2162 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2163 if (mt && mt->step_editing()) {
2164 if (_step_editors > 0) {
2169 update_latency_compensation ();
2172 /* Re-sort routes to remove the graph's current references to the one that is
2173 * going away, then flush old references out of the graph.
2177 route_graph->clear_other_chain ();
2179 /* get rid of it from the dead wood collection in the route list manager */
2181 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2185 /* try to cause everyone to drop their references */
2187 route->drop_references ();
2189 sync_order_keys (N_("session"));
2191 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2193 /* save the new state of the world */
2195 if (save_state (_current_snapshot_name)) {
2196 save_history (_current_snapshot_name);
2201 Session::route_mute_changed (void* /*src*/)
2207 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2209 boost::shared_ptr<Route> route = wpr.lock();
2211 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2215 if (route->listening_via_monitor ()) {
2217 if (Config->get_exclusive_solo()) {
2218 /* new listen: disable all other listen */
2219 boost::shared_ptr<RouteList> r = routes.reader ();
2220 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2221 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2224 (*i)->set_listen (false, this);
2230 } else if (_listen_cnt > 0) {
2235 update_route_solo_state ();
2238 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2240 boost::shared_ptr<Route> route = wpr.lock ();
2243 /* should not happen */
2244 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2248 bool send_changed = false;
2250 if (route->solo_isolated()) {
2251 if (_solo_isolated_cnt == 0) {
2252 send_changed = true;
2254 _solo_isolated_cnt++;
2255 } else if (_solo_isolated_cnt > 0) {
2256 _solo_isolated_cnt--;
2257 if (_solo_isolated_cnt == 0) {
2258 send_changed = true;
2263 IsolatedChanged (); /* EMIT SIGNAL */
2268 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2270 DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2272 if (!self_solo_change) {
2273 // session doesn't care about changes to soloed-by-others
2277 if (solo_update_disabled) {
2279 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2283 boost::shared_ptr<Route> route = wpr.lock ();
2286 boost::shared_ptr<RouteList> r = routes.reader ();
2289 if (route->self_soloed()) {
2295 RouteGroup* rg = route->route_group ();
2296 bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2298 if (delta == 1 && Config->get_exclusive_solo()) {
2300 /* new solo: disable all other solos, but not the group if its solo-enabled */
2302 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2303 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden() ||
2304 (leave_group_alone && ((*i)->route_group() == rg))) {
2307 (*i)->set_solo (false, this);
2311 DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2313 solo_update_disabled = true;
2315 RouteList uninvolved;
2317 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2319 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2320 bool via_sends_only;
2321 bool in_signal_flow;
2323 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden() ||
2324 (leave_group_alone && ((*i)->route_group() == rg))) {
2328 in_signal_flow = false;
2330 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2332 if ((*i)->feeds (route, &via_sends_only)) {
2333 if (!via_sends_only) {
2334 if (!route->soloed_by_others_upstream()) {
2335 (*i)->mod_solo_by_others_downstream (delta);
2338 in_signal_flow = true;
2340 DEBUG_TRACE (DEBUG::Solo, "\tno feed from\n");
2343 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2345 if (route->feeds (*i, &via_sends_only)) {
2346 /* propagate solo upstream only if routing other than
2347 sends is involved, but do consider the other route
2348 (*i) to be part of the signal flow even if only
2351 DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2355 route->soloed_by_others_downstream(),
2356 route->soloed_by_others_upstream()));
2357 if (!via_sends_only) {
2358 if (!route->soloed_by_others_downstream()) {
2359 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2360 (*i)->mod_solo_by_others_upstream (delta);
2363 in_signal_flow = true;
2365 DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2368 if (!in_signal_flow) {
2369 uninvolved.push_back (*i);
2373 solo_update_disabled = false;
2374 DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2376 update_route_solo_state (r);
2378 /* now notify that the mute state of the routes not involved in the signal
2379 pathway of the just-solo-changed route may have altered.
2382 for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2383 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1\n", (*i)->name()));
2384 (*i)->mute_changed (this);
2387 SoloChanged (); /* EMIT SIGNAL */
2392 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2394 /* now figure out if anything that matters is soloed (or is "listening")*/
2396 bool something_soloed = false;
2397 uint32_t listeners = 0;
2398 uint32_t isolated = 0;
2401 r = routes.reader();
2404 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2405 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2406 something_soloed = true;
2409 if (!(*i)->is_hidden() && (*i)->listening_via_monitor()) {
2410 if (Config->get_solo_control_is_listen_control()) {
2413 (*i)->set_listen (false, this);
2417 if ((*i)->solo_isolated()) {
2422 if (something_soloed != _non_soloed_outs_muted) {
2423 _non_soloed_outs_muted = something_soloed;
2424 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2427 _listen_cnt = listeners;
2429 if (isolated != _solo_isolated_cnt) {
2430 _solo_isolated_cnt = isolated;
2431 IsolatedChanged (); /* EMIT SIGNAL */
2435 boost::shared_ptr<RouteList>
2436 Session::get_routes_with_internal_returns() const
2438 boost::shared_ptr<RouteList> r = routes.reader ();
2439 boost::shared_ptr<RouteList> rl (new RouteList);
2441 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2442 if ((*i)->internal_return ()) {
2450 Session::io_name_is_legal (const std::string& name)
2452 boost::shared_ptr<RouteList> r = routes.reader ();
2454 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2455 if ((*i)->name() == name) {
2459 if ((*i)->has_io_processor_named (name)) {
2468 Session::set_exclusive_input_active (boost::shared_ptr<Route> rt, bool /*others_on*/)
2471 vector<string> connections;
2473 PortSet& ps (rt->input()->ports());
2475 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2476 p->get_connections (connections);
2479 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2480 routes_using_input_from (*s, rl);
2483 /* scan all relevant routes to see if others are on or off */
2485 bool others_are_already_on = false;
2487 for (RouteList::iterator r = rl.begin(); r != rl.end(); ++r) {
2489 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2491 if (mt->input_active()) {
2492 others_are_already_on = true;
2499 /* globally reverse other routes */
2501 for (RouteList::iterator r = rl.begin(); r != rl.end(); ++r) {
2503 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2505 mt->set_input_active (!others_are_already_on);
2512 Session::routes_using_input_from (const string& str, RouteList& rl)
2514 boost::shared_ptr<RouteList> r = routes.reader ();
2516 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2517 if ((*i)->input()->connected_to (str)) {
2523 boost::shared_ptr<Route>
2524 Session::route_by_name (string name)
2526 boost::shared_ptr<RouteList> r = routes.reader ();
2528 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2529 if ((*i)->name() == name) {
2534 return boost::shared_ptr<Route> ((Route*) 0);
2537 boost::shared_ptr<Route>
2538 Session::route_by_id (PBD::ID id)
2540 boost::shared_ptr<RouteList> r = routes.reader ();
2542 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2543 if ((*i)->id() == id) {
2548 return boost::shared_ptr<Route> ((Route*) 0);
2551 boost::shared_ptr<Route>
2552 Session::route_by_remote_id (uint32_t id)
2554 boost::shared_ptr<RouteList> r = routes.reader ();
2556 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2557 if ((*i)->remote_control_id() == id) {
2562 return boost::shared_ptr<Route> ((Route*) 0);
2566 Session::playlist_region_added (boost::weak_ptr<Region> w)
2568 boost::shared_ptr<Region> r = w.lock ();
2573 /* These are the operations that are currently in progress... */
2574 list<GQuark> curr = _current_trans_quarks;
2577 /* ...and these are the operations during which we want to update
2578 the session range location markers.
2581 ops.push_back (Operations::capture);
2582 ops.push_back (Operations::paste);
2583 ops.push_back (Operations::duplicate_region);
2584 ops.push_back (Operations::insert_file);
2585 ops.push_back (Operations::insert_region);
2586 ops.push_back (Operations::drag_region_brush);
2587 ops.push_back (Operations::region_drag);
2588 ops.push_back (Operations::selection_grab);
2589 ops.push_back (Operations::region_fill);
2590 ops.push_back (Operations::fill_selection);
2591 ops.push_back (Operations::create_region);
2592 ops.push_back (Operations::region_copy);
2593 ops.push_back (Operations::fixed_time_region_copy);
2596 /* See if any of the current operations match the ones that we want */
2598 set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
2600 /* If so, update the session range markers */
2602 maybe_update_session_range (r->position (), r->last_frame ());
2606 /** Update the session range markers if a is before the current start or
2607 * b is after the current end.
2610 Session::maybe_update_session_range (framepos_t a, framepos_t b)
2612 if (_state_of_the_state & Loading) {
2616 if (_session_range_location == 0) {
2618 add_session_range_location (a, b);
2622 if (a < _session_range_location->start()) {
2623 _session_range_location->set_start (a);
2626 if (b > _session_range_location->end()) {
2627 _session_range_location->set_end (b);
2633 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
2635 for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
2636 maybe_update_session_range (i->to, i->to + i->length);
2641 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
2643 for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
2644 maybe_update_session_range (i->from, i->to);
2648 /* Region management */
2650 boost::shared_ptr<Region>
2651 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2653 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2654 RegionFactory::RegionMap::const_iterator i;
2655 boost::shared_ptr<Region> region;
2657 Glib::Mutex::Lock lm (region_lock);
2659 for (i = regions.begin(); i != regions.end(); ++i) {
2663 if (region->whole_file()) {
2665 if (child->source_equivalent (region)) {
2671 return boost::shared_ptr<Region> ();
2675 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
2677 set<boost::shared_ptr<Region> > relevant_regions;
2679 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
2680 RegionFactory::get_regions_using_source (*s, relevant_regions);
2683 for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
2684 set<boost::shared_ptr<Region> >::iterator tmp;
2689 playlists->destroy_region (*r);
2690 RegionFactory::map_remove (*r);
2692 (*r)->drop_sources ();
2693 (*r)->drop_references ();
2695 relevant_regions.erase (r);
2700 for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
2703 Glib::Mutex::Lock ls (source_lock);
2704 /* remove from the main source list */
2705 sources.erase ((*s)->id());
2708 (*s)->mark_for_remove ();
2709 (*s)->drop_references ();
2718 Session::remove_last_capture ()
2720 list<boost::shared_ptr<Source> > srcs;
2722 boost::shared_ptr<RouteList> rl = routes.reader ();
2723 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2724 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2729 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
2732 srcs.insert (srcs.end(), l.begin(), l.end());
2737 destroy_sources (srcs);
2739 save_state (_current_snapshot_name);
2744 /* Source Management */
2747 Session::add_source (boost::shared_ptr<Source> source)
2749 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2750 pair<SourceMap::iterator,bool> result;
2752 entry.first = source->id();
2753 entry.second = source;
2756 Glib::Mutex::Lock lm (source_lock);
2757 result = sources.insert (entry);
2760 if (result.second) {
2762 /* yay, new source */
2766 boost::shared_ptr<AudioFileSource> afs;
2768 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2769 if (Config->get_auto_analyse_audio()) {
2770 Analyser::queue_source_for_analysis (source, false);
2774 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
2779 Session::remove_source (boost::weak_ptr<Source> src)
2781 if (_state_of_the_state & Deletion) {
2785 SourceMap::iterator i;
2786 boost::shared_ptr<Source> source = src.lock();
2793 Glib::Mutex::Lock lm (source_lock);
2795 if ((i = sources.find (source->id())) != sources.end()) {
2800 if (!_state_of_the_state & InCleanup) {
2802 /* save state so we don't end up with a session file
2803 referring to non-existent sources.
2806 save_state (_current_snapshot_name);
2810 boost::shared_ptr<Source>
2811 Session::source_by_id (const PBD::ID& id)
2813 Glib::Mutex::Lock lm (source_lock);
2814 SourceMap::iterator i;
2815 boost::shared_ptr<Source> source;
2817 if ((i = sources.find (id)) != sources.end()) {
2824 boost::shared_ptr<Source>
2825 Session::source_by_path_and_channel (const string& path, uint16_t chn)
2827 Glib::Mutex::Lock lm (source_lock);
2829 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2830 boost::shared_ptr<AudioFileSource> afs
2831 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2833 if (afs && afs->path() == path && chn == afs->channel()) {
2837 return boost::shared_ptr<Source>();
2841 Session::count_sources_by_origin (const string& path)
2844 Glib::Mutex::Lock lm (source_lock);
2846 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2847 boost::shared_ptr<FileSource> fs
2848 = boost::dynamic_pointer_cast<FileSource>(i->second);
2850 if (fs && fs->origin() == path) {
2860 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2863 string old_basename = PBD::basename_nosuffix (oldname);
2864 string new_legalized = legalize_for_path (newname);
2866 /* note: we know (or assume) the old path is already valid */
2870 /* destructive file sources have a name of the form:
2872 /path/to/Tnnnn-NAME(%[LR])?.wav
2874 the task here is to replace NAME with the new name.
2879 string::size_type dash;
2881 dir = Glib::path_get_dirname (path);
2882 path = Glib::path_get_basename (path);
2884 /* '-' is not a legal character for the NAME part of the path */
2886 if ((dash = path.find_last_of ('-')) == string::npos) {
2890 prefix = path.substr (0, dash);
2894 path += new_legalized;
2895 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
2896 path = Glib::build_filename (dir, path);
2900 /* non-destructive file sources have a name of the form:
2902 /path/to/NAME-nnnnn(%[LR])?.ext
2904 the task here is to replace NAME with the new name.
2909 string::size_type dash;
2910 string::size_type postfix;
2912 dir = Glib::path_get_dirname (path);
2913 path = Glib::path_get_basename (path);
2915 /* '-' is not a legal character for the NAME part of the path */
2917 if ((dash = path.find_last_of ('-')) == string::npos) {
2921 suffix = path.substr (dash+1);
2923 // Suffix is now everything after the dash. Now we need to eliminate
2924 // the nnnnn part, which is done by either finding a '%' or a '.'
2926 postfix = suffix.find_last_of ("%");
2927 if (postfix == string::npos) {
2928 postfix = suffix.find_last_of ('.');
2931 if (postfix != string::npos) {
2932 suffix = suffix.substr (postfix);
2934 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2938 const uint32_t limit = 10000;
2939 char buf[PATH_MAX+1];
2941 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2943 snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
2945 if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
2946 path = Glib::build_filename (dir, buf);
2954 fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
2963 /** Return the full path (in some session directory) for a new within-session source.
2964 * \a name must be a session-unique name that does not contain slashes
2965 * (e.g. as returned by new_*_source_name)
2968 Session::new_source_path_from_name (DataType type, const string& name)
2970 assert(name.find("/") == string::npos);
2972 SessionDirectory sdir(get_best_session_directory_for_new_source());
2975 if (type == DataType::AUDIO) {
2976 p = sdir.sound_path();
2977 } else if (type == DataType::MIDI) {
2978 p = sdir.midi_path();
2980 error << "Unknown source type, unable to create file path" << endmsg;
2985 return p.to_string();
2989 Session::peak_path (string base) const
2991 sys::path peakfile_path(_session_dir->peak_path());
2992 peakfile_path /= base + peakfile_suffix;
2993 return peakfile_path.to_string();
2996 /** Return a unique name based on \a base for a new internal audio source */
2998 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3001 char buf[PATH_MAX+1];
3002 const uint32_t limit = 10000;
3004 string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3007 legalized = legalize_for_path (base);
3009 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3010 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3012 vector<space_and_path>::iterator i;
3013 uint32_t existing = 0;
3015 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3020 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3021 cnt, legalized.c_str(), ext.c_str());
3022 } else if (nchan == 2) {
3024 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
3025 cnt, legalized.c_str(), ext.c_str());
3027 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
3028 cnt, legalized.c_str(), ext.c_str());
3030 } else if (nchan < 26) {
3031 snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
3032 cnt, legalized.c_str(), 'a' + chan, ext.c_str());
3034 snprintf (buf, sizeof(buf), "T%04d-%s%s",
3035 cnt, legalized.c_str(), ext.c_str());
3041 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3042 } else if (nchan == 2) {
3044 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
3046 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
3048 } else if (nchan < 26) {
3049 snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
3051 snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
3055 SessionDirectory sdir((*i).path);
3057 string spath = sdir.sound_path().to_string();
3059 /* note that we search *without* the extension so that
3060 we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3061 in the event that this new name is required for
3062 a file format change.
3065 if (matching_unsuffixed_filename_exists_in (spath, buf)) {
3071 if (existing == 0) {
3076 error << string_compose(
3077 _("There are already %1 recordings for %2, which I consider too many."),
3078 limit, base) << endmsg;
3080 throw failed_constructor();
3084 return Glib::path_get_basename (buf);
3087 /** Create a new within-session audio source */
3088 boost::shared_ptr<AudioFileSource>
3089 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
3091 const string name = new_audio_source_name (n, n_chans, chan, destructive);
3092 const string path = new_source_path_from_name(DataType::AUDIO, name);
3094 return boost::dynamic_pointer_cast<AudioFileSource> (
3095 SourceFactory::createWritable (DataType::AUDIO, *this, path, string(), destructive, frame_rate()));
3098 /** Return a unique name based on \a base for a new internal MIDI source */
3100 Session::new_midi_source_name (const string& base)
3103 char buf[PATH_MAX+1];
3104 const uint32_t limit = 10000;
3108 legalized = legalize_for_path (base);
3110 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3111 for (cnt = 1; cnt <= limit; ++cnt) {
3113 vector<space_and_path>::iterator i;
3114 uint32_t existing = 0;
3116 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3118 SessionDirectory sdir((*i).path);
3120 sys::path p = sdir.midi_path();
3123 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
3125 if (sys::exists (buf)) {
3130 if (existing == 0) {
3135 error << string_compose(
3136 _("There are already %1 recordings for %2, which I consider too many."),
3137 limit, base) << endmsg;
3139 throw failed_constructor();
3143 return Glib::path_get_basename(buf);
3147 /** Create a new within-session MIDI source */
3148 boost::shared_ptr<MidiSource>
3149 Session::create_midi_source_for_session (Track* track, string const & n)
3151 /* try to use the existing write source for the track, to keep numbering sane
3155 /*MidiTrack* mt = dynamic_cast<Track*> (track);
3159 list<boost::shared_ptr<Source> > l = track->steal_write_sources ();
3162 assert (boost::dynamic_pointer_cast<MidiSource> (l.front()));
3163 return boost::dynamic_pointer_cast<MidiSource> (l.front());
3167 const string name = new_midi_source_name (n);
3168 const string path = new_source_path_from_name (DataType::MIDI, name);
3170 return boost::dynamic_pointer_cast<SMFSource> (
3171 SourceFactory::createWritable (
3172 DataType::MIDI, *this, path, string(), false, frame_rate()));
3177 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3179 if (playlist->hidden()) {
3183 playlists->add (playlist);
3186 playlist->release();
3193 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3195 if (_state_of_the_state & Deletion) {
3199 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3205 playlists->remove (playlist);
3211 Session::set_audition (boost::shared_ptr<Region> r)
3213 pending_audition_region = r;
3214 add_post_transport_work (PostTransportAudition);
3215 _butler->schedule_transport_work ();
3219 Session::audition_playlist ()
3221 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3222 ev->region.reset ();
3227 Session::non_realtime_set_audition ()
3229 if (!pending_audition_region) {
3230 auditioner->audition_current_playlist ();
3232 auditioner->audition_region (pending_audition_region);
3233 pending_audition_region.reset ();
3235 AuditionActive (true); /* EMIT SIGNAL */
3239 Session::audition_region (boost::shared_ptr<Region> r)
3241 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3247 Session::cancel_audition ()
3249 if (auditioner->auditioning()) {
3250 auditioner->cancel_audition ();
3251 AuditionActive (false); /* EMIT SIGNAL */
3256 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3258 if (a->is_monitor()) {
3261 if (b->is_monitor()) {
3264 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3268 Session::is_auditioning () const
3270 /* can be called before we have an auditioner object */
3272 return auditioner->auditioning();
3279 Session::graph_reordered ()
3281 /* don't do this stuff if we are setting up connections
3282 from a set_state() call or creating new tracks. Ditto for deletion.
3285 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3289 /* every track/bus asked for this to be handled but it was deferred because
3290 we were connecting. do it now.
3293 request_input_change_handling ();
3297 /* force all diskstreams to update their capture offset values to
3298 reflect any changes in latencies within the graph.
3301 boost::shared_ptr<RouteList> rl = routes.reader ();
3302 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3303 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3305 tr->set_capture_offset ();
3311 Session::available_capture_duration ()
3313 float sample_bytes_on_disk = 4.0; // keep gcc happy
3315 switch (config.get_native_file_data_format()) {
3317 sample_bytes_on_disk = 4.0;
3321 sample_bytes_on_disk = 3.0;
3325 sample_bytes_on_disk = 2.0;
3329 /* impossible, but keep some gcc versions happy */
3330 fatal << string_compose (_("programming error: %1"),
3331 X_("illegal native file data format"))
3336 double scale = 4096.0 / sample_bytes_on_disk;
3338 if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3339 return max_framecnt;
3342 return (framecnt_t) floor (_total_free_4k_blocks * scale);
3346 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3349 RCUWriter<BundleList> writer (_bundles);
3350 boost::shared_ptr<BundleList> b = writer.get_copy ();
3351 b->push_back (bundle);
3354 BundleAdded (bundle); /* EMIT SIGNAL */
3360 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3362 bool removed = false;
3365 RCUWriter<BundleList> writer (_bundles);
3366 boost::shared_ptr<BundleList> b = writer.get_copy ();
3367 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3369 if (i != b->end()) {
3376 BundleRemoved (bundle); /* EMIT SIGNAL */
3382 boost::shared_ptr<Bundle>
3383 Session::bundle_by_name (string name) const
3385 boost::shared_ptr<BundleList> b = _bundles.reader ();
3387 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3388 if ((*i)->name() == name) {
3393 return boost::shared_ptr<Bundle> ();
3397 Session::tempo_map_changed (const PropertyChange&)
3401 playlists->update_after_tempo_map_change ();
3403 _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3409 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3411 for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3412 (*i)->recompute_frames_from_bbt ();
3416 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3417 * the given count with the current block size.
3420 Session::ensure_buffers (ChanCount howmany)
3422 BufferManager::ensure_buffers (howmany);
3426 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3428 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3429 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3434 Session::next_insert_id ()
3436 /* this doesn't really loop forever. just think about it */
3439 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3440 if (!insert_bitset[n]) {
3441 insert_bitset[n] = true;
3447 /* none available, so resize and try again */
3449 insert_bitset.resize (insert_bitset.size() + 16, false);
3454 Session::next_send_id ()
3456 /* this doesn't really loop forever. just think about it */
3459 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3460 if (!send_bitset[n]) {
3461 send_bitset[n] = true;
3467 /* none available, so resize and try again */
3469 send_bitset.resize (send_bitset.size() + 16, false);
3474 Session::next_return_id ()
3476 /* this doesn't really loop forever. just think about it */
3479 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3480 if (!return_bitset[n]) {
3481 return_bitset[n] = true;
3487 /* none available, so resize and try again */
3489 return_bitset.resize (return_bitset.size() + 16, false);
3494 Session::mark_send_id (uint32_t id)
3496 if (id >= send_bitset.size()) {
3497 send_bitset.resize (id+16, false);
3499 if (send_bitset[id]) {
3500 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3502 send_bitset[id] = true;
3506 Session::mark_return_id (uint32_t id)
3508 if (id >= return_bitset.size()) {
3509 return_bitset.resize (id+16, false);
3511 if (return_bitset[id]) {
3512 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3514 return_bitset[id] = true;
3518 Session::mark_insert_id (uint32_t id)
3520 if (id >= insert_bitset.size()) {
3521 insert_bitset.resize (id+16, false);
3523 if (insert_bitset[id]) {
3524 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3526 insert_bitset[id] = true;
3530 Session::unmark_send_id (uint32_t id)
3532 if (id < send_bitset.size()) {
3533 send_bitset[id] = false;
3538 Session::unmark_return_id (uint32_t id)
3540 if (id < return_bitset.size()) {
3541 return_bitset[id] = false;
3546 Session::unmark_insert_id (uint32_t id)
3548 if (id < insert_bitset.size()) {
3549 insert_bitset[id] = false;
3554 /* Named Selection management */
3556 boost::shared_ptr<NamedSelection>
3557 Session::named_selection_by_name (string name)
3559 Glib::Mutex::Lock lm (named_selection_lock);
3560 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3561 if ((*i)->name == name) {
3565 return boost::shared_ptr<NamedSelection>();
3569 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3572 Glib::Mutex::Lock lm (named_selection_lock);
3573 named_selections.insert (named_selections.begin(), named_selection);
3578 NamedSelectionAdded (); /* EMIT SIGNAL */
3582 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3584 bool removed = false;
3587 Glib::Mutex::Lock lm (named_selection_lock);
3589 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3591 if (i != named_selections.end()) {
3592 named_selections.erase (i);
3599 NamedSelectionRemoved (); /* EMIT SIGNAL */
3604 Session::reset_native_file_format ()
3606 boost::shared_ptr<RouteList> rl = routes.reader ();
3607 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3608 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3610 /* don't save state as we do this, there's no point
3613 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
3614 tr->reset_write_sources (false);
3615 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
3621 Session::route_name_unique (string n) const
3623 boost::shared_ptr<RouteList> r = routes.reader ();
3625 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3626 if ((*i)->name() == n) {
3635 Session::route_name_internal (string n) const
3637 if (auditioner && auditioner->name() == n) {
3641 if (_click_io && _click_io->name() == n) {
3649 Session::freeze_all (InterThreadInfo& itt)
3651 boost::shared_ptr<RouteList> r = routes.reader ();
3653 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3655 boost::shared_ptr<Track> t;
3657 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3658 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3668 boost::shared_ptr<Region>
3669 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
3670 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3671 InterThreadInfo& itt, bool enable_processing)
3673 boost::shared_ptr<Region> result;
3674 boost::shared_ptr<Playlist> playlist;
3675 boost::shared_ptr<AudioFileSource> fsource;
3677 char buf[PATH_MAX+1];
3678 ChanCount diskstream_channels (track.n_channels());
3679 framepos_t position;
3680 framecnt_t this_chunk;
3683 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3684 const string sound_dir = sdir.sound_path().to_string();
3685 framepos_t len = end - start;
3686 bool need_block_size_reset = false;
3688 ChanCount const max_proc = track.max_processor_streams ();
3691 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3692 end, start) << endmsg;
3696 const framecnt_t chunk_size = (256 * 1024)/4;
3698 // block all process callback handling
3700 block_processing ();
3702 /* call tree *MUST* hold route_lock */
3704 if ((playlist = track.playlist()) == 0) {
3708 /* external redirects will be a problem */
3710 if (track.has_external_redirects()) {
3714 ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3716 for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
3718 for (x = 0; x < 99999; ++x) {
3719 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 "%s", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1, ext.c_str());
3720 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
3726 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3731 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3732 SourceFactory::createWritable (DataType::AUDIO, *this, buf, string(), false, frame_rate()));
3735 catch (failed_constructor& err) {
3736 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3740 srcs.push_back (fsource);
3743 /* tell redirects that care that we are about to use a much larger blocksize */
3745 need_block_size_reset = true;
3746 track.set_block_size (chunk_size);
3748 /* XXX need to flush all redirects */
3753 /* create a set of reasonably-sized buffers */
3754 buffers.ensure_buffers (DataType::AUDIO, max_proc.n_audio(), chunk_size);
3755 buffers.set_count (max_proc);
3757 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3758 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3760 afs->prepare_for_peakfile_writes ();
3763 while (to_do && !itt.cancel) {
3765 this_chunk = min (to_do, chunk_size);
3767 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3772 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3773 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3776 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3782 start += this_chunk;
3783 to_do -= this_chunk;
3785 itt.progress = (float) (1.0 - ((double) to_do / len));
3794 xnow = localtime (&now);
3796 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3797 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3800 afs->update_header (position, *xnow, now);
3801 afs->flush_header ();
3805 /* construct a region to represent the bounced material */
3809 plist.add (Properties::start, 0);
3810 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3811 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3813 result = RegionFactory::create (srcs, plist);
3819 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3820 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3823 afs->mark_for_remove ();
3826 (*src)->drop_references ();
3830 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3831 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3834 afs->done_with_peakfile_writes ();
3839 if (need_block_size_reset) {
3840 track.set_block_size (get_block_size());
3843 unblock_processing ();
3849 Session::gain_automation_buffer() const
3851 return ProcessThread::gain_automation_buffer ();
3855 Session::pan_automation_buffer() const
3857 return ProcessThread::pan_automation_buffer ();
3861 Session::get_silent_buffers (ChanCount count)
3863 return ProcessThread::get_silent_buffers (count);
3867 Session::get_scratch_buffers (ChanCount count)
3869 return ProcessThread::get_scratch_buffers (count);
3873 Session::get_mix_buffers (ChanCount count)
3875 return ProcessThread::get_mix_buffers (count);
3879 Session::ntracks () const
3882 boost::shared_ptr<RouteList> r = routes.reader ();
3884 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3885 if (boost::dynamic_pointer_cast<Track> (*i)) {
3894 Session::nbusses () const
3897 boost::shared_ptr<RouteList> r = routes.reader ();
3899 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3900 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3909 Session::add_automation_list(AutomationList *al)
3911 automation_lists[al->id()] = al;
3915 Session::sync_order_keys (std::string const & base)
3917 if (deletion_in_progress()) {
3921 if (!Config->get_sync_all_route_ordering()) {
3922 /* leave order keys as they are */
3926 boost::shared_ptr<RouteList> r = routes.reader ();
3928 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3929 (*i)->sync_order_keys (base);
3932 Route::SyncOrderKeys (base); // EMIT SIGNAL
3934 /* this might not do anything */
3936 set_remote_control_ids ();
3939 /** @return true if there is at least one record-enabled track, otherwise false */
3941 Session::have_rec_enabled_track () const
3943 return g_atomic_int_get (&_have_rec_enabled_track) == 1;
3946 /** Update the state of our rec-enabled tracks flag */
3948 Session::update_have_rec_enabled_track ()
3950 boost::shared_ptr<RouteList> rl = routes.reader ();
3951 RouteList::iterator i = rl->begin();
3952 while (i != rl->end ()) {
3954 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3955 if (tr && tr->record_enabled ()) {
3962 int const old = g_atomic_int_get (&_have_rec_enabled_track);
3964 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
3966 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
3967 RecordStateChanged (); /* EMIT SIGNAL */
3972 Session::listen_position_changed ()
3974 boost::shared_ptr<RouteList> r = routes.reader ();
3976 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3977 (*i)->listen_position_changed ();
3982 Session::solo_control_mode_changed ()
3984 /* cancel all solo or all listen when solo control mode changes */
3987 set_solo (get_routes(), false);
3988 } else if (listening()) {
3989 set_listen (get_routes(), false);
3993 /** Called when a property of one of our route groups changes */
3995 Session::route_group_property_changed (RouteGroup* rg)
3997 RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4000 /** Called when a route is added to one of our route groups */
4002 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4004 RouteAddedToRouteGroup (rg, r);
4007 /** Called when a route is removed from one of our route groups */
4009 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4011 RouteRemovedFromRouteGroup (rg, r);
4015 Session::get_available_sync_options () const
4017 vector<SyncSource> ret;
4019 ret.push_back (JACK);
4020 ret.push_back (MTC);
4021 ret.push_back (MIDIClock);
4026 boost::shared_ptr<RouteList>
4027 Session::get_routes_with_regions_at (framepos_t const p) const
4029 boost::shared_ptr<RouteList> r = routes.reader ();
4030 boost::shared_ptr<RouteList> rl (new RouteList);
4032 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4033 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4038 boost::shared_ptr<Playlist> pl = tr->playlist ();
4043 if (pl->has_region_at (p)) {
4052 Session::goto_end ()
4054 if (_session_range_location) {
4055 request_locate (_session_range_location->end(), false);
4057 request_locate (0, false);
4062 Session::goto_start ()
4064 if (_session_range_location) {
4065 request_locate (_session_range_location->start(), false);
4067 request_locate (0, false);
4072 Session::current_start_frame () const
4074 return _session_range_location ? _session_range_location->start() : 0;
4078 Session::current_end_frame () const
4080 return _session_range_location ? _session_range_location->end() : 0;
4084 Session::add_session_range_location (framepos_t start, framepos_t end)
4086 _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4087 _locations->add (_session_range_location);
4090 /** Called when one of our routes' order keys has changed */
4092 Session::route_order_key_changed ()
4094 RouteOrderKeyChanged (); /* EMIT SIGNAL */
4098 Session::step_edit_status_change (bool yn)
4104 send = (_step_editors == 0);
4109 send = (_step_editors == 1);
4112 if (_step_editors > 0) {
4118 StepEditStatusChange (val);
4124 Session::start_time_changed (framepos_t old)
4126 /* Update the auto loop range to match the session range
4127 (unless the auto loop range has been changed by the user)
4130 Location* s = _locations->session_range_location ();
4135 Location* l = _locations->auto_loop_location ();
4137 if (l->start() == old) {
4138 l->set_start (s->start(), true);
4143 Session::end_time_changed (framepos_t old)
4145 /* Update the auto loop range to match the session range
4146 (unless the auto loop range has been changed by the user)
4149 Location* s = _locations->session_range_location ();
4154 Location* l = _locations->auto_loop_location ();
4156 if (l && l->end() == old) {
4157 l->set_end (s->end(), true);
4162 Session::source_search_path (DataType type) const
4166 if (session_dirs.size() == 1) {
4168 case DataType::AUDIO:
4169 search_path = _session_dir->sound_path().to_string();
4171 case DataType::MIDI:
4172 search_path = _session_dir->midi_path().to_string();
4176 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4177 SessionDirectory sdir (i->path);
4178 if (!search_path.empty()) {
4182 case DataType::AUDIO:
4183 search_path += sdir.sound_path().to_string();
4185 case DataType::MIDI:
4186 search_path += sdir.midi_path().to_string();
4192 /* now add user-specified locations
4195 vector<string> dirs;
4198 case DataType::AUDIO:
4199 split (config.get_audio_search_path (), dirs, ':');
4201 case DataType::MIDI:
4202 split (config.get_midi_search_path (), dirs, ':');
4206 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4216 Session::ensure_search_path_includes (const string& path, DataType type)
4219 vector<string> dirs;
4226 case DataType::AUDIO:
4227 search_path = config.get_audio_search_path ();
4229 case DataType::MIDI:
4230 search_path = config.get_midi_search_path ();
4234 split (search_path, dirs, ':');
4236 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
4242 if (!search_path.empty()) {
4246 search_path += path;
4249 case DataType::AUDIO:
4250 config.set_audio_search_path (search_path);
4252 case DataType::MIDI:
4253 config.set_midi_search_path (search_path);
4258 boost::shared_ptr<Speakers>
4259 Session::get_speakers()
4265 Session::unknown_processors () const
4269 boost::shared_ptr<RouteList> r = routes.reader ();
4270 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4271 list<string> t = (*i)->unknown_processors ();
4272 copy (t.begin(), t.end(), back_inserter (p));
4282 Session::update_latency (bool playback)
4284 DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4286 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4290 boost::shared_ptr<RouteList> r = routes.reader ();
4291 framecnt_t max_latency = 0;
4294 /* reverse the list so that we work backwards from the last route to run to the first */
4295 RouteList* rl = routes.reader().get();
4296 r.reset (new RouteList (*rl));
4297 reverse (r->begin(), r->end());
4300 /* compute actual latency values for the given direction and store them all in per-port
4301 structures. this will also publish the same values (to JACK) so that computation of latency
4302 for routes can consistently use public latency values.
4305 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4306 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4309 /* because we latency compensate playback, our published playback latencies should
4310 be the same for all output ports - all material played back by ardour has
4311 the same latency, whether its caused by plugins or by latency compensation. since
4312 these may differ from the values computed above, reset all playback port latencies
4316 DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4318 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4319 (*i)->set_public_port_latencies (max_latency, playback);
4324 post_playback_latency ();
4328 post_capture_latency ();
4331 DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4335 Session::post_playback_latency ()
4337 set_worst_playback_latency ();
4339 boost::shared_ptr<RouteList> r = routes.reader ();
4341 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4342 if (!(*i)->is_hidden() && ((*i)->active())) {
4343 _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4347 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4348 (*i)->set_latency_compensation (_worst_track_latency);
4353 Session::post_capture_latency ()
4355 set_worst_capture_latency ();
4357 /* reflect any changes in capture latencies into capture offsets
4360 boost::shared_ptr<RouteList> rl = routes.reader();
4361 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4362 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4364 tr->set_capture_offset ();
4370 Session::initialize_latencies ()
4373 Glib::Mutex::Lock lm (_engine.process_lock());
4374 update_latency (false);
4375 update_latency (true);
4378 set_worst_io_latencies ();
4382 Session::set_worst_io_latencies ()
4384 set_worst_playback_latency ();
4385 set_worst_capture_latency ();
4389 Session::set_worst_playback_latency ()
4391 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4395 _worst_output_latency = 0;
4397 if (!_engine.connected()) {
4401 boost::shared_ptr<RouteList> r = routes.reader ();
4403 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4404 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4407 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4411 Session::set_worst_capture_latency ()
4413 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4417 _worst_input_latency = 0;
4419 if (!_engine.connected()) {
4423 boost::shared_ptr<RouteList> r = routes.reader ();
4425 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4426 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4429 DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4433 Session::update_latency_compensation (bool force_whole_graph)
4435 bool some_track_latency_changed = false;
4437 if (_state_of_the_state & (InitialConnecting|Deletion)) {
4441 DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4443 _worst_track_latency = 0;
4445 boost::shared_ptr<RouteList> r = routes.reader ();
4447 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4448 if (!(*i)->is_hidden() && ((*i)->active())) {
4450 if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4451 some_track_latency_changed = true;
4453 _worst_track_latency = max (tl, _worst_track_latency);
4457 DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4458 (some_track_latency_changed ? "yes" : "no")));
4460 DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4462 if (some_track_latency_changed || force_whole_graph) {
4463 _engine.update_latencies ();
4467 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4468 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4472 tr->set_capture_offset ();