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.
25 #include <cstdio> /* sprintf(3) ... grrr */
31 #include <glibmm/thread.h>
32 #include <glibmm/miscutils.h>
33 #include <glibmm/fileutils.h>
35 #include "pbd/error.h"
36 #include "pbd/boost_debug.h"
37 #include "pbd/pathscanner.h"
38 #include "pbd/stl_delete.h"
39 #include "pbd/basename.h"
40 #include "pbd/stacktrace.h"
41 #include "pbd/file_utils.h"
42 #include "pbd/convert.h"
44 #include "ardour/amp.h"
45 #include "ardour/analyser.h"
46 #include "ardour/audio_buffer.h"
47 #include "ardour/audio_diskstream.h"
48 #include "ardour/audio_port.h"
49 #include "ardour/audio_track.h"
50 #include "ardour/audioengine.h"
51 #include "ardour/audiofilesource.h"
52 #include "ardour/audioplaylist.h"
53 #include "ardour/audioregion.h"
54 #include "ardour/auditioner.h"
55 #include "ardour/buffer_manager.h"
56 #include "ardour/buffer_set.h"
57 #include "ardour/bundle.h"
58 #include "ardour/butler.h"
59 #include "ardour/click.h"
60 #include "ardour/configuration.h"
61 #include "ardour/crossfade.h"
62 #include "ardour/cycle_timer.h"
63 #include "ardour/data_type.h"
64 #include "ardour/debug.h"
65 #include "ardour/filename_extensions.h"
66 #include "ardour/internal_send.h"
67 #include "ardour/io_processor.h"
68 #include "ardour/midi_diskstream.h"
69 #include "ardour/midi_playlist.h"
70 #include "ardour/midi_region.h"
71 #include "ardour/midi_track.h"
72 #include "ardour/midi_ui.h"
73 #include "ardour/named_selection.h"
74 #include "ardour/process_thread.h"
75 #include "ardour/playlist.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/port_insert.h"
78 #include "ardour/processor.h"
79 #include "ardour/rc_configuration.h"
80 #include "ardour/recent_sessions.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/return.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_directory.h"
88 #include "ardour/session_metadata.h"
89 #include "ardour/session_playlists.h"
90 #include "ardour/slave.h"
91 #include "ardour/smf_source.h"
92 #include "ardour/source_factory.h"
93 #include "ardour/tape_file_matcher.h"
94 #include "ardour/tempo.h"
95 #include "ardour/utils.h"
97 #include "midi++/jack.h"
102 using namespace ARDOUR;
104 using boost::shared_ptr;
105 using boost::weak_ptr;
107 bool Session::_disable_all_loaded_plugins = false;
109 PBD::Signal1<void,std::string> Session::Dialog;
110 PBD::Signal0<int> Session::AskAboutPendingState;
111 PBD::Signal2<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
112 PBD::Signal0<void> Session::SendFeedback;
114 PBD::Signal0<void> Session::TimecodeOffsetChanged;
115 PBD::Signal0<void> Session::StartTimeChanged;
116 PBD::Signal0<void> Session::EndTimeChanged;
117 PBD::Signal0<void> Session::AutoBindingOn;
118 PBD::Signal0<void> Session::AutoBindingOff;
119 PBD::Signal2<void,std::string, std::string> Session::Exported;
120 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
122 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
123 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
125 Session::Session (AudioEngine &eng,
126 const string& fullpath,
127 const string& snapshot_name,
128 BusProfile* bus_profile,
132 _target_transport_speed (0.0),
133 _requested_return_frame (-1),
135 _mmc_port (default_mmc_port),
136 _mtc_port (default_mtc_port),
137 _midi_port (default_midi_port),
138 _midi_clock_port (default_midi_clock_port),
139 _session_dir (new SessionDirectory(fullpath)),
141 _butler (new Butler (*this)),
142 _post_transport_work (0),
143 _send_timecode_update (false),
144 routes (new RouteList),
145 _total_free_4k_blocks (0),
146 _bundles (new BundleList),
147 _bundle_xml_node (0),
150 click_emphasis_data (0),
152 _metadata (new SessionMetadata()),
153 _have_rec_enabled_track (false)
156 playlists.reset (new SessionPlaylists);
158 interpolation.add_channel_to (0, 0);
160 if (!eng.connected()) {
161 throw failed_constructor();
164 n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
165 n_physical_inputs = _engine.n_physical_inputs(DataType::AUDIO);
167 first_stage_init (fullpath, snapshot_name);
169 _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
172 if (create (mix_template, compute_initial_length(), bus_profile)) {
174 throw failed_constructor ();
178 if (second_stage_init ()) {
180 throw failed_constructor ();
183 store_recent_sessions(_name, _path);
185 bool was_dirty = dirty();
187 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
189 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
190 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
193 DirtyChanged (); /* EMIT SIGNAL */
207 vector<void*> debug_pointers;
209 /* if we got to here, leaving pending capture state around
213 remove_pending_capture_state ();
215 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
217 _engine.remove_session ();
219 /* clear history so that no references to objects are held any more */
223 /* clear state tree so that no references to objects are held any more */
227 /* reset dynamic state version back to default */
229 Stateful::loading_state_version = 0;
231 _butler->drop_references ();
233 delete midi_control_ui;
235 if (click_data != default_click) {
236 delete [] click_data;
239 if (click_emphasis_data != default_click_emphasis) {
240 delete [] click_emphasis_data;
245 /* clear out any pending dead wood from RCU managed objects */
250 AudioDiskstream::free_working_buffers();
252 /* tell everyone who is still standing that we're about to die */
255 /* tell everyone to drop references and delete objects as we go */
257 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
258 named_selections.clear ();
260 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
261 RegionFactory::delete_all_regions ();
263 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
265 /* reset these three references to special routes before we do the usual route delete thing */
268 _master_out.reset ();
269 _monitor_out.reset ();
272 RCUWriter<RouteList> writer (routes);
273 boost::shared_ptr<RouteList> r = writer.get_copy ();
275 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
276 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
277 (*i)->drop_references ();
281 /* writer goes out of scope and updates master */
285 boost::shared_ptr<RouteList> r = routes.reader ();
287 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
288 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
289 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
290 i->second->drop_references ();
295 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
296 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
301 Crossfade::set_buffer_size (0);
305 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
308 boost_debug_list_ptrs ();
310 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
314 Session::set_worst_io_latencies ()
316 _worst_output_latency = 0;
317 _worst_input_latency = 0;
319 if (!_engine.connected()) {
323 boost::shared_ptr<RouteList> r = routes.reader ();
325 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
326 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
327 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
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::set_worst_io_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 */
394 for (int physport = 0; physport < 2; ++physport) {
395 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
397 if (physical_output.length()) {
398 if (_click_io->add_port (physical_output, this)) {
399 // relax, even though its an error
404 if (_click_io->n_ports () > ChanCount::ZERO) {
405 _clicking = Config->get_clicking ();
410 catch (failed_constructor& err) {
411 error << _("cannot setup Click I/O") << endmsg;
414 BootMessage (_("Compute I/O Latencies"));
416 set_worst_io_latencies ();
419 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
422 BootMessage (_("Set up standard connections"));
424 /* Create a set of Bundle objects that map
425 to the physical I/O currently available. We create both
426 mono and stereo bundles, so that the common cases of mono
427 and stereo tracks get bundles to put in their mixer strip
428 in / out menus. There may be a nicer way of achieving that;
429 it doesn't really scale that well to higher channel counts
432 /* mono output bundles */
434 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
436 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
438 shared_ptr<Bundle> c (new Bundle (buf, true));
439 c->add_channel (_("mono"));
440 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
445 /* stereo output bundles */
447 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
448 if (np + 1 < n_physical_outputs) {
450 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
451 shared_ptr<Bundle> c (new Bundle (buf, true));
452 c->add_channel (_("L"));
453 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
454 c->add_channel (_("R"));
455 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
461 /* mono input bundles */
463 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
465 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
467 shared_ptr<Bundle> c (new Bundle (buf, false));
468 c->add_channel (_("mono"));
469 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
474 /* stereo input bundles */
476 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
477 if (np + 1 < n_physical_inputs) {
479 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
481 shared_ptr<Bundle> c (new Bundle (buf, false));
482 c->add_channel (_("L"));
483 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
484 c->add_channel (_("R"));
485 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
491 BootMessage (_("Setup signal flow and plugins"));
495 if (_is_new && !no_auto_connect()) {
497 /* don't connect the master bus outputs if there is a monitor bus */
499 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
501 /* if requested auto-connect the outputs to the first N physical ports.
504 uint32_t limit = _master_out->n_outputs().n_total();
506 for (uint32_t n = 0; n < limit; ++n) {
507 Port* p = _master_out->output()->nth (n);
508 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
510 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
511 if (_master_out->output()->connect (p, connect_to, this)) {
512 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
522 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
523 are undefined, at best.
526 /* control out listens to master bus (but ignores it
527 under some conditions)
530 uint32_t limit = _monitor_out->n_inputs().n_audio();
533 for (uint32_t n = 0; n < limit; ++n) {
534 AudioPort* p = _monitor_out->input()->ports().nth_audio_port (n);
535 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
538 string connect_to = o->name();
539 if (_monitor_out->input()->connect (p, connect_to, this)) {
540 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
548 /* if control out is not connected, connect control out to physical outs
551 if (!_monitor_out->output()->connected ()) {
553 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
555 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
558 _monitor_out->output()->connect_ports_to_bundle (b, this);
560 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
561 Config->get_monitor_bus_preferred_bundle())
567 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
568 uint32_t mod = _engine.n_physical_outputs (*t);
569 uint32_t limit = _monitor_out->n_outputs().get(*t);
571 for (uint32_t n = 0; n < limit; ++n) {
573 Port* p = _monitor_out->output()->ports().port(*t, n);
574 string connect_to = _engine.get_nth_physical_output (*t, (n % mod));
576 if (!connect_to.empty()) {
577 if (_monitor_out->output()->connect (p, connect_to, this)) {
578 error << string_compose (
579 _("cannot connect control output %1 to %2"),
592 /* catch up on send+insert cnts */
594 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
596 /* hook us up to the engine */
598 BootMessage (_("Connect to engine"));
600 _engine.set_session (this);
604 Session::hookup_io ()
606 /* stop graph reordering notifications from
607 causing resorts, etc.
610 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
615 /* we delay creating the auditioner till now because
616 it makes its own connections to ports.
620 Auditioner* a = new Auditioner (*this);
623 throw failed_constructor();
625 a->use_new_diskstream ();
626 auditioner.reset (a);
629 catch (failed_constructor& err) {
630 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
634 /* load bundles, which we may have postponed earlier on */
635 if (_bundle_xml_node) {
636 load_bundles (*_bundle_xml_node);
637 delete _bundle_xml_node;
640 /* Tell all IO objects to connect themselves together */
642 IO::enable_connecting ();
643 MIDI::JACK_MidiPort::MakeConnections ();
645 /* Now reset all panners */
647 Delivery::reset_panners ();
649 /* Connect tracks to monitor/listen bus if there is one.
650 Note that in an existing session, the internal sends will
651 already exist, but we want the routes to notice that
652 they connect to the control out specifically.
656 boost::shared_ptr<RouteList> r = routes.reader ();
657 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
659 if ((*x)->is_monitor()) {
663 } else if ((*x)->is_master()) {
669 (*x)->listen_via (_monitor_out,
670 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
676 /* Anyone who cares about input state, wake up and do something */
678 IOConnectionsComplete (); /* EMIT SIGNAL */
680 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
682 /* now handle the whole enchilada as if it was one
688 /* update the full solo state, which can't be
689 correctly determined on a per-route basis, but
690 needs the global overview that only the session
694 update_route_solo_state ();
698 Session::playlist_length_changed ()
700 /* we can't just increase session_range_location->end() if pl->get_maximum_extent()
701 if larger. if the playlist used to be the longest playlist,
702 and its now shorter, we have to decrease session_range_location->end(). hence,
703 we have to iterate over all diskstreams and check the
704 playlists currently in use.
710 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
712 boost::shared_ptr<Track> track = wp.lock ();
717 boost::shared_ptr<Playlist> playlist;
719 if ((playlist = track->playlist()) != 0) {
720 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
723 /* see comment in playlist_length_changed () */
728 Session::record_enabling_legal () const
730 /* this used to be in here, but survey says.... we don't need to restrict it */
731 // if (record_status() == Recording) {
735 if (Config->get_all_safe()) {
742 Session::reset_input_monitor_state ()
744 if (transport_rolling()) {
746 boost::shared_ptr<RouteList> rl = routes.reader ();
747 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
748 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
749 if (tr && tr->record_enabled ()) {
750 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
751 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
757 boost::shared_ptr<RouteList> rl = routes.reader ();
758 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
759 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
760 if (tr && tr->record_enabled ()) {
761 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
762 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
769 Session::auto_punch_start_changed (Location* location)
771 replace_event (SessionEvent::PunchIn, location->start());
773 if (get_record_enabled() && config.get_punch_in()) {
774 /* capture start has been changed, so save new pending state */
775 save_state ("", true);
780 Session::auto_punch_end_changed (Location* location)
782 nframes_t when_to_stop = location->end();
783 // when_to_stop += _worst_output_latency + _worst_input_latency;
784 replace_event (SessionEvent::PunchOut, when_to_stop);
788 Session::auto_punch_changed (Location* location)
790 nframes_t when_to_stop = location->end();
792 replace_event (SessionEvent::PunchIn, location->start());
793 //when_to_stop += _worst_output_latency + _worst_input_latency;
794 replace_event (SessionEvent::PunchOut, when_to_stop);
798 Session::auto_loop_changed (Location* location)
800 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
802 if (transport_rolling() && play_loop) {
805 // if (_transport_frame > location->end()) {
807 if (_transport_frame < location->start() || _transport_frame > location->end()) {
808 // relocate to beginning of loop
809 clear_events (SessionEvent::LocateRoll);
811 request_locate (location->start(), true);
814 else if (Config->get_seamless_loop() && !loop_changing) {
816 // schedule a locate-roll to refill the diskstreams at the
818 loop_changing = true;
820 if (location->end() > last_loopend) {
821 clear_events (SessionEvent::LocateRoll);
822 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
829 last_loopend = location->end();
833 Session::set_auto_punch_location (Location* location)
837 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
838 punch_connections.drop_connections();
839 existing->set_auto_punch (false, this);
840 remove_event (existing->start(), SessionEvent::PunchIn);
841 clear_events (SessionEvent::PunchOut);
842 auto_punch_location_changed (0);
851 if (location->end() <= location->start()) {
852 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
856 punch_connections.drop_connections ();
858 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
859 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
860 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
862 location->set_auto_punch (true, this);
864 auto_punch_changed (location);
866 auto_punch_location_changed (location);
870 Session::set_auto_loop_location (Location* location)
874 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
875 loop_connections.drop_connections ();
876 existing->set_auto_loop (false, this);
877 remove_event (existing->end(), SessionEvent::AutoLoop);
878 auto_loop_location_changed (0);
887 if (location->end() <= location->start()) {
888 error << _("Session: you can't use a mark for auto loop") << endmsg;
892 last_loopend = location->end();
894 loop_connections.drop_connections ();
896 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
897 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
898 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
900 location->set_auto_loop (true, this);
902 /* take care of our stuff first */
904 auto_loop_changed (location);
906 /* now tell everyone else */
908 auto_loop_location_changed (location);
912 Session::locations_added (Location *)
918 Session::locations_changed ()
920 _locations.apply (*this, &Session::handle_locations_changed);
924 Session::handle_locations_changed (Locations::LocationList& locations)
926 Locations::LocationList::iterator i;
928 bool set_loop = false;
929 bool set_punch = false;
931 for (i = locations.begin(); i != locations.end(); ++i) {
935 if (location->is_auto_punch()) {
936 set_auto_punch_location (location);
939 if (location->is_auto_loop()) {
940 set_auto_loop_location (location);
944 if (location->is_session_range()) {
945 _session_range_location = location;
950 set_auto_loop_location (0);
953 set_auto_punch_location (0);
960 Session::enable_record ()
962 /* XXX really atomic compare+swap here */
963 if (g_atomic_int_get (&_record_status) != Recording) {
964 g_atomic_int_set (&_record_status, Recording);
965 _last_record_location = _transport_frame;
966 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
968 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
970 boost::shared_ptr<RouteList> rl = routes.reader ();
971 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
972 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
973 if (tr && tr->record_enabled ()) {
974 tr->monitor_input (true);
979 RecordStateChanged ();
984 Session::disable_record (bool rt_context, bool force)
988 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
990 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
991 g_atomic_int_set (&_record_status, Disabled);
993 if (rs == Recording) {
994 g_atomic_int_set (&_record_status, Enabled);
998 // FIXME: timestamp correct? [DR]
999 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1000 // does this /need/ to be sent in all cases?
1002 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1005 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1007 boost::shared_ptr<RouteList> rl = routes.reader ();
1008 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1009 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1010 if (tr && tr->record_enabled ()) {
1011 tr->monitor_input (false);
1016 RecordStateChanged (); /* emit signal */
1019 remove_pending_capture_state ();
1025 Session::step_back_from_record ()
1027 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1029 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1030 boost::shared_ptr<RouteList> rl = routes.reader ();
1031 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1032 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1033 if (tr && tr->record_enabled ()) {
1034 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1035 tr->monitor_input (false);
1043 Session::maybe_enable_record ()
1045 g_atomic_int_set (&_record_status, Enabled);
1047 /* this function is currently called from somewhere other than an RT thread.
1048 this save_state() call therefore doesn't impact anything.
1051 save_state ("", true);
1053 if (_transport_speed) {
1054 if (!config.get_punch_in()) {
1058 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1059 RecordStateChanged (); /* EMIT SIGNAL */
1066 Session::audible_frame () const
1072 /* the first of these two possible settings for "offset"
1073 mean that the audible frame is stationary until
1074 audio emerges from the latency compensation
1077 the second means that the audible frame is stationary
1078 until audio would emerge from a physical port
1079 in the absence of any plugin latency compensation
1082 offset = _worst_output_latency;
1084 if (offset > current_block_size) {
1085 offset -= current_block_size;
1087 /* XXX is this correct? if we have no external
1088 physical connections and everything is internal
1089 then surely this is zero? still, how
1090 likely is that anyway?
1092 offset = current_block_size;
1095 if (synced_to_jack()) {
1096 tf = _engine.transport_frame();
1098 tf = _transport_frame;
1103 if (!non_realtime_work_pending()) {
1107 /* Check to see if we have passed the first guaranteed
1108 audible frame past our last start position. if not,
1109 return that last start point because in terms
1110 of audible frames, we have not moved yet.
1112 `Start position' in this context means the time we last
1113 either started or changed transport direction.
1116 if (_transport_speed > 0.0f) {
1118 if (!play_loop || !have_looped) {
1119 if (tf < _last_roll_or_reversal_location + offset) {
1120 return _last_roll_or_reversal_location;
1128 } else if (_transport_speed < 0.0f) {
1130 /* XXX wot? no backward looping? */
1132 if (tf > _last_roll_or_reversal_location - offset) {
1133 return _last_roll_or_reversal_location;
1145 Session::set_frame_rate (nframes_t frames_per_second)
1147 /** \fn void Session::set_frame_size(nframes_t)
1148 the AudioEngine object that calls this guarantees
1149 that it will not be called while we are also in
1150 ::process(). Its fine to do things that block
1154 _base_frame_rate = frames_per_second;
1158 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1162 // XXX we need some equivalent to this, somehow
1163 // SndFileSource::setup_standard_crossfades (frames_per_second);
1167 /* XXX need to reset/reinstantiate all LADSPA plugins */
1171 Session::set_block_size (nframes_t nframes)
1173 /* the AudioEngine guarantees
1174 that it will not be called while we are also in
1175 ::process(). It is therefore fine to do things that block
1180 current_block_size = nframes;
1184 boost::shared_ptr<RouteList> r = routes.reader ();
1186 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1187 (*i)->set_block_size (nframes);
1190 boost::shared_ptr<RouteList> rl = routes.reader ();
1191 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1192 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1194 tr->set_block_size (nframes);
1198 set_worst_io_latencies ();
1203 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1206 nframes_t fade_frames;
1208 /* Don't allow fade of less 1 frame */
1210 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1217 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1221 default_fade_msecs = fade_msecs;
1222 default_fade_steepness = steepness;
1225 // jlc, WTF is this!
1226 Glib::RWLock::ReaderLock lm (route_lock);
1227 AudioRegion::set_default_fade (steepness, fade_frames);
1232 /* XXX have to do this at some point */
1233 /* foreach region using default fade, reset, then
1234 refill_all_diskstream_buffers ();
1239 struct RouteSorter {
1240 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1241 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1243 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1246 if (r1->fed_by.empty()) {
1247 if (r2->fed_by.empty()) {
1248 /* no ardour-based connections inbound to either route. just use signal order */
1249 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1251 /* r2 has connections, r1 does not; run r1 early */
1255 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1262 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1264 shared_ptr<Route> r2;
1266 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1267 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1271 /* make a copy of the existing list of routes that feed r1 */
1273 set<weak_ptr<Route> > existing = r1->fed_by;
1275 /* for each route that feeds r1, recurse, marking it as feeding
1279 for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1280 if (!(r2 = (*i).lock ())) {
1281 /* (*i) went away, ignore it */
1285 /* r2 is a route that feeds r1 which somehow feeds base. mark
1286 base as being fed by r2
1289 rbase->fed_by.insert (r2);
1293 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1297 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1301 /* now recurse, so that we can mark base as being fed by
1302 all routes that feed r2
1305 trace_terminal (r2, rbase);
1312 Session::resort_routes ()
1314 /* don't do anything here with signals emitted
1315 by Routes while we are being destroyed.
1318 if (_state_of_the_state & Deletion) {
1325 RCUWriter<RouteList> writer (routes);
1326 shared_ptr<RouteList> r = writer.get_copy ();
1327 resort_routes_using (r);
1328 /* writer goes out of scope and forces update */
1333 Session::resort_routes_using (shared_ptr<RouteList> r)
1335 RouteList::iterator i, j;
1337 for (i = r->begin(); i != r->end(); ++i) {
1339 (*i)->fed_by.clear ();
1341 for (j = r->begin(); j != r->end(); ++j) {
1343 /* although routes can feed themselves, it will
1344 cause an endless recursive descent if we
1345 detect it. so don't bother checking for
1353 if ((*j)->feeds (*i)) {
1354 (*i)->fed_by.insert (*j);
1359 for (i = r->begin(); i != r->end(); ++i) {
1360 trace_terminal (*i, *i);
1367 cerr << "finished route resort\n";
1369 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1370 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1377 /** Find the route name starting with \a base with the lowest \a id.
1379 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1380 * The available route name with the lowest ID will be used, and \a id
1381 * will be set to the ID.
1383 * \return false if a route name could not be found, and \a track_name
1384 * and \a id do not reflect a free route name.
1387 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1390 snprintf (name, name_len, "%s %" PRIu32, base, id);
1392 if (route_by_name (name) == 0) {
1398 } while (id < (UINT_MAX-1));
1404 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1406 in = ChanCount::ZERO;
1407 out = ChanCount::ZERO;
1408 shared_ptr<RouteList> r = routes.reader ();
1409 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1410 if (!(*i)->is_hidden()) {
1411 in += (*i)->n_inputs();
1412 out += (*i)->n_outputs();
1417 list<boost::shared_ptr<MidiTrack> >
1418 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1420 char track_name[32];
1421 uint32_t track_id = 0;
1422 ChanCount existing_inputs;
1423 ChanCount existing_outputs;
1425 RouteList new_routes;
1426 list<boost::shared_ptr<MidiTrack> > ret;
1427 uint32_t control_id;
1429 count_existing_route_channels (existing_inputs, existing_outputs);
1431 control_id = ntracks() + nbusses();
1434 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1435 error << "cannot find name for new midi track" << endmsg;
1439 shared_ptr<MidiTrack> track;
1442 MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1449 mt->use_new_diskstream();
1451 boost_debug_shared_ptr_mark_interesting (mt, "Track");
1452 track = boost::shared_ptr<MidiTrack>(mt);
1454 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1455 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;
1465 auto_connect_route (track, existing_inputs, existing_outputs);
1467 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, false);
1496 save_state (_current_snapshot_name);
1503 Session::auto_connect_route (boost::shared_ptr<Route> route,
1504 ChanCount& existing_inputs, ChanCount& existing_outputs)
1506 /* If both inputs and outputs are auto-connected to physical ports,
1507 use the max of input and output offsets to ensure auto-connected
1508 port numbers always match up (e.g. the first audio input and the
1509 first audio output of the route will have the same physical
1510 port number). Otherwise just use the lowest input or output
1513 const bool in_out_physical =
1514 (Config->get_input_auto_connect() & AutoConnectPhysical)
1515 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1517 const ChanCount in_offset = in_out_physical
1518 ? ChanCount::max(existing_inputs, existing_outputs)
1521 const ChanCount out_offset = in_out_physical
1522 ? ChanCount::max(existing_inputs, existing_outputs)
1525 static string empty_string;
1526 string& port = empty_string;
1528 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1529 vector<string> physinputs;
1530 vector<string> physoutputs;
1532 _engine.get_physical_outputs (*t, physoutputs);
1533 _engine.get_physical_inputs (*t, physinputs);
1535 if (!physinputs.empty()) {
1536 uint32_t nphysical_in = physinputs.size();
1537 for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1538 port = empty_string;
1540 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1541 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1544 if (!port.empty() && route->input()->connect (
1545 route->input()->ports().port(*t, i), port, this)) {
1551 if (!physoutputs.empty()) {
1552 uint32_t nphysical_out = physoutputs.size();
1553 for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1554 port = empty_string;
1556 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1557 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1558 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1559 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1560 port = _master_out->input()->ports().port(*t,
1561 i % _master_out->input()->n_ports().get(*t))->name();
1565 if (!port.empty() && route->output()->connect (
1566 route->output()->ports().port(*t, i), port, this)) {
1573 existing_inputs += route->n_inputs();
1574 existing_outputs += route->n_outputs();
1577 list< boost::shared_ptr<AudioTrack> >
1578 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1580 char track_name[32];
1581 uint32_t track_id = 0;
1582 ChanCount existing_inputs;
1583 ChanCount existing_outputs;
1585 RouteList new_routes;
1586 list<boost::shared_ptr<AudioTrack> > ret;
1587 uint32_t control_id;
1589 count_existing_route_channels (existing_inputs, existing_outputs);
1591 control_id = ntracks() + nbusses() + 1;
1594 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1595 error << "cannot find name for new audio track" << endmsg;
1599 shared_ptr<AudioTrack> track;
1602 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1609 at->use_new_diskstream();
1611 boost_debug_shared_ptr_mark_interesting (at, "Track");
1612 track = boost::shared_ptr<AudioTrack>(at);
1614 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1615 error << string_compose (
1616 _("cannot configure %1 in/%2 out configuration for new audio track"),
1617 input_channels, output_channels)
1622 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1623 error << string_compose (
1624 _("cannot configure %1 in/%2 out configuration for new audio track"),
1625 input_channels, output_channels)
1630 auto_connect_route (track, existing_inputs, existing_outputs);
1633 route_group->add (track);
1636 track->non_realtime_input_change();
1638 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1639 track->set_remote_control_id (control_id);
1642 new_routes.push_back (track);
1643 ret.push_back (track);
1646 catch (failed_constructor &err) {
1647 error << _("Session: could not create new audio track.") << endmsg;
1651 catch (AudioEngine::PortRegistrationFailure& pfe) {
1653 error << pfe.what() << endmsg;
1661 if (!new_routes.empty()) {
1662 add_routes (new_routes, true);
1669 Session::set_remote_control_ids ()
1671 RemoteModel m = Config->get_remote_model();
1672 bool emit_signal = false;
1674 shared_ptr<RouteList> r = routes.reader ();
1676 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1677 if (MixerOrdered == m) {
1678 long order = (*i)->order_key(N_("signal"));
1679 (*i)->set_remote_control_id (order+1, false);
1681 } else if (EditorOrdered == m) {
1682 long order = (*i)->order_key(N_("editor"));
1683 (*i)->set_remote_control_id (order+1, false);
1685 } else if (UserOrdered == m) {
1686 //do nothing ... only changes to remote id's are initiated by user
1691 Route::RemoteControlIDChange();
1697 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1700 uint32_t bus_id = 0;
1701 ChanCount existing_inputs;
1702 ChanCount existing_outputs;
1705 uint32_t control_id;
1707 count_existing_route_channels (existing_inputs, existing_outputs);
1709 control_id = ntracks() + nbusses() + 1;
1712 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1713 error << "cannot find name for new audio bus" << endmsg;
1718 Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1725 boost_debug_shared_ptr_mark_interesting (rt, "Route");
1726 shared_ptr<Route> bus (rt);
1728 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1729 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1730 input_channels, output_channels)
1736 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1737 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1738 input_channels, output_channels)
1743 auto_connect_route (bus, existing_inputs, existing_outputs);
1746 route_group->add (bus);
1748 bus->set_remote_control_id (control_id);
1752 bus->add_internal_return ();
1755 ret.push_back (bus);
1759 catch (failed_constructor &err) {
1760 error << _("Session: could not create new audio route.") << endmsg;
1764 catch (AudioEngine::PortRegistrationFailure& pfe) {
1765 error << pfe.what() << endmsg;
1775 add_routes (ret, true);
1783 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1787 uint32_t control_id;
1789 uint32_t number = 0;
1791 if (!tree.read (template_path.c_str())) {
1795 XMLNode* node = tree.root();
1797 control_id = ntracks() + nbusses() + 1;
1801 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1803 std::string node_name = IO::name_from_state (*node_copy.children().front());
1805 /* generate a new name by adding a number to the end of the template name */
1806 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1807 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1811 IO::set_name_in_state (*node_copy.children().front(), name);
1813 Track::zero_diskstream_id_in_xml (node_copy);
1816 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1819 error << _("Session: cannot create track/bus from template description") << endmsg;
1823 if (boost::dynamic_pointer_cast<Track>(route)) {
1824 /* force input/output change signals so that the new diskstream
1825 picks up the configuration of the route. During session
1826 loading this normally happens in a different way.
1828 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1829 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1832 route->set_remote_control_id (control_id);
1835 ret.push_back (route);
1838 catch (failed_constructor &err) {
1839 error << _("Session: could not create new route from template") << endmsg;
1843 catch (AudioEngine::PortRegistrationFailure& pfe) {
1844 error << pfe.what() << endmsg;
1853 add_routes (ret, true);
1860 Session::add_routes (RouteList& new_routes, bool save)
1863 RCUWriter<RouteList> writer (routes);
1864 shared_ptr<RouteList> r = writer.get_copy ();
1865 r->insert (r->end(), new_routes.begin(), new_routes.end());
1868 /* if there is no control out and we're not in the middle of loading,
1869 resort the graph here. if there is a control out, we will resort
1870 toward the end of this method. if we are in the middle of loading,
1871 we will resort when done.
1874 if (!_monitor_out && IO::connecting_legal) {
1875 resort_routes_using (r);
1879 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1881 boost::weak_ptr<Route> wpr (*x);
1882 boost::shared_ptr<Route> r (*x);
1884 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1885 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, wpr));
1886 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1887 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1888 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1889 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
1891 if (r->is_master()) {
1895 if (r->is_monitor()) {
1899 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
1901 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
1902 track_playlist_changed (boost::weak_ptr<Track> (tr));
1903 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
1907 if (_monitor_out && IO::connecting_legal) {
1909 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1910 if ((*x)->is_monitor()) {
1912 } else if ((*x)->is_master()) {
1915 (*x)->listen_via (_monitor_out,
1916 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
1927 save_state (_current_snapshot_name);
1930 RouteAdded (new_routes); /* EMIT SIGNAL */
1931 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
1935 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
1937 boost::shared_ptr<RouteList> r = routes.reader ();
1938 boost::shared_ptr<Send> s;
1942 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1943 if (boost::dynamic_pointer_cast<Track>(*i)) {
1944 if ((s = (*i)->internal_send_for (dest)) != 0) {
1945 s->amp()->gain_control()->set_value (0.0);
1952 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
1954 boost::shared_ptr<RouteList> r = routes.reader ();
1955 boost::shared_ptr<Send> s;
1959 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1960 if (boost::dynamic_pointer_cast<Track>(*i)) {
1961 if ((s = (*i)->internal_send_for (dest)) != 0) {
1962 s->amp()->gain_control()->set_value (1.0);
1969 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
1971 boost::shared_ptr<RouteList> r = routes.reader ();
1972 boost::shared_ptr<Send> s;
1976 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1977 if (boost::dynamic_pointer_cast<Track>(*i)) {
1978 if ((s = (*i)->internal_send_for (dest)) != 0) {
1979 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
1986 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
1988 boost::shared_ptr<RouteList> r = routes.reader ();
1989 boost::shared_ptr<RouteList> t (new RouteList);
1991 /* only send tracks */
1993 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1994 if (boost::dynamic_pointer_cast<Track>(*i)) {
1999 add_internal_sends (dest, p, t);
2003 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2005 if (dest->is_monitor() || dest->is_master()) {
2009 if (!dest->internal_return()) {
2010 dest->add_internal_return();
2013 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2015 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2019 (*i)->listen_via (dest, p, true, true);
2026 Session::remove_route (shared_ptr<Route> route)
2029 RCUWriter<RouteList> writer (routes);
2030 shared_ptr<RouteList> rs = writer.get_copy ();
2034 /* deleting the master out seems like a dumb
2035 idea, but its more of a UI policy issue
2039 if (route == _master_out) {
2040 _master_out = shared_ptr<Route> ();
2043 if (route == _monitor_out) {
2045 /* cancel control outs for all routes */
2047 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2048 (*r)->drop_listen (_monitor_out);
2051 _monitor_out.reset ();
2054 update_route_solo_state ();
2056 /* writer goes out of scope, forces route list update */
2059 find_current_end ();
2061 // We need to disconnect the routes inputs and outputs
2063 route->input()->disconnect (0);
2064 route->output()->disconnect (0);
2066 /* if the route had internal sends sending to it, remove them */
2067 if (route->internal_return()) {
2069 boost::shared_ptr<RouteList> r = routes.reader ();
2070 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2071 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2073 (*i)->remove_processor (s);
2078 update_latency_compensation (false, false);
2081 /* get rid of it from the dead wood collection in the route list manager */
2083 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2087 /* try to cause everyone to drop their references */
2089 route->drop_references ();
2091 sync_order_keys (N_("session"));
2093 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2095 /* save the new state of the world */
2097 if (save_state (_current_snapshot_name)) {
2098 save_history (_current_snapshot_name);
2103 Session::route_mute_changed (void* /*src*/)
2109 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2111 boost::shared_ptr<Route> route = wpr.lock();
2113 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2117 if (route->listening()) {
2119 } else if (_listen_cnt > 0) {
2125 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2127 if (solo_update_disabled) {
2132 boost::shared_ptr<Route> route = wpr.lock ();
2135 /* should not happen */
2136 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2140 shared_ptr<RouteList> r = routes.reader ();
2143 if (route->self_soloed()) {
2149 /* now mod the solo level of all other routes except master/control outs/auditioner
2150 so that they will be silent if appropriate.
2153 solo_update_disabled = true;
2155 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2156 bool via_sends_only;
2158 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2160 } else if ((*i)->feeds (route, &via_sends_only)) {
2161 if (!via_sends_only) {
2162 (*i)->mod_solo_by_others (delta);
2167 solo_update_disabled = false;
2168 update_route_solo_state (r);
2169 SoloChanged (); /* EMIT SIGNAL */
2174 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2176 /* now figure out if anything that matters is soloed (or is "listening")*/
2178 bool something_soloed = false;
2179 uint32_t listeners = 0;
2182 r = routes.reader();
2185 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2186 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2187 something_soloed = true;
2191 if (!(*i)->is_hidden() && (*i)->listening()) {
2192 if (Config->get_solo_control_is_listen_control()) {
2195 (*i)->set_listen (false, this);
2200 if (something_soloed != _non_soloed_outs_muted) {
2201 _non_soloed_outs_muted = something_soloed;
2202 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2206 _listen_cnt = listeners;
2210 boost::shared_ptr<RouteList>
2211 Session::get_routes_with_internal_returns() const
2213 shared_ptr<RouteList> r = routes.reader ();
2214 boost::shared_ptr<RouteList> rl (new RouteList);
2216 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2217 if ((*i)->internal_return ()) {
2225 Session::io_name_is_legal (const std::string& name)
2227 shared_ptr<RouteList> r = routes.reader ();
2229 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2230 if ((*i)->name() == name) {
2234 if ((*i)->has_io_processor_named (name)) {
2243 Session::route_by_name (string name)
2245 shared_ptr<RouteList> r = routes.reader ();
2247 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2248 if ((*i)->name() == name) {
2253 return shared_ptr<Route> ((Route*) 0);
2257 Session::route_by_id (PBD::ID id)
2259 shared_ptr<RouteList> r = routes.reader ();
2261 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2262 if ((*i)->id() == id) {
2267 return shared_ptr<Route> ((Route*) 0);
2271 Session::route_by_remote_id (uint32_t id)
2273 shared_ptr<RouteList> r = routes.reader ();
2275 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2276 if ((*i)->remote_control_id() == id) {
2281 return shared_ptr<Route> ((Route*) 0);
2285 Session::find_current_end ()
2287 if (_state_of_the_state & Loading) {
2291 nframes_t max = get_maximum_extent ();
2293 if (max > _session_range_location->end()) {
2294 _session_range_location->set_end (max);
2296 DurationChanged(); /* EMIT SIGNAL */
2301 Session::get_maximum_extent () const
2306 boost::shared_ptr<RouteList> rl = routes.reader ();
2307 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2308 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2309 if (!tr || tr->destructive()) {
2310 //ignore tape tracks when getting max extents
2314 boost::shared_ptr<Playlist> pl = tr->playlist();
2315 if ((me = pl->get_maximum_extent()) > max) {
2323 /* Region management */
2325 boost::shared_ptr<Region>
2326 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2328 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2329 RegionFactory::RegionMap::const_iterator i;
2330 boost::shared_ptr<Region> region;
2332 Glib::Mutex::Lock lm (region_lock);
2334 for (i = regions.begin(); i != regions.end(); ++i) {
2338 if (region->whole_file()) {
2340 if (child->source_equivalent (region)) {
2346 return boost::shared_ptr<Region> ();
2350 Session::destroy_region (boost::shared_ptr<Region> region)
2352 vector<boost::shared_ptr<Source> > srcs;
2355 if (region->playlist()) {
2356 region->playlist()->destroy_region (region);
2359 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2360 srcs.push_back (region->source (n));
2364 region->drop_references ();
2366 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2368 (*i)->mark_for_remove ();
2369 (*i)->drop_references ();
2371 cerr << "source was not used by any playlist\n";
2378 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2380 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2381 destroy_region (*i);
2387 Session::remove_last_capture ()
2389 list<boost::shared_ptr<Region> > r;
2391 boost::shared_ptr<RouteList> rl = routes.reader ();
2392 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2393 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2398 list<boost::shared_ptr<Region> >& l = tr->last_capture_regions();
2401 r.insert (r.end(), l.begin(), l.end());
2406 destroy_regions (r);
2408 save_state (_current_snapshot_name);
2413 /* Source Management */
2416 Session::add_source (boost::shared_ptr<Source> source)
2418 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2419 pair<SourceMap::iterator,bool> result;
2421 entry.first = source->id();
2422 entry.second = source;
2425 Glib::Mutex::Lock lm (source_lock);
2426 result = sources.insert (entry);
2429 if (result.second) {
2430 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
2434 boost::shared_ptr<AudioFileSource> afs;
2436 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2437 if (Config->get_auto_analyse_audio()) {
2438 Analyser::queue_source_for_analysis (source, false);
2444 Session::remove_source (boost::weak_ptr<Source> src)
2446 SourceMap::iterator i;
2447 boost::shared_ptr<Source> source = src.lock();
2454 Glib::Mutex::Lock lm (source_lock);
2456 if ((i = sources.find (source->id())) != sources.end()) {
2461 if (!_state_of_the_state & InCleanup) {
2463 /* save state so we don't end up with a session file
2464 referring to non-existent sources.
2467 save_state (_current_snapshot_name);
2471 boost::shared_ptr<Source>
2472 Session::source_by_id (const PBD::ID& id)
2474 Glib::Mutex::Lock lm (source_lock);
2475 SourceMap::iterator i;
2476 boost::shared_ptr<Source> source;
2478 if ((i = sources.find (id)) != sources.end()) {
2485 boost::shared_ptr<Source>
2486 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2488 Glib::Mutex::Lock lm (source_lock);
2490 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2491 cerr << "comparing " << path << " with " << i->second->name() << endl;
2492 boost::shared_ptr<AudioFileSource> afs
2493 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2495 if (afs && afs->path() == path && chn == afs->channel()) {
2499 return boost::shared_ptr<Source>();
2504 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2507 string old_basename = PBD::basename_nosuffix (oldname);
2508 string new_legalized = legalize_for_path (newname);
2510 /* note: we know (or assume) the old path is already valid */
2514 /* destructive file sources have a name of the form:
2516 /path/to/Tnnnn-NAME(%[LR])?.wav
2518 the task here is to replace NAME with the new name.
2521 /* find last slash */
2525 string::size_type slash;
2526 string::size_type dash;
2528 if ((slash = path.find_last_of ('/')) == string::npos) {
2532 dir = path.substr (0, slash+1);
2534 /* '-' is not a legal character for the NAME part of the path */
2536 if ((dash = path.find_last_of ('-')) == string::npos) {
2540 prefix = path.substr (slash+1, dash-(slash+1));
2545 path += new_legalized;
2546 path += ".wav"; /* XXX gag me with a spoon */
2550 /* non-destructive file sources have a name of the form:
2552 /path/to/NAME-nnnnn(%[LR])?.ext
2554 the task here is to replace NAME with the new name.
2559 string::size_type slash;
2560 string::size_type dash;
2561 string::size_type postfix;
2563 /* find last slash */
2565 if ((slash = path.find_last_of ('/')) == string::npos) {
2569 dir = path.substr (0, slash+1);
2571 /* '-' is not a legal character for the NAME part of the path */
2573 if ((dash = path.find_last_of ('-')) == string::npos) {
2577 suffix = path.substr (dash+1);
2579 // Suffix is now everything after the dash. Now we need to eliminate
2580 // the nnnnn part, which is done by either finding a '%' or a '.'
2582 postfix = suffix.find_last_of ("%");
2583 if (postfix == string::npos) {
2584 postfix = suffix.find_last_of ('.');
2587 if (postfix != string::npos) {
2588 suffix = suffix.substr (postfix);
2590 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2594 const uint32_t limit = 10000;
2595 char buf[PATH_MAX+1];
2597 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2599 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2601 if (access (buf, F_OK) != 0) {
2609 error << "FATAL ERROR! Could not find a " << endl;
2617 /** Return the full path (in some session directory) for a new within-session source.
2618 * \a name must be a session-unique name that does not contain slashes
2619 * (e.g. as returned by new_*_source_name)
2622 Session::new_source_path_from_name (DataType type, const string& name)
2624 assert(name.find("/") == string::npos);
2626 SessionDirectory sdir(get_best_session_directory_for_new_source());
2629 if (type == DataType::AUDIO) {
2630 p = sdir.sound_path();
2631 } else if (type == DataType::MIDI) {
2632 p = sdir.midi_path();
2634 error << "Unknown source type, unable to create file path" << endmsg;
2639 return p.to_string();
2643 Session::peak_path (Glib::ustring base) const
2645 sys::path peakfile_path(_session_dir->peak_path());
2646 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2647 return peakfile_path.to_string();
2650 /** Return a unique name based on \a base for a new internal audio source */
2652 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2656 char buf[PATH_MAX+1];
2657 const uint32_t limit = 10000;
2661 legalized = legalize_for_path (base);
2663 // Find a "version" of the base name that doesn't exist in any of the possible directories.
2664 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2666 vector<space_and_path>::iterator i;
2667 uint32_t existing = 0;
2669 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2671 SessionDirectory sdir((*i).path);
2673 spath = sdir.sound_path().to_string();
2678 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2679 spath.c_str(), cnt, legalized.c_str());
2680 } else if (nchan == 2) {
2682 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2683 spath.c_str(), cnt, legalized.c_str());
2685 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2686 spath.c_str(), cnt, legalized.c_str());
2688 } else if (nchan < 26) {
2689 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2690 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2692 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2693 spath.c_str(), cnt, legalized.c_str());
2702 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2703 } else if (nchan == 2) {
2705 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2707 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2709 } else if (nchan < 26) {
2710 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2712 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2716 if (sys::exists(buf)) {
2722 if (existing == 0) {
2727 error << string_compose(
2728 _("There are already %1 recordings for %2, which I consider too many."),
2729 limit, base) << endmsg;
2731 throw failed_constructor();
2735 return Glib::path_get_basename(buf);
2738 /** Create a new within-session audio source */
2739 boost::shared_ptr<AudioFileSource>
2740 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
2742 const string name = new_audio_source_name (n, n_chans, chan, destructive);
2743 const string path = new_source_path_from_name(DataType::AUDIO, name);
2745 return boost::dynamic_pointer_cast<AudioFileSource> (
2746 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2749 /** Return a unique name based on \a base for a new internal MIDI source */
2751 Session::new_midi_source_name (const string& base)
2754 char buf[PATH_MAX+1];
2755 const uint32_t limit = 10000;
2759 legalized = legalize_for_path (base);
2761 // Find a "version" of the file name that doesn't exist in any of the possible directories.
2762 for (cnt = 1; cnt <= limit; ++cnt) {
2764 vector<space_and_path>::iterator i;
2765 uint32_t existing = 0;
2767 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2769 SessionDirectory sdir((*i).path);
2771 sys::path p = sdir.midi_path();
2774 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2776 if (sys::exists (buf)) {
2781 if (existing == 0) {
2786 error << string_compose(
2787 _("There are already %1 recordings for %2, which I consider too many."),
2788 limit, base) << endmsg;
2790 throw failed_constructor();
2794 return Glib::path_get_basename(buf);
2798 /** Create a new within-session MIDI source */
2799 boost::shared_ptr<MidiSource>
2800 Session::create_midi_source_for_session (string const & n)
2802 const string name = new_midi_source_name (n);
2803 const string path = new_source_path_from_name (DataType::MIDI, name);
2805 return boost::dynamic_pointer_cast<SMFSource> (
2806 SourceFactory::createWritable (
2807 DataType::MIDI, *this, path, false, frame_rate()));
2812 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
2814 if (playlist->hidden()) {
2818 playlists->add (playlist);
2821 playlist->release();
2828 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
2830 if (_state_of_the_state & Deletion) {
2834 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
2840 playlists->remove (playlist);
2846 Session::set_audition (boost::shared_ptr<Region> r)
2848 pending_audition_region = r;
2849 add_post_transport_work (PostTransportAudition);
2850 _butler->schedule_transport_work ();
2854 Session::audition_playlist ()
2856 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2857 ev->region.reset ();
2862 Session::non_realtime_set_audition ()
2864 if (!pending_audition_region) {
2865 auditioner->audition_current_playlist ();
2867 auditioner->audition_region (pending_audition_region);
2868 pending_audition_region.reset ();
2870 AuditionActive (true); /* EMIT SIGNAL */
2874 Session::audition_region (boost::shared_ptr<Region> r)
2876 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2882 Session::cancel_audition ()
2884 if (auditioner->auditioning()) {
2885 auditioner->cancel_audition ();
2886 AuditionActive (false); /* EMIT SIGNAL */
2891 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
2893 if (a->is_monitor()) {
2896 if (b->is_monitor()) {
2899 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
2903 Session::remove_empty_sounds ()
2905 vector<string> audio_filenames;
2907 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
2909 Glib::Mutex::Lock lm (source_lock);
2911 TapeFileMatcher tape_file_matcher;
2913 remove_if (audio_filenames.begin(), audio_filenames.end(),
2914 boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
2916 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
2918 sys::path audio_file_path (_session_dir->sound_path());
2920 audio_file_path /= *i;
2922 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
2926 sys::remove (audio_file_path);
2927 const string peakfile = peak_path (audio_file_path.to_string());
2928 sys::remove (peakfile);
2930 catch (const sys::filesystem_error& err)
2932 error << err.what() << endmsg;
2939 Session::is_auditioning () const
2941 /* can be called before we have an auditioner object */
2943 return auditioner->auditioning();
2950 Session::graph_reordered ()
2952 /* don't do this stuff if we are setting up connections
2953 from a set_state() call or creating new tracks. Ditto for deletion.
2956 if (_state_of_the_state & (InitialConnecting|Deletion)) {
2960 /* every track/bus asked for this to be handled but it was deferred because
2961 we were connecting. do it now.
2964 request_input_change_handling ();
2968 /* force all diskstreams to update their capture offset values to
2969 reflect any changes in latencies within the graph.
2972 boost::shared_ptr<RouteList> rl = routes.reader ();
2973 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2974 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2976 tr->set_capture_offset ();
2982 Session::available_capture_duration ()
2984 float sample_bytes_on_disk = 4.0; // keep gcc happy
2986 switch (config.get_native_file_data_format()) {
2988 sample_bytes_on_disk = 4.0;
2992 sample_bytes_on_disk = 3.0;
2996 sample_bytes_on_disk = 2.0;
3000 /* impossible, but keep some gcc versions happy */
3001 fatal << string_compose (_("programming error: %1"),
3002 X_("illegal native file data format"))
3007 double scale = 4096.0 / sample_bytes_on_disk;
3009 if (_total_free_4k_blocks * scale > (double) max_frames) {
3013 return (nframes_t) floor (_total_free_4k_blocks * scale);
3017 Session::add_bundle (shared_ptr<Bundle> bundle)
3020 RCUWriter<BundleList> writer (_bundles);
3021 boost::shared_ptr<BundleList> b = writer.get_copy ();
3022 b->push_back (bundle);
3025 BundleAdded (bundle); /* EMIT SIGNAL */
3031 Session::remove_bundle (shared_ptr<Bundle> bundle)
3033 bool removed = false;
3036 RCUWriter<BundleList> writer (_bundles);
3037 boost::shared_ptr<BundleList> b = writer.get_copy ();
3038 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3040 if (i != b->end()) {
3047 BundleRemoved (bundle); /* EMIT SIGNAL */
3054 Session::bundle_by_name (string name) const
3056 boost::shared_ptr<BundleList> b = _bundles.reader ();
3058 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3059 if ((*i)->name() == name) {
3064 return boost::shared_ptr<Bundle> ();
3068 Session::tempo_map_changed (const PropertyChange&)
3072 playlists->update_after_tempo_map_change ();
3077 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3078 * the given count with the current block size.
3081 Session::ensure_buffers (ChanCount howmany)
3083 BufferManager::ensure_buffers (howmany);
3087 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3089 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3090 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3095 Session::next_insert_id ()
3097 /* this doesn't really loop forever. just think about it */
3100 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3101 if (!insert_bitset[n]) {
3102 insert_bitset[n] = true;
3108 /* none available, so resize and try again */
3110 insert_bitset.resize (insert_bitset.size() + 16, false);
3115 Session::next_send_id ()
3117 /* this doesn't really loop forever. just think about it */
3120 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3121 if (!send_bitset[n]) {
3122 send_bitset[n] = true;
3128 /* none available, so resize and try again */
3130 send_bitset.resize (send_bitset.size() + 16, false);
3135 Session::next_return_id ()
3137 /* this doesn't really loop forever. just think about it */
3140 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3141 if (!return_bitset[n]) {
3142 return_bitset[n] = true;
3148 /* none available, so resize and try again */
3150 return_bitset.resize (return_bitset.size() + 16, false);
3155 Session::mark_send_id (uint32_t id)
3157 if (id >= send_bitset.size()) {
3158 send_bitset.resize (id+16, false);
3160 if (send_bitset[id]) {
3161 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3163 send_bitset[id] = true;
3167 Session::mark_return_id (uint32_t id)
3169 if (id >= return_bitset.size()) {
3170 return_bitset.resize (id+16, false);
3172 if (return_bitset[id]) {
3173 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3175 return_bitset[id] = true;
3179 Session::mark_insert_id (uint32_t id)
3181 if (id >= insert_bitset.size()) {
3182 insert_bitset.resize (id+16, false);
3184 if (insert_bitset[id]) {
3185 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3187 insert_bitset[id] = true;
3191 Session::unmark_send_id (uint32_t id)
3193 if (id < send_bitset.size()) {
3194 send_bitset[id] = false;
3199 Session::unmark_return_id (uint32_t id)
3201 if (id < return_bitset.size()) {
3202 return_bitset[id] = false;
3207 Session::unmark_insert_id (uint32_t id)
3209 if (id < insert_bitset.size()) {
3210 insert_bitset[id] = false;
3215 /* Named Selection management */
3217 boost::shared_ptr<NamedSelection>
3218 Session::named_selection_by_name (string name)
3220 Glib::Mutex::Lock lm (named_selection_lock);
3221 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3222 if ((*i)->name == name) {
3226 return boost::shared_ptr<NamedSelection>();
3230 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3233 Glib::Mutex::Lock lm (named_selection_lock);
3234 named_selections.insert (named_selections.begin(), named_selection);
3239 NamedSelectionAdded (); /* EMIT SIGNAL */
3243 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3245 bool removed = false;
3248 Glib::Mutex::Lock lm (named_selection_lock);
3250 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3252 if (i != named_selections.end()) {
3253 named_selections.erase (i);
3260 NamedSelectionRemoved (); /* EMIT SIGNAL */
3265 Session::reset_native_file_format ()
3267 boost::shared_ptr<RouteList> rl = routes.reader ();
3268 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3269 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3271 tr->reset_write_sources (false);
3277 Session::route_name_unique (string n) const
3279 shared_ptr<RouteList> r = routes.reader ();
3281 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3282 if ((*i)->name() == n) {
3291 Session::route_name_internal (string n) const
3293 if (auditioner && auditioner->name() == n) {
3297 if (_click_io && _click_io->name() == n) {
3305 Session::freeze_all (InterThreadInfo& itt)
3307 shared_ptr<RouteList> r = routes.reader ();
3309 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3311 boost::shared_ptr<Track> t;
3313 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3314 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3324 boost::shared_ptr<Region>
3325 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3326 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3327 InterThreadInfo& itt, bool enable_processing)
3329 boost::shared_ptr<Region> result;
3330 boost::shared_ptr<Playlist> playlist;
3331 boost::shared_ptr<AudioFileSource> fsource;
3333 char buf[PATH_MAX+1];
3334 ChanCount nchans(track.n_channels());
3336 nframes_t this_chunk;
3339 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3340 const string sound_dir = sdir.sound_path().to_string();
3341 nframes_t len = end - start;
3344 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3345 end, start) << endmsg;
3349 const nframes_t chunk_size = (256 * 1024)/4;
3351 // block all process callback handling
3353 block_processing ();
3355 /* call tree *MUST* hold route_lock */
3357 if ((playlist = track.playlist()) == 0) {
3361 /* external redirects will be a problem */
3363 if (track.has_external_redirects()) {
3367 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3369 for (x = 0; x < 99999; ++x) {
3370 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3371 if (access (buf, F_OK) != 0) {
3377 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3382 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3383 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3386 catch (failed_constructor& err) {
3387 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3391 srcs.push_back (fsource);
3394 /* XXX need to flush all redirects */
3399 /* create a set of reasonably-sized buffers */
3400 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3401 buffers.set_count(nchans);
3403 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3404 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3406 afs->prepare_for_peakfile_writes ();
3409 while (to_do && !itt.cancel) {
3411 this_chunk = min (to_do, chunk_size);
3413 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3418 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3419 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3422 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3428 start += this_chunk;
3429 to_do -= this_chunk;
3431 itt.progress = (float) (1.0 - ((double) to_do / len));
3440 xnow = localtime (&now);
3442 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3443 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3446 afs->update_header (position, *xnow, now);
3447 afs->flush_header ();
3451 /* construct a region to represent the bounced material */
3455 plist.add (Properties::start, 0);
3456 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3457 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3459 result = RegionFactory::create (srcs, plist);
3465 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3466 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3469 afs->mark_for_remove ();
3472 (*src)->drop_references ();
3476 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3477 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3480 afs->done_with_peakfile_writes ();
3484 unblock_processing ();
3490 Session::gain_automation_buffer() const
3492 return ProcessThread::gain_automation_buffer ();
3496 Session::pan_automation_buffer() const
3498 return ProcessThread::pan_automation_buffer ();
3502 Session::get_silent_buffers (ChanCount count)
3504 return ProcessThread::get_silent_buffers (count);
3506 assert(_silent_buffers->available() >= count);
3507 _silent_buffers->set_count(count);
3509 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3510 for (size_t i= 0; i < count.get(*t); ++i) {
3511 _silent_buffers->get(*t, i).clear();
3515 return *_silent_buffers;
3520 Session::get_scratch_buffers (ChanCount count)
3522 return ProcessThread::get_scratch_buffers (count);
3524 if (count != ChanCount::ZERO) {
3525 assert(_scratch_buffers->available() >= count);
3526 _scratch_buffers->set_count(count);
3528 _scratch_buffers->set_count (_scratch_buffers->available());
3531 return *_scratch_buffers;
3536 Session::get_mix_buffers (ChanCount count)
3538 return ProcessThread::get_mix_buffers (count);
3540 assert(_mix_buffers->available() >= count);
3541 _mix_buffers->set_count(count);
3542 return *_mix_buffers;
3547 Session::ntracks () const
3550 shared_ptr<RouteList> r = routes.reader ();
3552 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3553 if (boost::dynamic_pointer_cast<Track> (*i)) {
3562 Session::nbusses () const
3565 shared_ptr<RouteList> r = routes.reader ();
3567 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3568 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3577 Session::add_automation_list(AutomationList *al)
3579 automation_lists[al->id()] = al;
3583 Session::compute_initial_length ()
3585 return _engine.frame_rate() * 60 * 5;
3589 Session::sync_order_keys (std::string const & base)
3591 if (deletion_in_progress()) {
3595 if (!Config->get_sync_all_route_ordering()) {
3596 /* leave order keys as they are */
3600 boost::shared_ptr<RouteList> r = routes.reader ();
3602 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3603 (*i)->sync_order_keys (base);
3606 Route::SyncOrderKeys (base); // EMIT SIGNAL
3608 /* this might not do anything */
3610 set_remote_control_ids ();
3613 /** @return true if there is at least one record-enabled track, otherwise false */
3615 Session::have_rec_enabled_track () const
3617 return g_atomic_int_get (&_have_rec_enabled_track) == 1;
3620 /** Update the state of our rec-enabled tracks flag */
3622 Session::update_have_rec_enabled_track ()
3624 boost::shared_ptr<RouteList> rl = routes.reader ();
3625 RouteList::iterator i = rl->begin();
3626 while (i != rl->end ()) {
3628 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3629 if (tr && tr->record_enabled ()) {
3636 int const old = g_atomic_int_get (&_have_rec_enabled_track);
3638 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
3640 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
3641 RecordStateChanged (); /* EMIT SIGNAL */
3646 Session::listen_position_changed ()
3650 switch (Config->get_listen_position()) {
3651 case AfterFaderListen:
3655 case PreFaderListen:
3660 boost::shared_ptr<RouteList> r = routes.reader ();
3662 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3663 (*i)->put_monitor_send_at (p);
3668 Session::solo_control_mode_changed ()
3670 /* cancel all solo or all listen when solo control mode changes */
3673 set_solo (get_routes(), false);
3674 } else if (listening()) {
3675 set_listen (get_routes(), false);
3680 Session::route_group_changed ()
3682 RouteGroupChanged (); /* EMIT SIGNAL */
3686 Session::get_available_sync_options () const
3688 vector<SyncSource> ret;
3690 ret.push_back (JACK);
3693 ret.push_back (MTC);
3696 if (midi_clock_port()) {
3697 ret.push_back (MIDIClock);
3703 boost::shared_ptr<RouteList>
3704 Session::get_routes_with_regions_at (nframes64_t const p) const
3706 shared_ptr<RouteList> r = routes.reader ();
3707 shared_ptr<RouteList> rl (new RouteList);
3709 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3710 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3715 boost::shared_ptr<Playlist> pl = tr->playlist ();
3720 if (pl->has_region_at (p)) {