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.
20 #define __STDC_LIMIT_MACROS
28 #include <cstdio> /* sprintf(3) ... grrr */
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
36 #include <glibmm/fileutils.h>
38 #include "pbd/error.h"
39 #include "pbd/boost_debug.h"
40 #include "pbd/pathscanner.h"
41 #include "pbd/stl_delete.h"
42 #include "pbd/basename.h"
43 #include "pbd/stacktrace.h"
44 #include "pbd/file_utils.h"
45 #include "pbd/convert.h"
47 #include "ardour/amp.h"
48 #include "ardour/analyser.h"
49 #include "ardour/audio_buffer.h"
50 #include "ardour/audio_diskstream.h"
51 #include "ardour/audio_port.h"
52 #include "ardour/audio_track.h"
53 #include "ardour/audioengine.h"
54 #include "ardour/audiofilesource.h"
55 #include "ardour/audioplaylist.h"
56 #include "ardour/audioregion.h"
57 #include "ardour/auditioner.h"
58 #include "ardour/buffer_manager.h"
59 #include "ardour/buffer_set.h"
60 #include "ardour/bundle.h"
61 #include "ardour/butler.h"
62 #include "ardour/click.h"
63 #include "ardour/configuration.h"
64 #include "ardour/crossfade.h"
65 #include "ardour/cycle_timer.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/internal_send.h"
70 #include "ardour/io_processor.h"
71 #include "ardour/midi_diskstream.h"
72 #include "ardour/midi_playlist.h"
73 #include "ardour/midi_region.h"
74 #include "ardour/midi_track.h"
75 #include "ardour/midi_ui.h"
76 #include "ardour/named_selection.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/playlist.h"
79 #include "ardour/plugin_insert.h"
80 #include "ardour/port_insert.h"
81 #include "ardour/processor.h"
82 #include "ardour/rc_configuration.h"
83 #include "ardour/recent_sessions.h"
84 #include "ardour/region_factory.h"
85 #include "ardour/return.h"
86 #include "ardour/route_group.h"
87 #include "ardour/send.h"
88 #include "ardour/session.h"
89 #include "ardour/session_directory.h"
90 #include "ardour/session_directory.h"
91 #include "ardour/session_metadata.h"
92 #include "ardour/session_playlists.h"
93 #include "ardour/slave.h"
94 #include "ardour/smf_source.h"
95 #include "ardour/source_factory.h"
96 #include "ardour/tape_file_matcher.h"
97 #include "ardour/tempo.h"
98 #include "ardour/utils.h"
100 #include "midi++/jack.h"
105 using namespace ARDOUR;
107 using boost::shared_ptr;
108 using boost::weak_ptr;
110 bool Session::_disable_all_loaded_plugins = false;
112 PBD::Signal1<void,std::string> Session::Dialog;
113 PBD::Signal0<int> Session::AskAboutPendingState;
114 PBD::Signal2<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
115 PBD::Signal0<void> Session::SendFeedback;
117 PBD::Signal0<void> Session::TimecodeOffsetChanged;
118 PBD::Signal0<void> Session::StartTimeChanged;
119 PBD::Signal0<void> Session::EndTimeChanged;
120 PBD::Signal0<void> Session::AutoBindingOn;
121 PBD::Signal0<void> Session::AutoBindingOff;
122 PBD::Signal2<void,std::string, std::string> Session::Exported;
123 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
125 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
126 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
128 Session::Session (AudioEngine &eng,
129 const string& fullpath,
130 const string& snapshot_name,
131 BusProfile* bus_profile,
135 _target_transport_speed (0.0),
136 _requested_return_frame (-1),
138 _mmc_port (default_mmc_port),
139 _mtc_port (default_mtc_port),
140 _midi_port (default_midi_port),
141 _midi_clock_port (default_midi_clock_port),
142 _session_dir (new SessionDirectory(fullpath)),
144 _butler (new Butler (*this)),
145 _post_transport_work (0),
146 _send_timecode_update (false),
147 routes (new RouteList),
148 _total_free_4k_blocks (0),
149 _bundles (new BundleList),
150 _bundle_xml_node (0),
153 click_emphasis_data (0),
155 _metadata (new SessionMetadata()),
156 _have_rec_enabled_track (false)
159 playlists.reset (new SessionPlaylists);
161 interpolation.add_channel_to (0, 0);
163 if (!eng.connected()) {
164 throw failed_constructor();
167 n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
168 n_physical_inputs = _engine.n_physical_inputs(DataType::AUDIO);
170 first_stage_init (fullpath, snapshot_name);
172 _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
175 if (create (mix_template, compute_initial_length(), bus_profile)) {
177 throw failed_constructor ();
181 if (second_stage_init ()) {
183 throw failed_constructor ();
186 store_recent_sessions(_name, _path);
188 bool was_dirty = dirty();
190 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
192 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
193 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
196 DirtyChanged (); /* EMIT SIGNAL */
210 vector<void*> debug_pointers;
212 /* if we got to here, leaving pending capture state around
216 remove_pending_capture_state ();
218 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
220 _engine.remove_session ();
222 /* clear history so that no references to objects are held any more */
226 /* clear state tree so that no references to objects are held any more */
230 /* reset dynamic state version back to default */
232 Stateful::loading_state_version = 0;
234 _butler->drop_references ();
236 delete midi_control_ui;
238 if (click_data != default_click) {
239 delete [] click_data;
242 if (click_emphasis_data != default_click_emphasis) {
243 delete [] click_emphasis_data;
248 /* clear out any pending dead wood from RCU managed objects */
253 AudioDiskstream::free_working_buffers();
255 /* tell everyone who is still standing that we're about to die */
258 /* tell everyone to drop references and delete objects as we go */
260 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
261 named_selections.clear ();
263 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
264 RegionFactory::delete_all_regions ();
266 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
268 /* reset these three references to special routes before we do the usual route delete thing */
271 _master_out.reset ();
272 _monitor_out.reset ();
275 RCUWriter<RouteList> writer (routes);
276 boost::shared_ptr<RouteList> r = writer.get_copy ();
278 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
279 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
280 (*i)->drop_references ();
284 /* writer goes out of scope and updates master */
288 boost::shared_ptr<RouteList> r = routes.reader ();
290 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
291 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
292 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
293 i->second->drop_references ();
298 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
299 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
304 Crossfade::set_buffer_size (0);
308 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
311 boost_debug_list_ptrs ();
313 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
317 Session::set_worst_io_latencies ()
319 _worst_output_latency = 0;
320 _worst_input_latency = 0;
322 if (!_engine.connected()) {
326 boost::shared_ptr<RouteList> r = routes.reader ();
328 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
329 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
330 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
335 Session::when_engine_running ()
337 string first_physical_output;
339 BootMessage (_("Set block size and sample rate"));
341 set_block_size (_engine.frames_per_cycle());
342 set_frame_rate (_engine.frame_rate());
344 BootMessage (_("Using configuration"));
346 boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
347 boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
349 Config->map_parameters (ff);
350 config.map_parameters (ft);
352 /* every time we reconnect, recompute worst case output latencies */
354 _engine.Running.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies, this));
356 if (synced_to_jack()) {
357 _engine.transport_stop ();
360 if (config.get_jack_time_master()) {
361 _engine.transport_locate (_transport_frame);
369 _click_io.reset (new ClickIO (*this, "click"));
371 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
373 /* existing state for Click */
376 if (Stateful::loading_state_version < 3000) {
377 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
379 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
384 _clicking = Config->get_clicking ();
388 error << _("could not setup Click I/O") << endmsg;
395 /* default state for Click: dual-mono to first 2 physical outputs */
397 for (int physport = 0; physport < 2; ++physport) {
398 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
400 if (physical_output.length()) {
401 if (_click_io->add_port (physical_output, this)) {
402 // relax, even though its an error
407 if (_click_io->n_ports () > ChanCount::ZERO) {
408 _clicking = Config->get_clicking ();
413 catch (failed_constructor& err) {
414 error << _("cannot setup Click I/O") << endmsg;
417 BootMessage (_("Compute I/O Latencies"));
419 set_worst_io_latencies ();
422 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
425 BootMessage (_("Set up standard connections"));
427 /* Create a set of Bundle objects that map
428 to the physical I/O currently available. We create both
429 mono and stereo bundles, so that the common cases of mono
430 and stereo tracks get bundles to put in their mixer strip
431 in / out menus. There may be a nicer way of achieving that;
432 it doesn't really scale that well to higher channel counts
435 /* mono output bundles */
437 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
439 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
441 shared_ptr<Bundle> c (new Bundle (buf, true));
442 c->add_channel (_("mono"));
443 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
448 /* stereo output bundles */
450 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
451 if (np + 1 < n_physical_outputs) {
453 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
454 shared_ptr<Bundle> c (new Bundle (buf, true));
455 c->add_channel (_("L"));
456 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
457 c->add_channel (_("R"));
458 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
464 /* mono input bundles */
466 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
468 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
470 shared_ptr<Bundle> c (new Bundle (buf, false));
471 c->add_channel (_("mono"));
472 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
477 /* stereo input bundles */
479 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
480 if (np + 1 < n_physical_inputs) {
482 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
484 shared_ptr<Bundle> c (new Bundle (buf, false));
485 c->add_channel (_("L"));
486 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
487 c->add_channel (_("R"));
488 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
494 BootMessage (_("Setup signal flow and plugins"));
498 if (_is_new && !no_auto_connect()) {
500 /* don't connect the master bus outputs if there is a monitor bus */
502 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
504 /* if requested auto-connect the outputs to the first N physical ports.
507 uint32_t limit = _master_out->n_outputs().n_total();
509 for (uint32_t n = 0; n < limit; ++n) {
510 Port* p = _master_out->output()->nth (n);
511 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
513 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
514 if (_master_out->output()->connect (p, connect_to, this)) {
515 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
525 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
526 are undefined, at best.
529 /* control out listens to master bus (but ignores it
530 under some conditions)
533 uint32_t limit = _monitor_out->n_inputs().n_audio();
536 for (uint32_t n = 0; n < limit; ++n) {
537 AudioPort* p = _monitor_out->input()->ports().nth_audio_port (n);
538 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
541 string connect_to = o->name();
542 if (_monitor_out->input()->connect (p, connect_to, this)) {
543 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
551 /* if control out is not connected, connect control out to physical outs
554 if (!_monitor_out->output()->connected ()) {
556 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
558 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
561 _monitor_out->output()->connect_ports_to_bundle (b, this);
563 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
564 Config->get_monitor_bus_preferred_bundle())
570 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
571 uint32_t mod = _engine.n_physical_outputs (*t);
572 uint32_t limit = _monitor_out->n_outputs().get(*t);
574 for (uint32_t n = 0; n < limit; ++n) {
576 Port* p = _monitor_out->output()->ports().port(*t, n);
577 string connect_to = _engine.get_nth_physical_output (*t, (n % mod));
579 if (!connect_to.empty()) {
580 if (_monitor_out->output()->connect (p, connect_to, this)) {
581 error << string_compose (
582 _("cannot connect control output %1 to %2"),
595 /* catch up on send+insert cnts */
597 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
599 /* hook us up to the engine */
601 BootMessage (_("Connect to engine"));
603 _engine.set_session (this);
607 Session::hookup_io ()
609 /* stop graph reordering notifications from
610 causing resorts, etc.
613 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
618 /* we delay creating the auditioner till now because
619 it makes its own connections to ports.
623 Auditioner* a = new Auditioner (*this);
626 throw failed_constructor();
628 a->use_new_diskstream ();
629 auditioner.reset (a);
632 catch (failed_constructor& err) {
633 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
637 /* load bundles, which we may have postponed earlier on */
638 if (_bundle_xml_node) {
639 load_bundles (*_bundle_xml_node);
640 delete _bundle_xml_node;
643 /* Tell all IO objects to connect themselves together */
645 IO::enable_connecting ();
646 MIDI::JACK_MidiPort::MakeConnections ();
648 /* Now reset all panners */
650 Delivery::reset_panners ();
652 /* Connect tracks to monitor/listen bus if there is one.
653 Note that in an existing session, the internal sends will
654 already exist, but we want the routes to notice that
655 they connect to the control out specifically.
659 boost::shared_ptr<RouteList> r = routes.reader ();
660 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
662 if ((*x)->is_monitor()) {
666 } else if ((*x)->is_master()) {
672 (*x)->listen_via (_monitor_out,
673 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
679 /* Anyone who cares about input state, wake up and do something */
681 IOConnectionsComplete (); /* EMIT SIGNAL */
683 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
685 /* now handle the whole enchilada as if it was one
691 /* update the full solo state, which can't be
692 correctly determined on a per-route basis, but
693 needs the global overview that only the session
697 update_route_solo_state ();
701 Session::playlist_length_changed ()
703 /* we can't just increase session_range_location->end() if pl->get_maximum_extent()
704 if larger. if the playlist used to be the longest playlist,
705 and its now shorter, we have to decrease session_range_location->end(). hence,
706 we have to iterate over all diskstreams and check the
707 playlists currently in use.
713 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
715 boost::shared_ptr<Track> track = wp.lock ();
720 boost::shared_ptr<Playlist> playlist;
722 if ((playlist = track->playlist()) != 0) {
723 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
726 /* see comment in playlist_length_changed () */
731 Session::record_enabling_legal () const
733 /* this used to be in here, but survey says.... we don't need to restrict it */
734 // if (record_status() == Recording) {
738 if (Config->get_all_safe()) {
745 Session::reset_input_monitor_state ()
747 if (transport_rolling()) {
749 boost::shared_ptr<RouteList> rl = routes.reader ();
750 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
751 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
752 if (tr && tr->record_enabled ()) {
753 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
754 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
760 boost::shared_ptr<RouteList> rl = routes.reader ();
761 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
762 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
763 if (tr && tr->record_enabled ()) {
764 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
765 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
772 Session::auto_punch_start_changed (Location* location)
774 replace_event (SessionEvent::PunchIn, location->start());
776 if (get_record_enabled() && config.get_punch_in()) {
777 /* capture start has been changed, so save new pending state */
778 save_state ("", true);
783 Session::auto_punch_end_changed (Location* location)
785 nframes_t when_to_stop = location->end();
786 // when_to_stop += _worst_output_latency + _worst_input_latency;
787 replace_event (SessionEvent::PunchOut, when_to_stop);
791 Session::auto_punch_changed (Location* location)
793 nframes_t when_to_stop = location->end();
795 replace_event (SessionEvent::PunchIn, location->start());
796 //when_to_stop += _worst_output_latency + _worst_input_latency;
797 replace_event (SessionEvent::PunchOut, when_to_stop);
801 Session::auto_loop_changed (Location* location)
803 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
805 if (transport_rolling() && play_loop) {
808 // if (_transport_frame > location->end()) {
810 if (_transport_frame < location->start() || _transport_frame > location->end()) {
811 // relocate to beginning of loop
812 clear_events (SessionEvent::LocateRoll);
814 request_locate (location->start(), true);
817 else if (Config->get_seamless_loop() && !loop_changing) {
819 // schedule a locate-roll to refill the diskstreams at the
821 loop_changing = true;
823 if (location->end() > last_loopend) {
824 clear_events (SessionEvent::LocateRoll);
825 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
832 last_loopend = location->end();
836 Session::set_auto_punch_location (Location* location)
840 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
841 punch_connections.drop_connections();
842 existing->set_auto_punch (false, this);
843 remove_event (existing->start(), SessionEvent::PunchIn);
844 clear_events (SessionEvent::PunchOut);
845 auto_punch_location_changed (0);
854 if (location->end() <= location->start()) {
855 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
859 punch_connections.drop_connections ();
861 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
862 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
863 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
865 location->set_auto_punch (true, this);
867 auto_punch_changed (location);
869 auto_punch_location_changed (location);
873 Session::set_auto_loop_location (Location* location)
877 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
878 loop_connections.drop_connections ();
879 existing->set_auto_loop (false, this);
880 remove_event (existing->end(), SessionEvent::AutoLoop);
881 auto_loop_location_changed (0);
890 if (location->end() <= location->start()) {
891 error << _("Session: you can't use a mark for auto loop") << endmsg;
895 last_loopend = location->end();
897 loop_connections.drop_connections ();
899 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
900 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
901 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
903 location->set_auto_loop (true, this);
905 /* take care of our stuff first */
907 auto_loop_changed (location);
909 /* now tell everyone else */
911 auto_loop_location_changed (location);
915 Session::locations_added (Location *)
921 Session::locations_changed ()
923 _locations.apply (*this, &Session::handle_locations_changed);
927 Session::handle_locations_changed (Locations::LocationList& locations)
929 Locations::LocationList::iterator i;
931 bool set_loop = false;
932 bool set_punch = false;
934 for (i = locations.begin(); i != locations.end(); ++i) {
938 if (location->is_auto_punch()) {
939 set_auto_punch_location (location);
942 if (location->is_auto_loop()) {
943 set_auto_loop_location (location);
947 if (location->is_session_range()) {
948 _session_range_location = location;
953 set_auto_loop_location (0);
956 set_auto_punch_location (0);
963 Session::enable_record ()
965 /* XXX really atomic compare+swap here */
966 if (g_atomic_int_get (&_record_status) != Recording) {
967 g_atomic_int_set (&_record_status, Recording);
968 _last_record_location = _transport_frame;
969 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
971 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
973 boost::shared_ptr<RouteList> rl = routes.reader ();
974 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
975 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
976 if (tr && tr->record_enabled ()) {
977 tr->monitor_input (true);
982 RecordStateChanged ();
987 Session::disable_record (bool rt_context, bool force)
991 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
993 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
994 g_atomic_int_set (&_record_status, Disabled);
996 if (rs == Recording) {
997 g_atomic_int_set (&_record_status, Enabled);
1001 // FIXME: timestamp correct? [DR]
1002 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1003 // does this /need/ to be sent in all cases?
1005 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1008 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1010 boost::shared_ptr<RouteList> rl = routes.reader ();
1011 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1012 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1013 if (tr && tr->record_enabled ()) {
1014 tr->monitor_input (false);
1019 RecordStateChanged (); /* emit signal */
1022 remove_pending_capture_state ();
1028 Session::step_back_from_record ()
1030 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1032 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1033 boost::shared_ptr<RouteList> rl = routes.reader ();
1034 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1035 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1036 if (tr && tr->record_enabled ()) {
1037 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1038 tr->monitor_input (false);
1046 Session::maybe_enable_record ()
1048 g_atomic_int_set (&_record_status, Enabled);
1050 /* this function is currently called from somewhere other than an RT thread.
1051 this save_state() call therefore doesn't impact anything.
1054 save_state ("", true);
1056 if (_transport_speed) {
1057 if (!config.get_punch_in()) {
1061 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1062 RecordStateChanged (); /* EMIT SIGNAL */
1069 Session::audible_frame () const
1075 /* the first of these two possible settings for "offset"
1076 mean that the audible frame is stationary until
1077 audio emerges from the latency compensation
1080 the second means that the audible frame is stationary
1081 until audio would emerge from a physical port
1082 in the absence of any plugin latency compensation
1085 offset = _worst_output_latency;
1087 if (offset > current_block_size) {
1088 offset -= current_block_size;
1090 /* XXX is this correct? if we have no external
1091 physical connections and everything is internal
1092 then surely this is zero? still, how
1093 likely is that anyway?
1095 offset = current_block_size;
1098 if (synced_to_jack()) {
1099 tf = _engine.transport_frame();
1101 tf = _transport_frame;
1106 if (!non_realtime_work_pending()) {
1110 /* Check to see if we have passed the first guaranteed
1111 audible frame past our last start position. if not,
1112 return that last start point because in terms
1113 of audible frames, we have not moved yet.
1115 `Start position' in this context means the time we last
1116 either started or changed transport direction.
1119 if (_transport_speed > 0.0f) {
1121 if (!play_loop || !have_looped) {
1122 if (tf < _last_roll_or_reversal_location + offset) {
1123 return _last_roll_or_reversal_location;
1131 } else if (_transport_speed < 0.0f) {
1133 /* XXX wot? no backward looping? */
1135 if (tf > _last_roll_or_reversal_location - offset) {
1136 return _last_roll_or_reversal_location;
1148 Session::set_frame_rate (nframes_t frames_per_second)
1150 /** \fn void Session::set_frame_size(nframes_t)
1151 the AudioEngine object that calls this guarantees
1152 that it will not be called while we are also in
1153 ::process(). Its fine to do things that block
1157 _base_frame_rate = frames_per_second;
1161 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1165 // XXX we need some equivalent to this, somehow
1166 // SndFileSource::setup_standard_crossfades (frames_per_second);
1170 /* XXX need to reset/reinstantiate all LADSPA plugins */
1174 Session::set_block_size (nframes_t nframes)
1176 /* the AudioEngine guarantees
1177 that it will not be called while we are also in
1178 ::process(). It is therefore fine to do things that block
1183 current_block_size = nframes;
1187 boost::shared_ptr<RouteList> r = routes.reader ();
1189 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1190 (*i)->set_block_size (nframes);
1193 boost::shared_ptr<RouteList> rl = routes.reader ();
1194 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1195 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1197 tr->set_block_size (nframes);
1201 set_worst_io_latencies ();
1206 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1209 nframes_t fade_frames;
1211 /* Don't allow fade of less 1 frame */
1213 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1220 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1224 default_fade_msecs = fade_msecs;
1225 default_fade_steepness = steepness;
1228 // jlc, WTF is this!
1229 Glib::RWLock::ReaderLock lm (route_lock);
1230 AudioRegion::set_default_fade (steepness, fade_frames);
1235 /* XXX have to do this at some point */
1236 /* foreach region using default fade, reset, then
1237 refill_all_diskstream_buffers ();
1242 struct RouteSorter {
1243 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1244 if (r2->feeds (r1)) {
1246 } else if (r1->feeds (r2)) {
1249 if (r1->not_fed ()) {
1250 if (r2->not_fed ()) {
1251 /* no ardour-based connections inbound to either route. just use signal order */
1252 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1254 /* r2 has connections, r1 does not; run r1 early */
1258 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1265 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1267 shared_ptr<Route> r2;
1269 if (r1->feeds (rbase) && rbase->feeds (r1)) {
1270 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1274 /* make a copy of the existing list of routes that feed r1 */
1276 Route::FedBy existing (r1->fed_by());
1278 /* for each route that feeds r1, recurse, marking it as feeding
1282 for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1283 if (!(r2 = i->r.lock ())) {
1284 /* (*i) went away, ignore it */
1288 /* r2 is a route that feeds r1 which somehow feeds base. mark
1289 base as being fed by r2
1292 rbase->add_fed_by (r2, i->sends_only);
1296 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1300 if (r1->feeds (r2) && r2->feeds (r1)) {
1304 /* now recurse, so that we can mark base as being fed by
1305 all routes that feed r2
1308 trace_terminal (r2, rbase);
1315 Session::resort_routes ()
1317 /* don't do anything here with signals emitted
1318 by Routes while we are being destroyed.
1321 if (_state_of_the_state & Deletion) {
1328 RCUWriter<RouteList> writer (routes);
1329 shared_ptr<RouteList> r = writer.get_copy ();
1330 resort_routes_using (r);
1331 /* writer goes out of scope and forces update */
1335 boost::shared_ptr<RouteList> rl = routes.reader ();
1336 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1337 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1339 const Route::FedBy& fb ((*i)->fed_by());
1341 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1342 boost::shared_ptr<Route> sf = f->r.lock();
1344 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1352 Session::resort_routes_using (shared_ptr<RouteList> r)
1354 RouteList::iterator i, j;
1356 for (i = r->begin(); i != r->end(); ++i) {
1357 (*i)->check_physical_connections ();
1360 for (i = r->begin(); i != r->end(); ++i) {
1362 (*i)->clear_fed_by ();
1364 for (j = r->begin(); j != r->end(); ++j) {
1366 /* although routes can feed themselves, it will
1367 cause an endless recursive descent if we
1368 detect it. so don't bother checking for
1376 bool via_sends_only;
1378 if ((*j)->direct_feeds (*i, &via_sends_only)) {
1379 (*i)->add_fed_by (*j, via_sends_only);
1384 for (i = r->begin(); i != r->end(); ++i) {
1385 trace_terminal (*i, *i);
1391 find_route_levels (r);
1394 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1395 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1396 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2 level %3\n",
1397 (*i)->name(), (*i)->order_key ("signal"),
1398 (*i)->graph_level()));
1405 Session::find_route_levels (shared_ptr<RouteList> rl)
1407 uint32_t setcnt = 0;
1408 uint32_t limit = rl->size();
1409 RouteList last_level;
1410 RouteList this_level;
1412 for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
1414 /* find routes with direct physical connections,
1415 or routes with no connections at all. Mark them
1416 with "special" level values, and push them into
1417 the "last_level" set.
1419 All other routes get marked with a graph level
1420 of -1, which indicates that it needs to be set.
1424 if ((*r)->physically_connected()) {
1425 last_level.push_back (*r);
1426 (*r)->set_graph_level (0);
1428 } else if (!(*r)->output()->connected()) {
1429 last_level.push_back (*r);
1430 (*r)->set_graph_level (INT32_MAX/2);
1433 (*r)->set_graph_level (-1);
1437 // until we've set the graph level for every route ...
1439 while (setcnt < limit) {
1441 for (RouteList::reverse_iterator r = rl->rbegin(); r != rl->rend(); ++r) {
1443 int32_t l = INT32_MAX;
1446 if ((*r)->graph_level() != -1) {
1447 // we already have the graph level for this route
1451 /* check if this route (r) has a direction connection to anything in
1452 the set of routes we processed last time. On the first pass
1453 through this, last_level will contain routes with either
1454 no connections or direct "physical" connections. If there is
1455 at least 1 connection, store the lowest graph level of whatever
1459 for (RouteList::iterator o = last_level.begin(); o != last_level.end(); ++o) {
1461 if ((*r)->direct_feeds (*o, &sends_only)) {
1463 l = min (l, (*o)->graph_level());
1469 /* if we found any connections, then mark the graph level of r, and push
1470 it into the "this_level" set that will become "last_level" next time
1471 around the while() loop.
1475 (*r)->set_graph_level (l + 1);
1476 this_level.push_back (*r);
1481 last_level = this_level;
1482 this_level.clear ();
1487 /** Find the route name starting with \a base with the lowest \a id.
1489 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1490 * The available route name with the lowest ID will be used, and \a id
1491 * will be set to the ID.
1493 * \return false if a route name could not be found, and \a track_name
1494 * and \a id do not reflect a free route name.
1497 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1500 snprintf (name, name_len, "%s %" PRIu32, base, id);
1502 if (route_by_name (name) == 0) {
1508 } while (id < (UINT_MAX-1));
1514 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1516 in = ChanCount::ZERO;
1517 out = ChanCount::ZERO;
1518 shared_ptr<RouteList> r = routes.reader ();
1519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1520 if (!(*i)->is_hidden()) {
1521 in += (*i)->n_inputs();
1522 out += (*i)->n_outputs();
1527 list<boost::shared_ptr<MidiTrack> >
1528 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1530 char track_name[32];
1531 uint32_t track_id = 0;
1532 ChanCount existing_inputs;
1533 ChanCount existing_outputs;
1535 RouteList new_routes;
1536 list<boost::shared_ptr<MidiTrack> > ret;
1537 uint32_t control_id;
1539 count_existing_route_channels (existing_inputs, existing_outputs);
1541 control_id = ntracks() + nbusses();
1544 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1545 error << "cannot find name for new midi track" << endmsg;
1549 shared_ptr<MidiTrack> track;
1552 MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1559 mt->use_new_diskstream();
1561 boost_debug_shared_ptr_mark_interesting (mt, "Track");
1562 track = boost::shared_ptr<MidiTrack>(mt);
1564 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1565 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1570 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1571 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1575 auto_connect_route (track, existing_inputs, existing_outputs);
1577 track->non_realtime_input_change();
1579 route_group->add (track);
1582 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1583 track->set_remote_control_id (control_id);
1585 new_routes.push_back (track);
1586 ret.push_back (track);
1589 catch (failed_constructor &err) {
1590 error << _("Session: could not create new midi track.") << endmsg;
1594 catch (AudioEngine::PortRegistrationFailure& pfe) {
1596 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;
1604 if (!new_routes.empty()) {
1605 add_routes (new_routes, false);
1606 save_state (_current_snapshot_name);
1613 Session::auto_connect_route (boost::shared_ptr<Route> route,
1614 ChanCount& existing_inputs, ChanCount& existing_outputs)
1616 /* If both inputs and outputs are auto-connected to physical ports,
1617 use the max of input and output offsets to ensure auto-connected
1618 port numbers always match up (e.g. the first audio input and the
1619 first audio output of the route will have the same physical
1620 port number). Otherwise just use the lowest input or output
1623 const bool in_out_physical =
1624 (Config->get_input_auto_connect() & AutoConnectPhysical)
1625 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1627 const ChanCount in_offset = in_out_physical
1628 ? ChanCount::max(existing_inputs, existing_outputs)
1631 const ChanCount out_offset = in_out_physical
1632 ? ChanCount::max(existing_inputs, existing_outputs)
1635 static string empty_string;
1636 string& port = empty_string;
1638 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1639 vector<string> physinputs;
1640 vector<string> physoutputs;
1642 _engine.get_physical_outputs (*t, physoutputs);
1643 _engine.get_physical_inputs (*t, physinputs);
1645 if (!physinputs.empty()) {
1646 uint32_t nphysical_in = physinputs.size();
1647 for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1648 port = empty_string;
1650 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1651 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1654 if (!port.empty() && route->input()->connect (
1655 route->input()->ports().port(*t, i), port, this)) {
1661 if (!physoutputs.empty()) {
1662 uint32_t nphysical_out = physoutputs.size();
1663 for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1664 port = empty_string;
1666 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1667 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1668 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1669 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1670 port = _master_out->input()->ports().port(*t,
1671 i % _master_out->input()->n_ports().get(*t))->name();
1675 if (!port.empty() && route->output()->connect (
1676 route->output()->ports().port(*t, i), port, this)) {
1683 existing_inputs += route->n_inputs();
1684 existing_outputs += route->n_outputs();
1687 list< boost::shared_ptr<AudioTrack> >
1688 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1690 char track_name[32];
1691 uint32_t track_id = 0;
1692 ChanCount existing_inputs;
1693 ChanCount existing_outputs;
1695 RouteList new_routes;
1696 list<boost::shared_ptr<AudioTrack> > ret;
1697 uint32_t control_id;
1699 count_existing_route_channels (existing_inputs, existing_outputs);
1701 control_id = ntracks() + nbusses() + 1;
1704 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1705 error << "cannot find name for new audio track" << endmsg;
1709 shared_ptr<AudioTrack> track;
1712 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1719 at->use_new_diskstream();
1721 boost_debug_shared_ptr_mark_interesting (at, "Track");
1722 track = boost::shared_ptr<AudioTrack>(at);
1724 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1725 error << string_compose (
1726 _("cannot configure %1 in/%2 out configuration for new audio track"),
1727 input_channels, output_channels)
1732 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1733 error << string_compose (
1734 _("cannot configure %1 in/%2 out configuration for new audio track"),
1735 input_channels, output_channels)
1740 auto_connect_route (track, existing_inputs, existing_outputs);
1743 route_group->add (track);
1746 track->non_realtime_input_change();
1748 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1749 track->set_remote_control_id (control_id);
1752 new_routes.push_back (track);
1753 ret.push_back (track);
1756 catch (failed_constructor &err) {
1757 error << _("Session: could not create new audio track.") << endmsg;
1761 catch (AudioEngine::PortRegistrationFailure& pfe) {
1763 error << pfe.what() << endmsg;
1771 if (!new_routes.empty()) {
1772 add_routes (new_routes, true);
1779 Session::set_remote_control_ids ()
1781 RemoteModel m = Config->get_remote_model();
1782 bool emit_signal = false;
1784 shared_ptr<RouteList> r = routes.reader ();
1786 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1787 if (MixerOrdered == m) {
1788 long order = (*i)->order_key(N_("signal"));
1789 (*i)->set_remote_control_id (order+1, false);
1791 } else if (EditorOrdered == m) {
1792 long order = (*i)->order_key(N_("editor"));
1793 (*i)->set_remote_control_id (order+1, false);
1795 } else if (UserOrdered == m) {
1796 //do nothing ... only changes to remote id's are initiated by user
1801 Route::RemoteControlIDChange();
1807 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1810 uint32_t bus_id = 0;
1811 ChanCount existing_inputs;
1812 ChanCount existing_outputs;
1815 uint32_t control_id;
1817 count_existing_route_channels (existing_inputs, existing_outputs);
1819 control_id = ntracks() + nbusses() + 1;
1822 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1823 error << "cannot find name for new audio bus" << endmsg;
1828 Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1835 boost_debug_shared_ptr_mark_interesting (rt, "Route");
1836 shared_ptr<Route> bus (rt);
1838 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1839 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1840 input_channels, output_channels)
1846 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1847 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1848 input_channels, output_channels)
1853 auto_connect_route (bus, existing_inputs, existing_outputs);
1856 route_group->add (bus);
1858 bus->set_remote_control_id (control_id);
1862 bus->add_internal_return ();
1865 ret.push_back (bus);
1869 catch (failed_constructor &err) {
1870 error << _("Session: could not create new audio route.") << endmsg;
1874 catch (AudioEngine::PortRegistrationFailure& pfe) {
1875 error << pfe.what() << endmsg;
1885 add_routes (ret, true);
1893 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1897 uint32_t control_id;
1899 uint32_t number = 0;
1901 if (!tree.read (template_path.c_str())) {
1905 XMLNode* node = tree.root();
1907 control_id = ntracks() + nbusses() + 1;
1911 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1913 std::string node_name = IO::name_from_state (*node_copy.children().front());
1915 /* generate a new name by adding a number to the end of the template name */
1916 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1917 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1921 IO::set_name_in_state (*node_copy.children().front(), name);
1923 Track::zero_diskstream_id_in_xml (node_copy);
1926 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1929 error << _("Session: cannot create track/bus from template description") << endmsg;
1933 if (boost::dynamic_pointer_cast<Track>(route)) {
1934 /* force input/output change signals so that the new diskstream
1935 picks up the configuration of the route. During session
1936 loading this normally happens in a different way.
1938 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1939 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1942 route->set_remote_control_id (control_id);
1945 ret.push_back (route);
1948 catch (failed_constructor &err) {
1949 error << _("Session: could not create new route from template") << endmsg;
1953 catch (AudioEngine::PortRegistrationFailure& pfe) {
1954 error << pfe.what() << endmsg;
1963 add_routes (ret, true);
1970 Session::add_routes (RouteList& new_routes, bool save)
1973 RCUWriter<RouteList> writer (routes);
1974 shared_ptr<RouteList> r = writer.get_copy ();
1975 r->insert (r->end(), new_routes.begin(), new_routes.end());
1978 /* if there is no control out and we're not in the middle of loading,
1979 resort the graph here. if there is a control out, we will resort
1980 toward the end of this method. if we are in the middle of loading,
1981 we will resort when done.
1984 if (!_monitor_out && IO::connecting_legal) {
1985 resort_routes_using (r);
1989 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1991 boost::weak_ptr<Route> wpr (*x);
1992 boost::shared_ptr<Route> r (*x);
1994 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1995 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
1996 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1997 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1998 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1999 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
2001 if (r->is_master()) {
2005 if (r->is_monitor()) {
2009 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2011 tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2012 track_playlist_changed (boost::weak_ptr<Track> (tr));
2013 tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2017 if (_monitor_out && IO::connecting_legal) {
2019 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2020 if ((*x)->is_monitor()) {
2022 } else if ((*x)->is_master()) {
2025 (*x)->listen_via (_monitor_out,
2026 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
2037 save_state (_current_snapshot_name);
2040 RouteAdded (new_routes); /* EMIT SIGNAL */
2041 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
2045 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2047 boost::shared_ptr<RouteList> r = routes.reader ();
2048 boost::shared_ptr<Send> s;
2052 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2053 if (boost::dynamic_pointer_cast<Track>(*i)) {
2054 if ((s = (*i)->internal_send_for (dest)) != 0) {
2055 s->amp()->gain_control()->set_value (0.0);
2062 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2064 boost::shared_ptr<RouteList> r = routes.reader ();
2065 boost::shared_ptr<Send> s;
2069 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2070 if (boost::dynamic_pointer_cast<Track>(*i)) {
2071 if ((s = (*i)->internal_send_for (dest)) != 0) {
2072 s->amp()->gain_control()->set_value (1.0);
2079 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2081 boost::shared_ptr<RouteList> r = routes.reader ();
2082 boost::shared_ptr<Send> s;
2086 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2087 if (boost::dynamic_pointer_cast<Track>(*i)) {
2088 if ((s = (*i)->internal_send_for (dest)) != 0) {
2089 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2096 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2098 boost::shared_ptr<RouteList> r = routes.reader ();
2099 boost::shared_ptr<RouteList> t (new RouteList);
2101 /* only send tracks */
2103 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2104 if (boost::dynamic_pointer_cast<Track>(*i)) {
2109 add_internal_sends (dest, p, t);
2113 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2115 if (dest->is_monitor() || dest->is_master()) {
2119 if (!dest->internal_return()) {
2120 dest->add_internal_return();
2123 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2125 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2129 (*i)->listen_via (dest, p, true, true);
2136 Session::remove_route (shared_ptr<Route> route)
2139 RCUWriter<RouteList> writer (routes);
2140 shared_ptr<RouteList> rs = writer.get_copy ();
2144 /* deleting the master out seems like a dumb
2145 idea, but its more of a UI policy issue
2149 if (route == _master_out) {
2150 _master_out = shared_ptr<Route> ();
2153 if (route == _monitor_out) {
2155 /* cancel control outs for all routes */
2157 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2158 (*r)->drop_listen (_monitor_out);
2161 _monitor_out.reset ();
2164 update_route_solo_state ();
2166 /* writer goes out of scope, forces route list update */
2169 find_current_end ();
2171 // We need to disconnect the routes inputs and outputs
2173 route->input()->disconnect (0);
2174 route->output()->disconnect (0);
2176 /* if the route had internal sends sending to it, remove them */
2177 if (route->internal_return()) {
2179 boost::shared_ptr<RouteList> r = routes.reader ();
2180 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2181 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2183 (*i)->remove_processor (s);
2188 update_latency_compensation (false, false);
2191 /* get rid of it from the dead wood collection in the route list manager */
2193 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2197 /* try to cause everyone to drop their references */
2199 route->drop_references ();
2201 sync_order_keys (N_("session"));
2203 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2205 /* save the new state of the world */
2207 if (save_state (_current_snapshot_name)) {
2208 save_history (_current_snapshot_name);
2213 Session::route_mute_changed (void* /*src*/)
2219 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2221 boost::shared_ptr<Route> route = wpr.lock();
2223 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2227 if (route->listening()) {
2229 } else if (_listen_cnt > 0) {
2235 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2237 if (!self_solo_change) {
2238 // session doesn't care about changes to soloed-by-others
2242 if (solo_update_disabled) {
2247 boost::shared_ptr<Route> route = wpr.lock ();
2250 /* should not happen */
2251 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2255 shared_ptr<RouteList> r = routes.reader ();
2258 if (route->self_soloed()) {
2264 solo_update_disabled = true;
2269 for anything in the signal path for this route, increment its soloed-by-other count
2270 for anything not in the signal path for this route, increment its muted-by-other count
2273 for anything in the signal path for this route, decrement its soloed-by-other count
2274 for anything not in the signal path for this route, decrement its muted-by-other count
2278 RouteList uninvolved;
2280 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2281 bool via_sends_only;
2283 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2287 if ((*i)->graph_level () == route->graph_level()) {
2288 (*i)->mod_muted_by_others (delta);
2291 /* feed-backwards (other route to solo change route):
2293 if (*i) feeds the one whose solo status changed
2294 it should be soloed by other if the change was -> solo OR de-soloed by other if change was -> !solo
2300 if ((*i)->feeds (route, &via_sends_only)) {
2301 if (!via_sends_only) {
2302 (*i)->mod_solo_by_others_upstream (delta);
2306 /* feed-forward (solo change route to other routes):
2308 if the route whose solo status changed feeds (*i)
2311 mute if the change was -> solo OR demute if change was -> !solo
2314 if (route->feeds (*i, &via_sends_only)) {
2315 (*i)->mod_solo_by_others_downstream (delta);
2319 solo_update_disabled = false;
2320 update_route_solo_state (r);
2321 SoloChanged (); /* EMIT SIGNAL */
2326 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2328 /* now figure out if anything that matters is soloed (or is "listening")*/
2330 bool something_soloed = false;
2331 uint32_t listeners = 0;
2334 r = routes.reader();
2337 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2338 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2339 something_soloed = true;
2343 if (!(*i)->is_hidden() && (*i)->listening()) {
2344 if (Config->get_solo_control_is_listen_control()) {
2347 (*i)->set_listen (false, this);
2352 if (something_soloed != _non_soloed_outs_muted) {
2353 _non_soloed_outs_muted = something_soloed;
2354 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2358 _listen_cnt = listeners;
2362 boost::shared_ptr<RouteList>
2363 Session::get_routes_with_internal_returns() const
2365 shared_ptr<RouteList> r = routes.reader ();
2366 boost::shared_ptr<RouteList> rl (new RouteList);
2368 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2369 if ((*i)->internal_return ()) {
2377 Session::io_name_is_legal (const std::string& name)
2379 shared_ptr<RouteList> r = routes.reader ();
2381 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2382 if ((*i)->name() == name) {
2386 if ((*i)->has_io_processor_named (name)) {
2395 Session::route_by_name (string name)
2397 shared_ptr<RouteList> r = routes.reader ();
2399 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2400 if ((*i)->name() == name) {
2405 return shared_ptr<Route> ((Route*) 0);
2409 Session::route_by_id (PBD::ID id)
2411 shared_ptr<RouteList> r = routes.reader ();
2413 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2414 if ((*i)->id() == id) {
2419 return shared_ptr<Route> ((Route*) 0);
2423 Session::route_by_remote_id (uint32_t id)
2425 shared_ptr<RouteList> r = routes.reader ();
2427 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2428 if ((*i)->remote_control_id() == id) {
2433 return shared_ptr<Route> ((Route*) 0);
2437 Session::find_current_end ()
2439 if (_state_of_the_state & Loading) {
2443 nframes_t max = get_maximum_extent ();
2445 if (max > _session_range_location->end()) {
2446 _session_range_location->set_end (max);
2448 DurationChanged(); /* EMIT SIGNAL */
2453 Session::get_maximum_extent () const
2458 boost::shared_ptr<RouteList> rl = routes.reader ();
2459 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2460 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2461 if (!tr || tr->destructive()) {
2462 //ignore tape tracks when getting max extents
2466 boost::shared_ptr<Playlist> pl = tr->playlist();
2467 if ((me = pl->get_maximum_extent()) > max) {
2475 /* Region management */
2477 boost::shared_ptr<Region>
2478 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2480 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2481 RegionFactory::RegionMap::const_iterator i;
2482 boost::shared_ptr<Region> region;
2484 Glib::Mutex::Lock lm (region_lock);
2486 for (i = regions.begin(); i != regions.end(); ++i) {
2490 if (region->whole_file()) {
2492 if (child->source_equivalent (region)) {
2498 return boost::shared_ptr<Region> ();
2502 Session::destroy_region (boost::shared_ptr<Region> region)
2504 vector<boost::shared_ptr<Source> > srcs;
2507 if (region->playlist()) {
2508 region->playlist()->destroy_region (region);
2511 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2512 srcs.push_back (region->source (n));
2516 region->drop_references ();
2518 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2520 (*i)->mark_for_remove ();
2521 (*i)->drop_references ();
2523 cerr << "source was not used by any playlist\n";
2530 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2532 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2533 destroy_region (*i);
2539 Session::remove_last_capture ()
2541 list<boost::shared_ptr<Region> > r;
2543 boost::shared_ptr<RouteList> rl = routes.reader ();
2544 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2545 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2550 list<boost::shared_ptr<Region> >& l = tr->last_capture_regions();
2553 r.insert (r.end(), l.begin(), l.end());
2558 destroy_regions (r);
2560 save_state (_current_snapshot_name);
2565 /* Source Management */
2568 Session::add_source (boost::shared_ptr<Source> source)
2570 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2571 pair<SourceMap::iterator,bool> result;
2573 entry.first = source->id();
2574 entry.second = source;
2577 Glib::Mutex::Lock lm (source_lock);
2578 result = sources.insert (entry);
2581 if (result.second) {
2585 boost::shared_ptr<AudioFileSource> afs;
2587 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2588 if (Config->get_auto_analyse_audio()) {
2589 Analyser::queue_source_for_analysis (source, false);
2595 Session::remove_source (boost::weak_ptr<Source> src)
2597 SourceMap::iterator i;
2598 boost::shared_ptr<Source> source = src.lock();
2605 Glib::Mutex::Lock lm (source_lock);
2607 if ((i = sources.find (source->id())) != sources.end()) {
2612 if (!_state_of_the_state & InCleanup) {
2614 /* save state so we don't end up with a session file
2615 referring to non-existent sources.
2618 save_state (_current_snapshot_name);
2622 boost::shared_ptr<Source>
2623 Session::source_by_id (const PBD::ID& id)
2625 Glib::Mutex::Lock lm (source_lock);
2626 SourceMap::iterator i;
2627 boost::shared_ptr<Source> source;
2629 if ((i = sources.find (id)) != sources.end()) {
2636 boost::shared_ptr<Source>
2637 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2639 Glib::Mutex::Lock lm (source_lock);
2641 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2642 cerr << "comparing " << path << " with " << i->second->name() << endl;
2643 boost::shared_ptr<AudioFileSource> afs
2644 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2646 if (afs && afs->path() == path && chn == afs->channel()) {
2650 return boost::shared_ptr<Source>();
2655 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2658 string old_basename = PBD::basename_nosuffix (oldname);
2659 string new_legalized = legalize_for_path (newname);
2661 /* note: we know (or assume) the old path is already valid */
2665 /* destructive file sources have a name of the form:
2667 /path/to/Tnnnn-NAME(%[LR])?.wav
2669 the task here is to replace NAME with the new name.
2672 /* find last slash */
2676 string::size_type slash;
2677 string::size_type dash;
2679 if ((slash = path.find_last_of ('/')) == string::npos) {
2683 dir = path.substr (0, slash+1);
2685 /* '-' is not a legal character for the NAME part of the path */
2687 if ((dash = path.find_last_of ('-')) == string::npos) {
2691 prefix = path.substr (slash+1, dash-(slash+1));
2696 path += new_legalized;
2697 path += ".wav"; /* XXX gag me with a spoon */
2701 /* non-destructive file sources have a name of the form:
2703 /path/to/NAME-nnnnn(%[LR])?.ext
2705 the task here is to replace NAME with the new name.
2710 string::size_type slash;
2711 string::size_type dash;
2712 string::size_type postfix;
2714 /* find last slash */
2716 if ((slash = path.find_last_of ('/')) == string::npos) {
2720 dir = path.substr (0, slash+1);
2722 /* '-' is not a legal character for the NAME part of the path */
2724 if ((dash = path.find_last_of ('-')) == string::npos) {
2728 suffix = path.substr (dash+1);
2730 // Suffix is now everything after the dash. Now we need to eliminate
2731 // the nnnnn part, which is done by either finding a '%' or a '.'
2733 postfix = suffix.find_last_of ("%");
2734 if (postfix == string::npos) {
2735 postfix = suffix.find_last_of ('.');
2738 if (postfix != string::npos) {
2739 suffix = suffix.substr (postfix);
2741 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2745 const uint32_t limit = 10000;
2746 char buf[PATH_MAX+1];
2748 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2750 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2752 if (access (buf, F_OK) != 0) {
2760 error << "FATAL ERROR! Could not find a " << endl;
2768 /** Return the full path (in some session directory) for a new within-session source.
2769 * \a name must be a session-unique name that does not contain slashes
2770 * (e.g. as returned by new_*_source_name)
2773 Session::new_source_path_from_name (DataType type, const string& name)
2775 assert(name.find("/") == string::npos);
2777 SessionDirectory sdir(get_best_session_directory_for_new_source());
2780 if (type == DataType::AUDIO) {
2781 p = sdir.sound_path();
2782 } else if (type == DataType::MIDI) {
2783 p = sdir.midi_path();
2785 error << "Unknown source type, unable to create file path" << endmsg;
2790 return p.to_string();
2794 Session::peak_path (Glib::ustring base) const
2796 sys::path peakfile_path(_session_dir->peak_path());
2797 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2798 return peakfile_path.to_string();
2801 /** Return a unique name based on \a base for a new internal audio source */
2803 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2807 char buf[PATH_MAX+1];
2808 const uint32_t limit = 10000;
2812 legalized = legalize_for_path (base);
2814 // Find a "version" of the base name that doesn't exist in any of the possible directories.
2815 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2817 vector<space_and_path>::iterator i;
2818 uint32_t existing = 0;
2820 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2822 SessionDirectory sdir((*i).path);
2824 spath = sdir.sound_path().to_string();
2829 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2830 spath.c_str(), cnt, legalized.c_str());
2831 } else if (nchan == 2) {
2833 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2834 spath.c_str(), cnt, legalized.c_str());
2836 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2837 spath.c_str(), cnt, legalized.c_str());
2839 } else if (nchan < 26) {
2840 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2841 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2843 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2844 spath.c_str(), cnt, legalized.c_str());
2853 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2854 } else if (nchan == 2) {
2856 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2858 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2860 } else if (nchan < 26) {
2861 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2863 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2867 if (sys::exists(buf)) {
2873 if (existing == 0) {
2878 error << string_compose(
2879 _("There are already %1 recordings for %2, which I consider too many."),
2880 limit, base) << endmsg;
2882 throw failed_constructor();
2886 return Glib::path_get_basename(buf);
2889 /** Create a new within-session audio source */
2890 boost::shared_ptr<AudioFileSource>
2891 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
2893 const string name = new_audio_source_name (n, n_chans, chan, destructive);
2894 const string path = new_source_path_from_name(DataType::AUDIO, name);
2896 return boost::dynamic_pointer_cast<AudioFileSource> (
2897 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2900 /** Return a unique name based on \a base for a new internal MIDI source */
2902 Session::new_midi_source_name (const string& base)
2905 char buf[PATH_MAX+1];
2906 const uint32_t limit = 10000;
2910 legalized = legalize_for_path (base);
2912 // Find a "version" of the file name that doesn't exist in any of the possible directories.
2913 for (cnt = 1; cnt <= limit; ++cnt) {
2915 vector<space_and_path>::iterator i;
2916 uint32_t existing = 0;
2918 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2920 SessionDirectory sdir((*i).path);
2922 sys::path p = sdir.midi_path();
2925 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2927 if (sys::exists (buf)) {
2932 if (existing == 0) {
2937 error << string_compose(
2938 _("There are already %1 recordings for %2, which I consider too many."),
2939 limit, base) << endmsg;
2941 throw failed_constructor();
2945 return Glib::path_get_basename(buf);
2949 /** Create a new within-session MIDI source */
2950 boost::shared_ptr<MidiSource>
2951 Session::create_midi_source_for_session (string const & n)
2953 const string name = new_midi_source_name (n);
2954 const string path = new_source_path_from_name (DataType::MIDI, name);
2956 return boost::dynamic_pointer_cast<SMFSource> (
2957 SourceFactory::createWritable (
2958 DataType::MIDI, *this, path, false, frame_rate()));
2963 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
2965 if (playlist->hidden()) {
2969 playlists->add (playlist);
2972 playlist->release();
2979 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
2981 if (_state_of_the_state & Deletion) {
2985 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
2991 playlists->remove (playlist);
2997 Session::set_audition (boost::shared_ptr<Region> r)
2999 pending_audition_region = r;
3000 add_post_transport_work (PostTransportAudition);
3001 _butler->schedule_transport_work ();
3005 Session::audition_playlist ()
3007 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3008 ev->region.reset ();
3013 Session::non_realtime_set_audition ()
3015 if (!pending_audition_region) {
3016 auditioner->audition_current_playlist ();
3018 auditioner->audition_region (pending_audition_region);
3019 pending_audition_region.reset ();
3021 AuditionActive (true); /* EMIT SIGNAL */
3025 Session::audition_region (boost::shared_ptr<Region> r)
3027 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3033 Session::cancel_audition ()
3035 if (auditioner->auditioning()) {
3036 auditioner->cancel_audition ();
3037 AuditionActive (false); /* EMIT SIGNAL */
3042 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3044 if (a->is_monitor()) {
3047 if (b->is_monitor()) {
3050 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3054 Session::remove_empty_sounds ()
3056 vector<string> audio_filenames;
3058 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3060 Glib::Mutex::Lock lm (source_lock);
3062 TapeFileMatcher tape_file_matcher;
3064 remove_if (audio_filenames.begin(), audio_filenames.end(),
3065 boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3067 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3069 sys::path audio_file_path (_session_dir->sound_path());
3071 audio_file_path /= *i;
3073 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3077 sys::remove (audio_file_path);
3078 const string peakfile = peak_path (audio_file_path.to_string());
3079 sys::remove (peakfile);
3081 catch (const sys::filesystem_error& err)
3083 error << err.what() << endmsg;
3090 Session::is_auditioning () const
3092 /* can be called before we have an auditioner object */
3094 return auditioner->auditioning();
3101 Session::graph_reordered ()
3103 /* don't do this stuff if we are setting up connections
3104 from a set_state() call or creating new tracks. Ditto for deletion.
3107 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3111 /* every track/bus asked for this to be handled but it was deferred because
3112 we were connecting. do it now.
3115 request_input_change_handling ();
3119 /* force all diskstreams to update their capture offset values to
3120 reflect any changes in latencies within the graph.
3123 boost::shared_ptr<RouteList> rl = routes.reader ();
3124 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3125 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3127 tr->set_capture_offset ();
3133 Session::available_capture_duration ()
3135 float sample_bytes_on_disk = 4.0; // keep gcc happy
3137 switch (config.get_native_file_data_format()) {
3139 sample_bytes_on_disk = 4.0;
3143 sample_bytes_on_disk = 3.0;
3147 sample_bytes_on_disk = 2.0;
3151 /* impossible, but keep some gcc versions happy */
3152 fatal << string_compose (_("programming error: %1"),
3153 X_("illegal native file data format"))
3158 double scale = 4096.0 / sample_bytes_on_disk;
3160 if (_total_free_4k_blocks * scale > (double) max_frames) {
3164 return (nframes_t) floor (_total_free_4k_blocks * scale);
3168 Session::add_bundle (shared_ptr<Bundle> bundle)
3171 RCUWriter<BundleList> writer (_bundles);
3172 boost::shared_ptr<BundleList> b = writer.get_copy ();
3173 b->push_back (bundle);
3176 BundleAdded (bundle); /* EMIT SIGNAL */
3182 Session::remove_bundle (shared_ptr<Bundle> bundle)
3184 bool removed = false;
3187 RCUWriter<BundleList> writer (_bundles);
3188 boost::shared_ptr<BundleList> b = writer.get_copy ();
3189 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3191 if (i != b->end()) {
3198 BundleRemoved (bundle); /* EMIT SIGNAL */
3205 Session::bundle_by_name (string name) const
3207 boost::shared_ptr<BundleList> b = _bundles.reader ();
3209 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3210 if ((*i)->name() == name) {
3215 return boost::shared_ptr<Bundle> ();
3219 Session::tempo_map_changed (const PropertyChange&)
3223 playlists->update_after_tempo_map_change ();
3228 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3229 * the given count with the current block size.
3232 Session::ensure_buffers (ChanCount howmany)
3234 BufferManager::ensure_buffers (howmany);
3238 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3240 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3241 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3246 Session::next_insert_id ()
3248 /* this doesn't really loop forever. just think about it */
3251 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3252 if (!insert_bitset[n]) {
3253 insert_bitset[n] = true;
3259 /* none available, so resize and try again */
3261 insert_bitset.resize (insert_bitset.size() + 16, false);
3266 Session::next_send_id ()
3268 /* this doesn't really loop forever. just think about it */
3271 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3272 if (!send_bitset[n]) {
3273 send_bitset[n] = true;
3279 /* none available, so resize and try again */
3281 send_bitset.resize (send_bitset.size() + 16, false);
3286 Session::next_return_id ()
3288 /* this doesn't really loop forever. just think about it */
3291 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3292 if (!return_bitset[n]) {
3293 return_bitset[n] = true;
3299 /* none available, so resize and try again */
3301 return_bitset.resize (return_bitset.size() + 16, false);
3306 Session::mark_send_id (uint32_t id)
3308 if (id >= send_bitset.size()) {
3309 send_bitset.resize (id+16, false);
3311 if (send_bitset[id]) {
3312 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3314 send_bitset[id] = true;
3318 Session::mark_return_id (uint32_t id)
3320 if (id >= return_bitset.size()) {
3321 return_bitset.resize (id+16, false);
3323 if (return_bitset[id]) {
3324 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3326 return_bitset[id] = true;
3330 Session::mark_insert_id (uint32_t id)
3332 if (id >= insert_bitset.size()) {
3333 insert_bitset.resize (id+16, false);
3335 if (insert_bitset[id]) {
3336 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3338 insert_bitset[id] = true;
3342 Session::unmark_send_id (uint32_t id)
3344 if (id < send_bitset.size()) {
3345 send_bitset[id] = false;
3350 Session::unmark_return_id (uint32_t id)
3352 if (id < return_bitset.size()) {
3353 return_bitset[id] = false;
3358 Session::unmark_insert_id (uint32_t id)
3360 if (id < insert_bitset.size()) {
3361 insert_bitset[id] = false;
3366 /* Named Selection management */
3368 boost::shared_ptr<NamedSelection>
3369 Session::named_selection_by_name (string name)
3371 Glib::Mutex::Lock lm (named_selection_lock);
3372 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3373 if ((*i)->name == name) {
3377 return boost::shared_ptr<NamedSelection>();
3381 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3384 Glib::Mutex::Lock lm (named_selection_lock);
3385 named_selections.insert (named_selections.begin(), named_selection);
3390 NamedSelectionAdded (); /* EMIT SIGNAL */
3394 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3396 bool removed = false;
3399 Glib::Mutex::Lock lm (named_selection_lock);
3401 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3403 if (i != named_selections.end()) {
3404 named_selections.erase (i);
3411 NamedSelectionRemoved (); /* EMIT SIGNAL */
3416 Session::reset_native_file_format ()
3418 boost::shared_ptr<RouteList> rl = routes.reader ();
3419 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3420 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3422 tr->reset_write_sources (false);
3428 Session::route_name_unique (string n) const
3430 shared_ptr<RouteList> r = routes.reader ();
3432 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3433 if ((*i)->name() == n) {
3442 Session::route_name_internal (string n) const
3444 if (auditioner && auditioner->name() == n) {
3448 if (_click_io && _click_io->name() == n) {
3456 Session::freeze_all (InterThreadInfo& itt)
3458 shared_ptr<RouteList> r = routes.reader ();
3460 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3462 boost::shared_ptr<Track> t;
3464 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3465 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3475 boost::shared_ptr<Region>
3476 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3477 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3478 InterThreadInfo& itt, bool enable_processing)
3480 boost::shared_ptr<Region> result;
3481 boost::shared_ptr<Playlist> playlist;
3482 boost::shared_ptr<AudioFileSource> fsource;
3484 char buf[PATH_MAX+1];
3485 ChanCount nchans(track.n_channels());
3487 nframes_t this_chunk;
3490 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3491 const string sound_dir = sdir.sound_path().to_string();
3492 nframes_t len = end - start;
3495 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3496 end, start) << endmsg;
3500 const nframes_t chunk_size = (256 * 1024)/4;
3502 // block all process callback handling
3504 block_processing ();
3506 /* call tree *MUST* hold route_lock */
3508 if ((playlist = track.playlist()) == 0) {
3512 /* external redirects will be a problem */
3514 if (track.has_external_redirects()) {
3518 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3520 for (x = 0; x < 99999; ++x) {
3521 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3522 if (access (buf, F_OK) != 0) {
3528 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3533 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3534 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3537 catch (failed_constructor& err) {
3538 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3542 srcs.push_back (fsource);
3545 /* XXX need to flush all redirects */
3550 /* create a set of reasonably-sized buffers */
3551 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3552 buffers.set_count(nchans);
3554 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3555 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3557 afs->prepare_for_peakfile_writes ();
3560 while (to_do && !itt.cancel) {
3562 this_chunk = min (to_do, chunk_size);
3564 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3569 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3570 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3573 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3579 start += this_chunk;
3580 to_do -= this_chunk;
3582 itt.progress = (float) (1.0 - ((double) to_do / len));
3591 xnow = localtime (&now);
3593 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3594 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3597 afs->update_header (position, *xnow, now);
3598 afs->flush_header ();
3602 /* construct a region to represent the bounced material */
3606 plist.add (Properties::start, 0);
3607 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3608 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3610 result = RegionFactory::create (srcs, plist);
3616 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3617 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3620 afs->mark_for_remove ();
3623 (*src)->drop_references ();
3627 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3628 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3631 afs->done_with_peakfile_writes ();
3635 unblock_processing ();
3641 Session::gain_automation_buffer() const
3643 return ProcessThread::gain_automation_buffer ();
3647 Session::pan_automation_buffer() const
3649 return ProcessThread::pan_automation_buffer ();
3653 Session::get_silent_buffers (ChanCount count)
3655 return ProcessThread::get_silent_buffers (count);
3657 assert(_silent_buffers->available() >= count);
3658 _silent_buffers->set_count(count);
3660 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3661 for (size_t i= 0; i < count.get(*t); ++i) {
3662 _silent_buffers->get(*t, i).clear();
3666 return *_silent_buffers;
3671 Session::get_scratch_buffers (ChanCount count)
3673 return ProcessThread::get_scratch_buffers (count);
3675 if (count != ChanCount::ZERO) {
3676 assert(_scratch_buffers->available() >= count);
3677 _scratch_buffers->set_count(count);
3679 _scratch_buffers->set_count (_scratch_buffers->available());
3682 return *_scratch_buffers;
3687 Session::get_mix_buffers (ChanCount count)
3689 return ProcessThread::get_mix_buffers (count);
3691 assert(_mix_buffers->available() >= count);
3692 _mix_buffers->set_count(count);
3693 return *_mix_buffers;
3698 Session::ntracks () const
3701 shared_ptr<RouteList> r = routes.reader ();
3703 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3704 if (boost::dynamic_pointer_cast<Track> (*i)) {
3713 Session::nbusses () const
3716 shared_ptr<RouteList> r = routes.reader ();
3718 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3719 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3728 Session::add_automation_list(AutomationList *al)
3730 automation_lists[al->id()] = al;
3734 Session::compute_initial_length ()
3736 return _engine.frame_rate() * 60 * 5;
3740 Session::sync_order_keys (std::string const & base)
3742 if (deletion_in_progress()) {
3746 if (!Config->get_sync_all_route_ordering()) {
3747 /* leave order keys as they are */
3751 boost::shared_ptr<RouteList> r = routes.reader ();
3753 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3754 (*i)->sync_order_keys (base);
3757 Route::SyncOrderKeys (base); // EMIT SIGNAL
3759 /* this might not do anything */
3761 set_remote_control_ids ();
3764 /** @return true if there is at least one record-enabled track, otherwise false */
3766 Session::have_rec_enabled_track () const
3768 return g_atomic_int_get (&_have_rec_enabled_track) == 1;
3771 /** Update the state of our rec-enabled tracks flag */
3773 Session::update_have_rec_enabled_track ()
3775 boost::shared_ptr<RouteList> rl = routes.reader ();
3776 RouteList::iterator i = rl->begin();
3777 while (i != rl->end ()) {
3779 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3780 if (tr && tr->record_enabled ()) {
3787 int const old = g_atomic_int_get (&_have_rec_enabled_track);
3789 g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
3791 if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
3792 RecordStateChanged (); /* EMIT SIGNAL */
3797 Session::listen_position_changed ()
3801 switch (Config->get_listen_position()) {
3802 case AfterFaderListen:
3806 case PreFaderListen:
3811 boost::shared_ptr<RouteList> r = routes.reader ();
3813 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3814 (*i)->put_monitor_send_at (p);
3819 Session::solo_control_mode_changed ()
3821 /* cancel all solo or all listen when solo control mode changes */
3824 set_solo (get_routes(), false);
3825 } else if (listening()) {
3826 set_listen (get_routes(), false);
3831 Session::route_group_changed ()
3833 RouteGroupChanged (); /* EMIT SIGNAL */
3837 Session::get_available_sync_options () const
3839 vector<SyncSource> ret;
3841 ret.push_back (JACK);
3844 ret.push_back (MTC);
3847 if (midi_clock_port()) {
3848 ret.push_back (MIDIClock);
3854 boost::shared_ptr<RouteList>
3855 Session::get_routes_with_regions_at (nframes64_t const p) const
3857 shared_ptr<RouteList> r = routes.reader ();
3858 shared_ptr<RouteList> rl (new RouteList);
3860 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3861 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3866 boost::shared_ptr<Playlist> pl = tr->playlist ();
3871 if (pl->has_region_at (p)) {