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 diskstreams (new DiskstreamList),
145 routes (new RouteList),
146 _total_free_4k_blocks (0),
147 _bundles (new BundleList),
148 _bundle_xml_node (0),
151 click_emphasis_data (0),
153 _metadata (new SessionMetadata()),
154 _have_rec_enabled_diskstream (false)
157 playlists.reset (new SessionPlaylists);
159 interpolation.add_channel_to (0, 0);
161 if (!eng.connected()) {
162 throw failed_constructor();
165 n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
166 n_physical_inputs = _engine.n_physical_inputs(DataType::AUDIO);
168 first_stage_init (fullpath, snapshot_name);
170 _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
173 if (create (mix_template, compute_initial_length(), bus_profile)) {
175 throw failed_constructor ();
179 if (second_stage_init ()) {
181 throw failed_constructor ();
184 store_recent_sessions(_name, _path);
186 bool was_dirty = dirty();
188 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
190 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
191 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
194 DirtyChanged (); /* EMIT SIGNAL */
208 vector<void*> debug_pointers;
210 /* if we got to here, leaving pending capture state around
214 remove_pending_capture_state ();
216 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
218 _engine.remove_session ();
220 /* clear history so that no references to objects are held any more */
224 /* clear state tree so that no references to objects are held any more */
228 /* reset dynamic state version back to default */
230 Stateful::loading_state_version = 0;
232 _butler->drop_references ();
234 delete midi_control_ui;
236 if (click_data != default_click) {
237 delete [] click_data;
240 if (click_emphasis_data != default_click_emphasis) {
241 delete [] click_emphasis_data;
246 /* clear out any pending dead wood from RCU managed objects */
249 diskstreams.flush ();
252 AudioDiskstream::free_working_buffers();
254 /* tell everyone who is still standing that we're about to die */
257 /* tell everyone to drop references and delete objects as we go */
259 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
260 named_selections.clear ();
262 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
263 RegionFactory::delete_all_regions ();
265 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
267 /* reset these three references to special routes before we do the usual route delete thing */
270 _master_out.reset ();
271 _monitor_out.reset ();
274 RCUWriter<RouteList> writer (routes);
275 boost::shared_ptr<RouteList> r = writer.get_copy ();
277 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
278 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
279 (*i)->drop_references ();
283 /* writer goes out of scope and updates master */
287 boost::shared_ptr<RouteList> r = routes.reader ();
289 DEBUG_TRACE (DEBUG::Destruction, "delete diskstreams\n");
291 RCUWriter<DiskstreamList> dwriter (diskstreams);
292 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
293 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
294 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for diskstream %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
295 (*i)->drop_references ();
300 diskstreams.flush ();
302 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
303 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
304 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
305 i->second->drop_references ();
310 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
311 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
316 Crossfade::set_buffer_size (0);
320 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
323 boost_debug_list_ptrs ();
325 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
329 Session::set_worst_io_latencies ()
331 _worst_output_latency = 0;
332 _worst_input_latency = 0;
334 if (!_engine.connected()) {
338 boost::shared_ptr<RouteList> r = routes.reader ();
340 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
341 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
342 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
347 Session::when_engine_running ()
349 string first_physical_output;
351 BootMessage (_("Set block size and sample rate"));
353 set_block_size (_engine.frames_per_cycle());
354 set_frame_rate (_engine.frame_rate());
356 BootMessage (_("Using configuration"));
358 boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
359 boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
361 Config->map_parameters (ff);
362 config.map_parameters (ft);
364 /* every time we reconnect, recompute worst case output latencies */
366 _engine.Running.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies, this));
368 if (synced_to_jack()) {
369 _engine.transport_stop ();
372 if (config.get_jack_time_master()) {
373 _engine.transport_locate (_transport_frame);
381 _click_io.reset (new ClickIO (*this, "click"));
383 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
385 /* existing state for Click */
388 if (Stateful::loading_state_version < 3000) {
389 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
391 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
396 _clicking = Config->get_clicking ();
400 error << _("could not setup Click I/O") << endmsg;
407 /* default state for Click: dual-mono to first 2 physical outputs */
409 for (int physport = 0; physport < 2; ++physport) {
410 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
412 if (physical_output.length()) {
413 if (_click_io->add_port (physical_output, this)) {
414 // relax, even though its an error
419 if (_click_io->n_ports () > ChanCount::ZERO) {
420 _clicking = Config->get_clicking ();
425 catch (failed_constructor& err) {
426 error << _("cannot setup Click I/O") << endmsg;
429 BootMessage (_("Compute I/O Latencies"));
431 set_worst_io_latencies ();
434 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
437 BootMessage (_("Set up standard connections"));
439 /* Create a set of Bundle objects that map
440 to the physical I/O currently available. We create both
441 mono and stereo bundles, so that the common cases of mono
442 and stereo tracks get bundles to put in their mixer strip
443 in / out menus. There may be a nicer way of achieving that;
444 it doesn't really scale that well to higher channel counts
447 /* mono output bundles */
449 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
451 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
453 shared_ptr<Bundle> c (new Bundle (buf, true));
454 c->add_channel (_("mono"));
455 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
460 /* stereo output bundles */
462 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
463 if (np + 1 < n_physical_outputs) {
465 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
466 shared_ptr<Bundle> c (new Bundle (buf, true));
467 c->add_channel (_("L"));
468 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
469 c->add_channel (_("R"));
470 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
476 /* mono input bundles */
478 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
480 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
482 shared_ptr<Bundle> c (new Bundle (buf, false));
483 c->add_channel (_("mono"));
484 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
489 /* stereo input bundles */
491 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
492 if (np + 1 < n_physical_inputs) {
494 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
496 shared_ptr<Bundle> c (new Bundle (buf, false));
497 c->add_channel (_("L"));
498 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
499 c->add_channel (_("R"));
500 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
506 BootMessage (_("Setup signal flow and plugins"));
510 if (_is_new && !no_auto_connect()) {
512 /* don't connect the master bus outputs if there is a monitor bus */
514 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
516 /* if requested auto-connect the outputs to the first N physical ports.
519 uint32_t limit = _master_out->n_outputs().n_total();
521 for (uint32_t n = 0; n < limit; ++n) {
522 Port* p = _master_out->output()->nth (n);
523 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
525 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
526 if (_master_out->output()->connect (p, connect_to, this)) {
527 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
537 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
538 are undefined, at best.
541 /* control out listens to master bus (but ignores it
542 under some conditions)
545 uint32_t limit = _monitor_out->n_inputs().n_audio();
548 for (uint32_t n = 0; n < limit; ++n) {
549 AudioPort* p = _monitor_out->input()->ports().nth_audio_port (n);
550 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
553 string connect_to = o->name();
554 if (_monitor_out->input()->connect (p, connect_to, this)) {
555 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
563 /* if control out is not connected, connect control out to physical outs
566 if (!_monitor_out->output()->connected ()) {
568 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
570 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
573 _monitor_out->output()->connect_ports_to_bundle (b, this);
575 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
576 Config->get_monitor_bus_preferred_bundle())
582 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
583 uint32_t mod = _engine.n_physical_outputs (*t);
584 uint32_t limit = _monitor_out->n_outputs().get(*t);
586 for (uint32_t n = 0; n < limit; ++n) {
588 Port* p = _monitor_out->output()->ports().port(*t, n);
589 string connect_to = _engine.get_nth_physical_output (*t, (n % mod));
591 if (!connect_to.empty()) {
592 if (_monitor_out->output()->connect (p, connect_to, this)) {
593 error << string_compose (
594 _("cannot connect control output %1 to %2"),
607 /* catch up on send+insert cnts */
609 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
611 /* hook us up to the engine */
613 BootMessage (_("Connect to engine"));
615 _engine.set_session (this);
619 Session::hookup_io ()
621 /* stop graph reordering notifications from
622 causing resorts, etc.
625 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
630 /* we delay creating the auditioner till now because
631 it makes its own connections to ports.
635 Auditioner* a = new Auditioner (*this);
638 throw failed_constructor();
640 a->use_new_diskstream ();
641 auditioner.reset (a);
644 catch (failed_constructor& err) {
645 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
649 /* load bundles, which we may have postponed earlier on */
650 if (_bundle_xml_node) {
651 load_bundles (*_bundle_xml_node);
652 delete _bundle_xml_node;
655 /* Tell all IO objects to connect themselves together */
657 IO::enable_connecting ();
658 MIDI::JACK_MidiPort::MakeConnections ();
660 /* Now reset all panners */
662 Delivery::reset_panners ();
664 /* Connect tracks to monitor/listen bus if there is one.
665 Note that in an existing session, the internal sends will
666 already exist, but we want the routes to notice that
667 they connect to the control out specifically.
671 boost::shared_ptr<RouteList> r = routes.reader ();
672 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
674 if ((*x)->is_monitor()) {
678 } else if ((*x)->is_master()) {
684 (*x)->listen_via (_monitor_out,
685 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
691 /* Anyone who cares about input state, wake up and do something */
693 IOConnectionsComplete (); /* EMIT SIGNAL */
695 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
697 /* now handle the whole enchilada as if it was one
703 /* update the full solo state, which can't be
704 correctly determined on a per-route basis, but
705 needs the global overview that only the session
709 update_route_solo_state ();
713 Session::playlist_length_changed ()
715 /* we can't just increase end_location->end() if pl->get_maximum_extent()
716 if larger. if the playlist used to be the longest playlist,
717 and its now shorter, we have to decrease end_location->end(). hence,
718 we have to iterate over all diskstreams and check the
719 playlists currently in use.
725 Session::diskstream_playlist_changed (boost::weak_ptr<Diskstream> wp)
727 boost::shared_ptr<Diskstream> dstream = wp.lock ();
732 boost::shared_ptr<Playlist> playlist;
734 if ((playlist = dstream->playlist()) != 0) {
735 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
738 /* see comment in playlist_length_changed () */
743 Session::record_enabling_legal () const
745 /* this used to be in here, but survey says.... we don't need to restrict it */
746 // if (record_status() == Recording) {
750 if (Config->get_all_safe()) {
757 Session::reset_input_monitor_state ()
759 if (transport_rolling()) {
761 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
763 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
764 if ((*i)->record_enabled ()) {
765 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
766 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
770 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
772 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
773 if ((*i)->record_enabled ()) {
774 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
775 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
782 Session::auto_punch_start_changed (Location* location)
784 replace_event (SessionEvent::PunchIn, location->start());
786 if (get_record_enabled() && config.get_punch_in()) {
787 /* capture start has been changed, so save new pending state */
788 save_state ("", true);
793 Session::auto_punch_end_changed (Location* location)
795 nframes_t when_to_stop = location->end();
796 // when_to_stop += _worst_output_latency + _worst_input_latency;
797 replace_event (SessionEvent::PunchOut, when_to_stop);
801 Session::auto_punch_changed (Location* location)
803 nframes_t when_to_stop = location->end();
805 replace_event (SessionEvent::PunchIn, location->start());
806 //when_to_stop += _worst_output_latency + _worst_input_latency;
807 replace_event (SessionEvent::PunchOut, when_to_stop);
811 Session::auto_loop_changed (Location* location)
813 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
815 if (transport_rolling() && play_loop) {
818 // if (_transport_frame > location->end()) {
820 if (_transport_frame < location->start() || _transport_frame > location->end()) {
821 // relocate to beginning of loop
822 clear_events (SessionEvent::LocateRoll);
824 request_locate (location->start(), true);
827 else if (Config->get_seamless_loop() && !loop_changing) {
829 // schedule a locate-roll to refill the diskstreams at the
831 loop_changing = true;
833 if (location->end() > last_loopend) {
834 clear_events (SessionEvent::LocateRoll);
835 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
842 last_loopend = location->end();
846 Session::set_auto_punch_location (Location* location)
850 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
851 punch_connections.drop_connections();
852 existing->set_auto_punch (false, this);
853 remove_event (existing->start(), SessionEvent::PunchIn);
854 clear_events (SessionEvent::PunchOut);
855 auto_punch_location_changed (0);
864 if (location->end() <= location->start()) {
865 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
869 punch_connections.drop_connections ();
871 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
872 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
873 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
875 location->set_auto_punch (true, this);
877 auto_punch_changed (location);
879 auto_punch_location_changed (location);
883 Session::set_auto_loop_location (Location* location)
887 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
888 loop_connections.drop_connections ();
889 existing->set_auto_loop (false, this);
890 remove_event (existing->end(), SessionEvent::AutoLoop);
891 auto_loop_location_changed (0);
900 if (location->end() <= location->start()) {
901 error << _("Session: you can't use a mark for auto loop") << endmsg;
905 last_loopend = location->end();
907 loop_connections.drop_connections ();
909 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
910 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
911 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
913 location->set_auto_loop (true, this);
915 /* take care of our stuff first */
917 auto_loop_changed (location);
919 /* now tell everyone else */
921 auto_loop_location_changed (location);
925 Session::locations_added (Location *)
931 Session::locations_changed ()
933 _locations.apply (*this, &Session::handle_locations_changed);
937 Session::handle_locations_changed (Locations::LocationList& locations)
939 Locations::LocationList::iterator i;
941 bool set_loop = false;
942 bool set_punch = false;
944 for (i = locations.begin(); i != locations.end(); ++i) {
948 if (location->is_auto_punch()) {
949 set_auto_punch_location (location);
952 if (location->is_auto_loop()) {
953 set_auto_loop_location (location);
957 if (location->is_start()) {
958 start_location = location;
960 if (location->is_end()) {
961 end_location = location;
966 set_auto_loop_location (0);
969 set_auto_punch_location (0);
976 Session::enable_record ()
978 /* XXX really atomic compare+swap here */
979 if (g_atomic_int_get (&_record_status) != Recording) {
980 g_atomic_int_set (&_record_status, Recording);
981 _last_record_location = _transport_frame;
982 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
984 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
985 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
986 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
987 if ((*i)->record_enabled ()) {
988 (*i)->monitor_input (true);
993 RecordStateChanged ();
998 Session::disable_record (bool rt_context, bool force)
1002 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1004 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1005 g_atomic_int_set (&_record_status, Disabled);
1007 if (rs == Recording) {
1008 g_atomic_int_set (&_record_status, Enabled);
1012 // FIXME: timestamp correct? [DR]
1013 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1014 // does this /need/ to be sent in all cases?
1016 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1019 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1020 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1022 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1023 if ((*i)->record_enabled ()) {
1024 (*i)->monitor_input (false);
1029 RecordStateChanged (); /* emit signal */
1032 remove_pending_capture_state ();
1038 Session::step_back_from_record ()
1040 if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1042 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1043 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1045 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1046 if ((*i)->record_enabled ()) {
1047 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1048 (*i)->monitor_input (false);
1056 Session::maybe_enable_record ()
1058 g_atomic_int_set (&_record_status, Enabled);
1060 /* this function is currently called from somewhere other than an RT thread.
1061 this save_state() call therefore doesn't impact anything.
1064 save_state ("", true);
1066 if (_transport_speed) {
1067 if (!config.get_punch_in()) {
1071 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1072 RecordStateChanged (); /* EMIT SIGNAL */
1079 Session::audible_frame () const
1085 /* the first of these two possible settings for "offset"
1086 mean that the audible frame is stationary until
1087 audio emerges from the latency compensation
1090 the second means that the audible frame is stationary
1091 until audio would emerge from a physical port
1092 in the absence of any plugin latency compensation
1095 offset = _worst_output_latency;
1097 if (offset > current_block_size) {
1098 offset -= current_block_size;
1100 /* XXX is this correct? if we have no external
1101 physical connections and everything is internal
1102 then surely this is zero? still, how
1103 likely is that anyway?
1105 offset = current_block_size;
1108 if (synced_to_jack()) {
1109 tf = _engine.transport_frame();
1111 tf = _transport_frame;
1116 if (!non_realtime_work_pending()) {
1120 /* check to see if we have passed the first guaranteed
1121 audible frame past our last start position. if not,
1122 return that last start point because in terms
1123 of audible frames, we have not moved yet.
1126 if (_transport_speed > 0.0f) {
1128 if (!play_loop || !have_looped) {
1129 if (tf < _last_roll_location + offset) {
1130 return _last_roll_location;
1138 } else if (_transport_speed < 0.0f) {
1140 /* XXX wot? no backward looping? */
1142 if (tf > _last_roll_location - offset) {
1143 return _last_roll_location;
1155 Session::set_frame_rate (nframes_t frames_per_second)
1157 /** \fn void Session::set_frame_size(nframes_t)
1158 the AudioEngine object that calls this guarantees
1159 that it will not be called while we are also in
1160 ::process(). Its fine to do things that block
1164 _base_frame_rate = frames_per_second;
1168 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1172 // XXX we need some equivalent to this, somehow
1173 // SndFileSource::setup_standard_crossfades (frames_per_second);
1177 /* XXX need to reset/reinstantiate all LADSPA plugins */
1181 Session::set_block_size (nframes_t nframes)
1183 /* the AudioEngine guarantees
1184 that it will not be called while we are also in
1185 ::process(). It is therefore fine to do things that block
1190 current_block_size = nframes;
1194 boost::shared_ptr<RouteList> r = routes.reader ();
1196 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1197 (*i)->set_block_size (nframes);
1200 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1201 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1202 (*i)->set_block_size (nframes);
1205 set_worst_io_latencies ();
1210 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1213 nframes_t fade_frames;
1215 /* Don't allow fade of less 1 frame */
1217 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1224 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1228 default_fade_msecs = fade_msecs;
1229 default_fade_steepness = steepness;
1232 // jlc, WTF is this!
1233 Glib::RWLock::ReaderLock lm (route_lock);
1234 AudioRegion::set_default_fade (steepness, fade_frames);
1239 /* XXX have to do this at some point */
1240 /* foreach region using default fade, reset, then
1241 refill_all_diskstream_buffers ();
1246 struct RouteSorter {
1247 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1248 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1250 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1253 if (r1->fed_by.empty()) {
1254 if (r2->fed_by.empty()) {
1255 /* no ardour-based connections inbound to either route. just use signal order */
1256 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1258 /* r2 has connections, r1 does not; run r1 early */
1262 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1269 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1271 shared_ptr<Route> r2;
1273 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1274 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1278 /* make a copy of the existing list of routes that feed r1 */
1280 set<weak_ptr<Route> > existing = r1->fed_by;
1282 /* for each route that feeds r1, recurse, marking it as feeding
1286 for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1287 if (!(r2 = (*i).lock ())) {
1288 /* (*i) went away, ignore it */
1292 /* r2 is a route that feeds r1 which somehow feeds base. mark
1293 base as being fed by r2
1296 rbase->fed_by.insert (r2);
1300 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1304 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1308 /* now recurse, so that we can mark base as being fed by
1309 all routes that feed r2
1312 trace_terminal (r2, rbase);
1319 Session::resort_routes ()
1321 /* don't do anything here with signals emitted
1322 by Routes while we are being destroyed.
1325 if (_state_of_the_state & Deletion) {
1332 RCUWriter<RouteList> writer (routes);
1333 shared_ptr<RouteList> r = writer.get_copy ();
1334 resort_routes_using (r);
1335 /* writer goes out of scope and forces update */
1340 Session::resort_routes_using (shared_ptr<RouteList> r)
1342 RouteList::iterator i, j;
1344 for (i = r->begin(); i != r->end(); ++i) {
1346 (*i)->fed_by.clear ();
1348 for (j = r->begin(); j != r->end(); ++j) {
1350 /* although routes can feed themselves, it will
1351 cause an endless recursive descent if we
1352 detect it. so don't bother checking for
1360 if ((*j)->feeds (*i)) {
1361 (*i)->fed_by.insert (*j);
1366 for (i = r->begin(); i != r->end(); ++i) {
1367 trace_terminal (*i, *i);
1374 cerr << "finished route resort\n";
1376 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1377 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1384 /** Find the route name starting with \a base with the lowest \a id.
1386 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1387 * The available route name with the lowest ID will be used, and \a id
1388 * will be set to the ID.
1390 * \return false if a route name could not be found, and \a track_name
1391 * and \a id do not reflect a free route name.
1394 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1397 snprintf (name, name_len, "%s %" PRIu32, base, id);
1399 if (route_by_name (name) == 0) {
1405 } while (id < (UINT_MAX-1));
1411 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1413 in = ChanCount::ZERO;
1414 out = ChanCount::ZERO;
1415 shared_ptr<RouteList> r = routes.reader ();
1416 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1417 if (!(*i)->is_hidden()) {
1418 in += (*i)->n_inputs();
1419 out += (*i)->n_outputs();
1424 list<boost::shared_ptr<MidiTrack> >
1425 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1427 char track_name[32];
1428 uint32_t track_id = 0;
1429 ChanCount existing_inputs;
1430 ChanCount existing_outputs;
1432 RouteList new_routes;
1433 list<boost::shared_ptr<MidiTrack> > ret;
1434 uint32_t control_id;
1436 count_existing_route_channels (existing_inputs, existing_outputs);
1438 control_id = ntracks() + nbusses();
1441 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1442 error << "cannot find name for new midi track" << endmsg;
1446 shared_ptr<MidiTrack> track;
1449 MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1456 mt->use_new_diskstream();
1458 boost_debug_shared_ptr_mark_interesting (mt, "Track");
1459 track = boost::shared_ptr<MidiTrack>(mt);
1461 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1462 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1467 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1468 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1472 auto_connect_route (track, existing_inputs, existing_outputs);
1474 track->midi_diskstream()->non_realtime_input_change();
1476 route_group->add (track);
1479 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1480 track->set_remote_control_id (control_id);
1482 new_routes.push_back (track);
1483 ret.push_back (track);
1486 catch (failed_constructor &err) {
1487 error << _("Session: could not create new midi track.") << endmsg;
1490 /* we need to get rid of this, since the track failed to be created */
1491 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1494 RCUWriter<DiskstreamList> writer (diskstreams);
1495 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1496 ds->remove (track->midi_diskstream());
1503 catch (AudioEngine::PortRegistrationFailure& pfe) {
1505 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;
1508 /* we need to get rid of this, since the track failed to be created */
1509 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1512 RCUWriter<DiskstreamList> writer (diskstreams);
1513 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1514 ds->remove (track->midi_diskstream());
1525 if (!new_routes.empty()) {
1526 add_routes (new_routes, false);
1527 save_state (_current_snapshot_name);
1534 Session::auto_connect_route (boost::shared_ptr<Route> route,
1535 ChanCount& existing_inputs, ChanCount& existing_outputs)
1537 /* If both inputs and outputs are auto-connected to physical ports,
1538 use the max of input and output offsets to ensure auto-connected
1539 port numbers always match up (e.g. the first audio input and the
1540 first audio output of the route will have the same physical
1541 port number). Otherwise just use the lowest input or output
1544 const bool in_out_physical =
1545 (Config->get_input_auto_connect() & AutoConnectPhysical)
1546 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1548 const ChanCount in_offset = in_out_physical
1549 ? ChanCount::max(existing_inputs, existing_outputs)
1552 const ChanCount out_offset = in_out_physical
1553 ? ChanCount::max(existing_inputs, existing_outputs)
1556 static string empty_string;
1557 string& port = empty_string;
1559 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1560 vector<string> physinputs;
1561 vector<string> physoutputs;
1563 _engine.get_physical_outputs (*t, physoutputs);
1564 _engine.get_physical_inputs (*t, physinputs);
1566 if (!physinputs.empty()) {
1567 uint32_t nphysical_in = physinputs.size();
1568 for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1569 port = empty_string;
1571 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1572 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1575 if (!port.empty() && route->input()->connect (
1576 route->input()->ports().port(*t, i), port, this)) {
1582 if (!physoutputs.empty()) {
1583 uint32_t nphysical_out = physoutputs.size();
1584 for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1585 port = empty_string;
1587 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1588 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1589 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1590 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1591 port = _master_out->input()->ports().port(*t,
1592 i % _master_out->input()->n_ports().get(*t))->name();
1596 if (!port.empty() && route->output()->connect (
1597 route->output()->ports().port(*t, i), port, this)) {
1604 existing_inputs += route->n_inputs();
1605 existing_outputs += route->n_outputs();
1608 list< boost::shared_ptr<AudioTrack> >
1609 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1611 char track_name[32];
1612 uint32_t track_id = 0;
1613 ChanCount existing_inputs;
1614 ChanCount existing_outputs;
1616 RouteList new_routes;
1617 list<boost::shared_ptr<AudioTrack> > ret;
1618 uint32_t control_id;
1620 count_existing_route_channels (existing_inputs, existing_outputs);
1622 control_id = ntracks() + nbusses() + 1;
1625 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1626 error << "cannot find name for new audio track" << endmsg;
1630 shared_ptr<AudioTrack> track;
1633 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1640 at->use_new_diskstream();
1642 boost_debug_shared_ptr_mark_interesting (at, "Track");
1643 track = boost::shared_ptr<AudioTrack>(at);
1645 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1646 error << string_compose (
1647 _("cannot configure %1 in/%2 out configuration for new audio track"),
1648 input_channels, output_channels)
1653 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1654 error << string_compose (
1655 _("cannot configure %1 in/%2 out configuration for new audio track"),
1656 input_channels, output_channels)
1661 auto_connect_route (track, existing_inputs, existing_outputs);
1664 route_group->add (track);
1667 track->audio_diskstream()->non_realtime_input_change();
1669 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1670 track->set_remote_control_id (control_id);
1673 new_routes.push_back (track);
1674 ret.push_back (track);
1677 catch (failed_constructor &err) {
1678 error << _("Session: could not create new audio track.") << endmsg;
1681 /* we need to get rid of this, since the track failed to be created */
1682 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1685 RCUWriter<DiskstreamList> writer (diskstreams);
1686 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1687 ds->remove (track->audio_diskstream());
1694 catch (AudioEngine::PortRegistrationFailure& pfe) {
1696 error << pfe.what() << endmsg;
1699 /* we need to get rid of this, since the track failed to be created */
1700 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1703 RCUWriter<DiskstreamList> writer (diskstreams);
1704 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1705 ds->remove (track->audio_diskstream());
1716 if (!new_routes.empty()) {
1717 add_routes (new_routes, true);
1724 Session::set_remote_control_ids ()
1726 RemoteModel m = Config->get_remote_model();
1727 bool emit_signal = false;
1729 shared_ptr<RouteList> r = routes.reader ();
1731 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1732 if (MixerOrdered == m) {
1733 long order = (*i)->order_key(N_("signal"));
1734 (*i)->set_remote_control_id (order+1, false);
1736 } else if (EditorOrdered == m) {
1737 long order = (*i)->order_key(N_("editor"));
1738 (*i)->set_remote_control_id (order+1, false);
1740 } else if (UserOrdered == m) {
1741 //do nothing ... only changes to remote id's are initiated by user
1746 Route::RemoteControlIDChange();
1752 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1755 uint32_t bus_id = 0;
1756 ChanCount existing_inputs;
1757 ChanCount existing_outputs;
1760 uint32_t control_id;
1762 count_existing_route_channels (existing_inputs, existing_outputs);
1764 control_id = ntracks() + nbusses() + 1;
1767 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1768 error << "cannot find name for new audio bus" << endmsg;
1773 Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1780 boost_debug_shared_ptr_mark_interesting (rt, "Route");
1781 shared_ptr<Route> bus (rt);
1783 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1784 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1785 input_channels, output_channels)
1791 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1792 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1793 input_channels, output_channels)
1798 auto_connect_route (bus, existing_inputs, existing_outputs);
1801 route_group->add (bus);
1803 bus->set_remote_control_id (control_id);
1807 bus->add_internal_return ();
1810 ret.push_back (bus);
1814 catch (failed_constructor &err) {
1815 error << _("Session: could not create new audio route.") << endmsg;
1819 catch (AudioEngine::PortRegistrationFailure& pfe) {
1820 error << pfe.what() << endmsg;
1830 add_routes (ret, true);
1838 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1842 uint32_t control_id;
1844 uint32_t number = 0;
1846 if (!tree.read (template_path.c_str())) {
1850 XMLNode* node = tree.root();
1852 control_id = ntracks() + nbusses() + 1;
1856 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1858 std::string node_name = IO::name_from_state (*node_copy.children().front());
1860 /* generate a new name by adding a number to the end of the template name */
1861 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1862 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1866 IO::set_name_in_state (*node_copy.children().front(), name);
1868 Track::zero_diskstream_id_in_xml (node_copy);
1871 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1874 error << _("Session: cannot create track/bus from template description") << endmsg;
1878 if (boost::dynamic_pointer_cast<Track>(route)) {
1879 /* force input/output change signals so that the new diskstream
1880 picks up the configuration of the route. During session
1881 loading this normally happens in a different way.
1883 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1884 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1887 route->set_remote_control_id (control_id);
1890 ret.push_back (route);
1893 catch (failed_constructor &err) {
1894 error << _("Session: could not create new route from template") << endmsg;
1898 catch (AudioEngine::PortRegistrationFailure& pfe) {
1899 error << pfe.what() << endmsg;
1908 add_routes (ret, true);
1915 Session::add_routes (RouteList& new_routes, bool save)
1918 RCUWriter<RouteList> writer (routes);
1919 shared_ptr<RouteList> r = writer.get_copy ();
1920 r->insert (r->end(), new_routes.begin(), new_routes.end());
1923 /* if there is no control out and we're not in the middle of loading,
1924 resort the graph here. if there is a control out, we will resort
1925 toward the end of this method. if we are in the middle of loading,
1926 we will resort when done.
1929 if (!_monitor_out && IO::connecting_legal) {
1930 resort_routes_using (r);
1934 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1936 boost::weak_ptr<Route> wpr (*x);
1937 boost::shared_ptr<Route> r (*x);
1939 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1940 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, wpr));
1941 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1942 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1943 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1944 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
1946 if (r->is_master()) {
1950 if (r->is_monitor()) {
1955 if (_monitor_out && IO::connecting_legal) {
1957 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1958 if ((*x)->is_monitor()) {
1960 } else if ((*x)->is_master()) {
1963 (*x)->listen_via (_monitor_out,
1964 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
1975 save_state (_current_snapshot_name);
1978 RouteAdded (new_routes); /* EMIT SIGNAL */
1979 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
1983 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
1985 boost::shared_ptr<RouteList> r = routes.reader ();
1986 boost::shared_ptr<Send> s;
1990 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1991 if (boost::dynamic_pointer_cast<Track>(*i)) {
1992 if ((s = (*i)->internal_send_for (dest)) != 0) {
1993 s->amp()->gain_control()->set_value (0.0);
2000 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2002 boost::shared_ptr<RouteList> r = routes.reader ();
2003 boost::shared_ptr<Send> s;
2007 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2008 if (boost::dynamic_pointer_cast<Track>(*i)) {
2009 if ((s = (*i)->internal_send_for (dest)) != 0) {
2010 s->amp()->gain_control()->set_value (1.0);
2017 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2019 boost::shared_ptr<RouteList> r = routes.reader ();
2020 boost::shared_ptr<Send> s;
2024 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2025 if (boost::dynamic_pointer_cast<Track>(*i)) {
2026 if ((s = (*i)->internal_send_for (dest)) != 0) {
2027 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2034 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2036 boost::shared_ptr<RouteList> r = routes.reader ();
2037 boost::shared_ptr<RouteList> t (new RouteList);
2039 /* only send tracks */
2041 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2042 if (boost::dynamic_pointer_cast<Track>(*i)) {
2047 add_internal_sends (dest, p, t);
2051 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2053 if (dest->is_monitor() || dest->is_master()) {
2057 if (!dest->internal_return()) {
2058 dest->add_internal_return();
2061 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2063 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2067 (*i)->listen_via (dest, p, true, true);
2074 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2076 /* need to do this in case we're rolling at the time, to prevent false underruns */
2077 dstream->do_refill_with_alloc ();
2079 dstream->set_block_size (current_block_size);
2082 RCUWriter<DiskstreamList> writer (diskstreams);
2083 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2084 ds->push_back (dstream);
2085 /* writer goes out of scope, copies ds back to main */
2088 dstream->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::diskstream_playlist_changed, this, boost::weak_ptr<Diskstream> (dstream)));
2089 /* this will connect to future changes, and check the current length */
2090 diskstream_playlist_changed (boost::weak_ptr<Diskstream> (dstream));
2092 dstream->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_diskstream, this));
2096 Session::remove_route (shared_ptr<Route> route)
2099 RCUWriter<RouteList> writer (routes);
2100 shared_ptr<RouteList> rs = writer.get_copy ();
2104 /* deleting the master out seems like a dumb
2105 idea, but its more of a UI policy issue
2109 if (route == _master_out) {
2110 _master_out = shared_ptr<Route> ();
2113 if (route == _monitor_out) {
2115 /* cancel control outs for all routes */
2117 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2118 (*r)->drop_listen (_monitor_out);
2121 _monitor_out.reset ();
2124 update_route_solo_state ();
2126 /* writer goes out of scope, forces route list update */
2129 boost::shared_ptr<Track> t;
2130 boost::shared_ptr<Diskstream> ds;
2132 if ((t = boost::dynamic_pointer_cast<Track>(route)) != 0) {
2133 ds = t->diskstream();
2139 RCUWriter<DiskstreamList> dsl (diskstreams);
2140 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2145 find_current_end ();
2147 // We need to disconnect the routes inputs and outputs
2149 route->input()->disconnect (0);
2150 route->output()->disconnect (0);
2152 /* if the route had internal sends sending to it, remove them */
2153 if (route->internal_return()) {
2155 boost::shared_ptr<RouteList> r = routes.reader ();
2156 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2157 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2159 (*i)->remove_processor (s);
2164 update_latency_compensation (false, false);
2167 /* get rid of it from the dead wood collection in the route list manager */
2169 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2173 /* try to cause everyone to drop their references */
2175 route->drop_references ();
2177 sync_order_keys (N_("session"));
2179 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2181 /* save the new state of the world */
2183 if (save_state (_current_snapshot_name)) {
2184 save_history (_current_snapshot_name);
2189 Session::route_mute_changed (void* /*src*/)
2195 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2197 boost::shared_ptr<Route> route = wpr.lock();
2199 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2203 if (route->listening()) {
2205 } else if (_listen_cnt > 0) {
2211 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2213 if (solo_update_disabled) {
2218 boost::shared_ptr<Route> route = wpr.lock ();
2221 /* should not happen */
2222 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2226 shared_ptr<RouteList> r = routes.reader ();
2229 if (route->self_soloed()) {
2235 /* now mod the solo level of all other routes except master/control outs/auditioner
2236 so that they will be silent if appropriate.
2239 solo_update_disabled = true;
2241 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2242 bool via_sends_only;
2244 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2246 } else if ((*i)->feeds (route, &via_sends_only)) {
2247 if (!via_sends_only) {
2248 (*i)->mod_solo_by_others (delta);
2253 /* make sure master is never muted by solo */
2255 if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2256 _master_out->mod_solo_by_others (1);
2259 /* ditto for control outs make sure it is never muted by solo */
2261 if (_monitor_out && route != _monitor_out && _monitor_out && _monitor_out->soloed_by_others() == 0) {
2262 _monitor_out->mod_solo_by_others (1);
2265 /* ditto for auditioner make sure it is never muted by solo */
2268 auditioner->mod_solo_by_others (1);
2271 solo_update_disabled = false;
2272 update_route_solo_state (r);
2273 SoloChanged (); /* EMIT SIGNAL */
2278 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2280 /* now figure out if anything that matters is soloed (or is "listening")*/
2282 bool something_soloed = false;
2283 uint32_t listeners = 0;
2286 r = routes.reader();
2289 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2290 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2291 something_soloed = true;
2295 if (!(*i)->is_hidden() && (*i)->listening()) {
2296 if (Config->get_solo_control_is_listen_control()) {
2299 (*i)->set_listen (false, this);
2304 if (something_soloed != _non_soloed_outs_muted) {
2305 _non_soloed_outs_muted = something_soloed;
2306 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2310 _listen_cnt = listeners;
2314 boost::shared_ptr<RouteList>
2315 Session::get_routes_with_internal_returns() const
2317 shared_ptr<RouteList> r = routes.reader ();
2318 boost::shared_ptr<RouteList> rl (new RouteList);
2320 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2321 if ((*i)->internal_return ()) {
2329 Session::route_by_name (string name)
2331 shared_ptr<RouteList> r = routes.reader ();
2333 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2334 if ((*i)->name() == name) {
2339 return shared_ptr<Route> ((Route*) 0);
2343 Session::route_by_id (PBD::ID id)
2345 shared_ptr<RouteList> r = routes.reader ();
2347 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2348 if ((*i)->id() == id) {
2353 return shared_ptr<Route> ((Route*) 0);
2357 Session::route_by_remote_id (uint32_t id)
2359 shared_ptr<RouteList> r = routes.reader ();
2361 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2362 if ((*i)->remote_control_id() == id) {
2367 return shared_ptr<Route> ((Route*) 0);
2371 Session::find_current_end ()
2373 if (_state_of_the_state & Loading) {
2377 nframes_t max = get_maximum_extent ();
2379 if (max > end_location->end()) {
2380 end_location->set_end (max);
2382 DurationChanged(); /* EMIT SIGNAL */
2387 Session::get_maximum_extent () const
2392 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2394 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2395 if ((*i)->destructive()) //ignore tape tracks when getting max extents
2397 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2398 if ((me = pl->get_maximum_extent()) > max) {
2406 boost::shared_ptr<Diskstream>
2407 Session::diskstream_by_name (string name)
2409 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2411 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2412 if ((*i)->name() == name) {
2417 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2420 boost::shared_ptr<Diskstream>
2421 Session::diskstream_by_id (const PBD::ID& id)
2423 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2425 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2426 if ((*i)->id() == id) {
2431 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2434 /* Region management */
2436 boost::shared_ptr<Region>
2437 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2439 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2440 RegionFactory::RegionMap::const_iterator i;
2441 boost::shared_ptr<Region> region;
2443 Glib::Mutex::Lock lm (region_lock);
2445 for (i = regions.begin(); i != regions.end(); ++i) {
2449 if (region->whole_file()) {
2451 if (child->source_equivalent (region)) {
2457 return boost::shared_ptr<Region> ();
2461 Session::destroy_region (boost::shared_ptr<Region> region)
2463 vector<boost::shared_ptr<Source> > srcs;
2466 if (region->playlist()) {
2467 region->playlist()->destroy_region (region);
2470 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2471 srcs.push_back (region->source (n));
2475 region->drop_references ();
2477 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2479 (*i)->mark_for_remove ();
2480 (*i)->drop_references ();
2482 cerr << "source was not used by any playlist\n";
2489 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2491 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2492 destroy_region (*i);
2498 Session::remove_last_capture ()
2500 list<boost::shared_ptr<Region> > r;
2502 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2504 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2505 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2508 r.insert (r.end(), l.begin(), l.end());
2513 destroy_regions (r);
2515 save_state (_current_snapshot_name);
2520 /* Source Management */
2523 Session::add_source (boost::shared_ptr<Source> source)
2525 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2526 pair<SourceMap::iterator,bool> result;
2528 entry.first = source->id();
2529 entry.second = source;
2532 Glib::Mutex::Lock lm (source_lock);
2533 result = sources.insert (entry);
2536 if (result.second) {
2540 boost::shared_ptr<AudioFileSource> afs;
2542 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2543 if (Config->get_auto_analyse_audio()) {
2544 Analyser::queue_source_for_analysis (source, false);
2550 Session::remove_source (boost::weak_ptr<Source> src)
2552 SourceMap::iterator i;
2553 boost::shared_ptr<Source> source = src.lock();
2560 Glib::Mutex::Lock lm (source_lock);
2562 if ((i = sources.find (source->id())) != sources.end()) {
2567 if (!_state_of_the_state & InCleanup) {
2569 /* save state so we don't end up with a session file
2570 referring to non-existent sources.
2573 save_state (_current_snapshot_name);
2577 boost::shared_ptr<Source>
2578 Session::source_by_id (const PBD::ID& id)
2580 Glib::Mutex::Lock lm (source_lock);
2581 SourceMap::iterator i;
2582 boost::shared_ptr<Source> source;
2584 if ((i = sources.find (id)) != sources.end()) {
2591 boost::shared_ptr<Source>
2592 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2594 Glib::Mutex::Lock lm (source_lock);
2596 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2597 cerr << "comparing " << path << " with " << i->second->name() << endl;
2598 boost::shared_ptr<AudioFileSource> afs
2599 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2601 if (afs && afs->path() == path && chn == afs->channel()) {
2605 return boost::shared_ptr<Source>();
2610 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2613 string old_basename = PBD::basename_nosuffix (oldname);
2614 string new_legalized = legalize_for_path (newname);
2616 /* note: we know (or assume) the old path is already valid */
2620 /* destructive file sources have a name of the form:
2622 /path/to/Tnnnn-NAME(%[LR])?.wav
2624 the task here is to replace NAME with the new name.
2627 /* find last slash */
2631 string::size_type slash;
2632 string::size_type dash;
2634 if ((slash = path.find_last_of ('/')) == string::npos) {
2638 dir = path.substr (0, slash+1);
2640 /* '-' is not a legal character for the NAME part of the path */
2642 if ((dash = path.find_last_of ('-')) == string::npos) {
2646 prefix = path.substr (slash+1, dash-(slash+1));
2651 path += new_legalized;
2652 path += ".wav"; /* XXX gag me with a spoon */
2656 /* non-destructive file sources have a name of the form:
2658 /path/to/NAME-nnnnn(%[LR])?.ext
2660 the task here is to replace NAME with the new name.
2665 string::size_type slash;
2666 string::size_type dash;
2667 string::size_type postfix;
2669 /* find last slash */
2671 if ((slash = path.find_last_of ('/')) == string::npos) {
2675 dir = path.substr (0, slash+1);
2677 /* '-' is not a legal character for the NAME part of the path */
2679 if ((dash = path.find_last_of ('-')) == string::npos) {
2683 suffix = path.substr (dash+1);
2685 // Suffix is now everything after the dash. Now we need to eliminate
2686 // the nnnnn part, which is done by either finding a '%' or a '.'
2688 postfix = suffix.find_last_of ("%");
2689 if (postfix == string::npos) {
2690 postfix = suffix.find_last_of ('.');
2693 if (postfix != string::npos) {
2694 suffix = suffix.substr (postfix);
2696 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2700 const uint32_t limit = 10000;
2701 char buf[PATH_MAX+1];
2703 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2705 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2707 if (access (buf, F_OK) != 0) {
2715 error << "FATAL ERROR! Could not find a " << endl;
2723 /** Return the full path (in some session directory) for a new within-session source.
2724 * \a name must be a session-unique name that does not contain slashes
2725 * (e.g. as returned by new_*_source_name)
2728 Session::new_source_path_from_name (DataType type, const string& name)
2730 assert(name.find("/") == string::npos);
2732 SessionDirectory sdir(get_best_session_directory_for_new_source());
2735 if (type == DataType::AUDIO) {
2736 p = sdir.sound_path();
2737 } else if (type == DataType::MIDI) {
2738 p = sdir.midi_path();
2740 error << "Unknown source type, unable to create file path" << endmsg;
2745 return p.to_string();
2749 Session::peak_path (Glib::ustring base) const
2751 sys::path peakfile_path(_session_dir->peak_path());
2752 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2753 return peakfile_path.to_string();
2756 /** Return a unique name based on \a base for a new internal audio source */
2758 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2762 char buf[PATH_MAX+1];
2763 const uint32_t limit = 10000;
2767 legalized = legalize_for_path (base);
2769 // Find a "version" of the base name that doesn't exist in any of the possible directories.
2770 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2772 vector<space_and_path>::iterator i;
2773 uint32_t existing = 0;
2775 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2777 SessionDirectory sdir((*i).path);
2779 spath = sdir.sound_path().to_string();
2784 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2785 spath.c_str(), cnt, legalized.c_str());
2786 } else if (nchan == 2) {
2788 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2789 spath.c_str(), cnt, legalized.c_str());
2791 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2792 spath.c_str(), cnt, legalized.c_str());
2794 } else if (nchan < 26) {
2795 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2796 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2798 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2799 spath.c_str(), cnt, legalized.c_str());
2808 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2809 } else if (nchan == 2) {
2811 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2813 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2815 } else if (nchan < 26) {
2816 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2818 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2822 if (sys::exists(buf)) {
2828 if (existing == 0) {
2833 error << string_compose(
2834 _("There are already %1 recordings for %2, which I consider too many."),
2835 limit, base) << endmsg;
2837 throw failed_constructor();
2841 return Glib::path_get_basename(buf);
2844 /** Create a new within-session audio source */
2845 boost::shared_ptr<AudioFileSource>
2846 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2848 const size_t n_chans = ds.n_channels().n_audio();
2849 const string name = new_audio_source_name (ds.name(), n_chans, chan, destructive);
2850 const string path = new_source_path_from_name(DataType::AUDIO, name);
2852 return boost::dynamic_pointer_cast<AudioFileSource> (
2853 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2856 /** Return a unique name based on \a base for a new internal MIDI source */
2858 Session::new_midi_source_name (const string& base)
2861 char buf[PATH_MAX+1];
2862 const uint32_t limit = 10000;
2866 legalized = legalize_for_path (base);
2868 // Find a "version" of the file name that doesn't exist in any of the possible directories.
2869 for (cnt = 1; cnt <= limit; ++cnt) {
2871 vector<space_and_path>::iterator i;
2872 uint32_t existing = 0;
2874 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2876 SessionDirectory sdir((*i).path);
2878 sys::path p = sdir.midi_path();
2881 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2883 if (sys::exists (buf)) {
2888 if (existing == 0) {
2893 error << string_compose(
2894 _("There are already %1 recordings for %2, which I consider too many."),
2895 limit, base) << endmsg;
2897 throw failed_constructor();
2901 return Glib::path_get_basename(buf);
2905 /** Create a new within-session MIDI source */
2906 boost::shared_ptr<MidiSource>
2907 Session::create_midi_source_for_session (MidiDiskstream& ds)
2909 const string name = new_midi_source_name (ds.name());
2910 const string path = new_source_path_from_name (DataType::MIDI, name);
2912 return boost::dynamic_pointer_cast<SMFSource> (
2913 SourceFactory::createWritable (
2914 DataType::MIDI, *this, path, false, frame_rate()));
2919 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
2921 if (playlist->hidden()) {
2925 playlists->add (playlist);
2928 playlist->release();
2935 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
2937 if (_state_of_the_state & Deletion) {
2941 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
2947 playlists->remove (playlist);
2953 Session::set_audition (boost::shared_ptr<Region> r)
2955 pending_audition_region = r;
2956 add_post_transport_work (PostTransportAudition);
2957 _butler->schedule_transport_work ();
2961 Session::audition_playlist ()
2963 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2964 ev->region.reset ();
2969 Session::non_realtime_set_audition ()
2971 if (!pending_audition_region) {
2972 auditioner->audition_current_playlist ();
2974 auditioner->audition_region (pending_audition_region);
2975 pending_audition_region.reset ();
2977 AuditionActive (true); /* EMIT SIGNAL */
2981 Session::audition_region (boost::shared_ptr<Region> r)
2983 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2989 Session::cancel_audition ()
2991 if (auditioner->auditioning()) {
2992 auditioner->cancel_audition ();
2993 AuditionActive (false); /* EMIT SIGNAL */
2998 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3000 if (a->is_monitor()) {
3003 if (b->is_monitor()) {
3006 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3010 Session::remove_empty_sounds ()
3012 vector<string> audio_filenames;
3014 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3016 Glib::Mutex::Lock lm (source_lock);
3018 TapeFileMatcher tape_file_matcher;
3020 remove_if (audio_filenames.begin(), audio_filenames.end(),
3021 boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3023 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3025 sys::path audio_file_path (_session_dir->sound_path());
3027 audio_file_path /= *i;
3029 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3033 sys::remove (audio_file_path);
3034 const string peakfile = peak_path (audio_file_path.to_string());
3035 sys::remove (peakfile);
3037 catch (const sys::filesystem_error& err)
3039 error << err.what() << endmsg;
3046 Session::is_auditioning () const
3048 /* can be called before we have an auditioner object */
3050 return auditioner->auditioning();
3057 Session::n_diskstreams () const
3061 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3063 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3064 if (!(*i)->hidden()) {
3072 Session::graph_reordered ()
3074 /* don't do this stuff if we are setting up connections
3075 from a set_state() call or creating new tracks. Ditto for deletion.
3078 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3082 /* every track/bus asked for this to be handled but it was deferred because
3083 we were connecting. do it now.
3086 request_input_change_handling ();
3090 /* force all diskstreams to update their capture offset values to
3091 reflect any changes in latencies within the graph.
3094 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3096 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3097 (*i)->set_capture_offset ();
3102 Session::available_capture_duration ()
3104 float sample_bytes_on_disk = 4.0; // keep gcc happy
3106 switch (config.get_native_file_data_format()) {
3108 sample_bytes_on_disk = 4.0;
3112 sample_bytes_on_disk = 3.0;
3116 sample_bytes_on_disk = 2.0;
3120 /* impossible, but keep some gcc versions happy */
3121 fatal << string_compose (_("programming error: %1"),
3122 X_("illegal native file data format"))
3127 double scale = 4096.0 / sample_bytes_on_disk;
3129 if (_total_free_4k_blocks * scale > (double) max_frames) {
3133 return (nframes_t) floor (_total_free_4k_blocks * scale);
3137 Session::add_bundle (shared_ptr<Bundle> bundle)
3140 RCUWriter<BundleList> writer (_bundles);
3141 boost::shared_ptr<BundleList> b = writer.get_copy ();
3142 b->push_back (bundle);
3145 BundleAdded (bundle); /* EMIT SIGNAL */
3151 Session::remove_bundle (shared_ptr<Bundle> bundle)
3153 bool removed = false;
3156 RCUWriter<BundleList> writer (_bundles);
3157 boost::shared_ptr<BundleList> b = writer.get_copy ();
3158 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3160 if (i != b->end()) {
3167 BundleRemoved (bundle); /* EMIT SIGNAL */
3174 Session::bundle_by_name (string name) const
3176 boost::shared_ptr<BundleList> b = _bundles.reader ();
3178 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3179 if ((*i)->name() == name) {
3184 return boost::shared_ptr<Bundle> ();
3188 Session::tempo_map_changed (const PropertyChange&)
3192 playlists->update_after_tempo_map_change ();
3197 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3198 * the given count with the current block size.
3201 Session::ensure_buffers (ChanCount howmany)
3203 BufferManager::ensure_buffers (howmany);
3207 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3209 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3210 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3215 Session::next_insert_id ()
3217 /* this doesn't really loop forever. just think about it */
3220 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3221 if (!insert_bitset[n]) {
3222 insert_bitset[n] = true;
3228 /* none available, so resize and try again */
3230 insert_bitset.resize (insert_bitset.size() + 16, false);
3235 Session::next_send_id ()
3237 /* this doesn't really loop forever. just think about it */
3240 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3241 if (!send_bitset[n]) {
3242 send_bitset[n] = true;
3248 /* none available, so resize and try again */
3250 send_bitset.resize (send_bitset.size() + 16, false);
3255 Session::next_return_id ()
3257 /* this doesn't really loop forever. just think about it */
3260 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3261 if (!return_bitset[n]) {
3262 return_bitset[n] = true;
3268 /* none available, so resize and try again */
3270 return_bitset.resize (return_bitset.size() + 16, false);
3275 Session::mark_send_id (uint32_t id)
3277 if (id >= send_bitset.size()) {
3278 send_bitset.resize (id+16, false);
3280 if (send_bitset[id]) {
3281 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3283 send_bitset[id] = true;
3287 Session::mark_return_id (uint32_t id)
3289 if (id >= return_bitset.size()) {
3290 return_bitset.resize (id+16, false);
3292 if (return_bitset[id]) {
3293 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3295 return_bitset[id] = true;
3299 Session::mark_insert_id (uint32_t id)
3301 if (id >= insert_bitset.size()) {
3302 insert_bitset.resize (id+16, false);
3304 if (insert_bitset[id]) {
3305 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3307 insert_bitset[id] = true;
3311 Session::unmark_send_id (uint32_t id)
3313 if (id < send_bitset.size()) {
3314 send_bitset[id] = false;
3319 Session::unmark_return_id (uint32_t id)
3321 if (id < return_bitset.size()) {
3322 return_bitset[id] = false;
3327 Session::unmark_insert_id (uint32_t id)
3329 if (id < insert_bitset.size()) {
3330 insert_bitset[id] = false;
3335 /* Named Selection management */
3337 boost::shared_ptr<NamedSelection>
3338 Session::named_selection_by_name (string name)
3340 Glib::Mutex::Lock lm (named_selection_lock);
3341 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3342 if ((*i)->name == name) {
3346 return boost::shared_ptr<NamedSelection>();
3350 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3353 Glib::Mutex::Lock lm (named_selection_lock);
3354 named_selections.insert (named_selections.begin(), named_selection);
3359 NamedSelectionAdded (); /* EMIT SIGNAL */
3363 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3365 bool removed = false;
3368 Glib::Mutex::Lock lm (named_selection_lock);
3370 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3372 if (i != named_selections.end()) {
3373 named_selections.erase (i);
3380 NamedSelectionRemoved (); /* EMIT SIGNAL */
3385 Session::reset_native_file_format ()
3387 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3389 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3390 (*i)->reset_write_sources (false);
3395 Session::route_name_unique (string n) const
3397 shared_ptr<RouteList> r = routes.reader ();
3399 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3400 if ((*i)->name() == n) {
3409 Session::route_name_internal (string n) const
3411 if (auditioner && auditioner->name() == n) {
3415 if (_click_io && _click_io->name() == n) {
3423 Session::freeze_all (InterThreadInfo& itt)
3425 shared_ptr<RouteList> r = routes.reader ();
3427 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3429 boost::shared_ptr<Track> t;
3431 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3432 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3442 boost::shared_ptr<Region>
3443 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3444 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3445 InterThreadInfo& itt, bool enable_processing)
3447 boost::shared_ptr<Region> result;
3448 boost::shared_ptr<Playlist> playlist;
3449 boost::shared_ptr<AudioFileSource> fsource;
3451 char buf[PATH_MAX+1];
3452 ChanCount nchans(track.audio_diskstream()->n_channels());
3454 nframes_t this_chunk;
3457 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3458 const string sound_dir = sdir.sound_path().to_string();
3459 nframes_t len = end - start;
3462 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3463 end, start) << endmsg;
3467 const nframes_t chunk_size = (256 * 1024)/4;
3469 // block all process callback handling
3471 block_processing ();
3473 /* call tree *MUST* hold route_lock */
3475 if ((playlist = track.diskstream()->playlist()) == 0) {
3479 /* external redirects will be a problem */
3481 if (track.has_external_redirects()) {
3485 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3487 for (x = 0; x < 99999; ++x) {
3488 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3489 if (access (buf, F_OK) != 0) {
3495 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3500 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3501 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3504 catch (failed_constructor& err) {
3505 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3509 srcs.push_back (fsource);
3512 /* XXX need to flush all redirects */
3517 /* create a set of reasonably-sized buffers */
3518 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3519 buffers.set_count(nchans);
3521 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3522 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3524 afs->prepare_for_peakfile_writes ();
3527 while (to_do && !itt.cancel) {
3529 this_chunk = min (to_do, chunk_size);
3531 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3536 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3537 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3540 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3546 start += this_chunk;
3547 to_do -= this_chunk;
3549 itt.progress = (float) (1.0 - ((double) to_do / len));
3558 xnow = localtime (&now);
3560 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3561 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3564 afs->update_header (position, *xnow, now);
3565 afs->flush_header ();
3569 /* construct a region to represent the bounced material */
3573 plist.add (Properties::start, 0);
3574 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3575 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3577 result = RegionFactory::create (srcs, plist);
3583 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3584 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3587 afs->mark_for_remove ();
3590 (*src)->drop_references ();
3594 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3595 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3598 afs->done_with_peakfile_writes ();
3602 unblock_processing ();
3608 Session::gain_automation_buffer() const
3610 return ProcessThread::gain_automation_buffer ();
3614 Session::pan_automation_buffer() const
3616 return ProcessThread::pan_automation_buffer ();
3620 Session::get_silent_buffers (ChanCount count)
3622 return ProcessThread::get_silent_buffers (count);
3624 assert(_silent_buffers->available() >= count);
3625 _silent_buffers->set_count(count);
3627 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3628 for (size_t i= 0; i < count.get(*t); ++i) {
3629 _silent_buffers->get(*t, i).clear();
3633 return *_silent_buffers;
3638 Session::get_scratch_buffers (ChanCount count)
3640 return ProcessThread::get_scratch_buffers (count);
3642 if (count != ChanCount::ZERO) {
3643 assert(_scratch_buffers->available() >= count);
3644 _scratch_buffers->set_count(count);
3646 _scratch_buffers->set_count (_scratch_buffers->available());
3649 return *_scratch_buffers;
3654 Session::get_mix_buffers (ChanCount count)
3656 return ProcessThread::get_mix_buffers (count);
3658 assert(_mix_buffers->available() >= count);
3659 _mix_buffers->set_count(count);
3660 return *_mix_buffers;
3665 Session::ntracks () const
3668 shared_ptr<RouteList> r = routes.reader ();
3670 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3671 if (boost::dynamic_pointer_cast<Track> (*i)) {
3680 Session::nbusses () const
3683 shared_ptr<RouteList> r = routes.reader ();
3685 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3686 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3695 Session::add_automation_list(AutomationList *al)
3697 automation_lists[al->id()] = al;
3701 Session::compute_initial_length ()
3703 return _engine.frame_rate() * 60 * 5;
3707 Session::sync_order_keys (std::string const & base)
3709 if (deletion_in_progress()) {
3713 if (!Config->get_sync_all_route_ordering()) {
3714 /* leave order keys as they are */
3718 boost::shared_ptr<RouteList> r = routes.reader ();
3720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3721 (*i)->sync_order_keys (base);
3724 Route::SyncOrderKeys (base); // EMIT SIGNAL
3726 /* this might not do anything */
3728 set_remote_control_ids ();
3731 /** @return true if there is at least one record-enabled diskstream, otherwise false */
3733 Session::have_rec_enabled_diskstream () const
3735 return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
3738 /** Update the state of our rec-enabled diskstreams flag */
3740 Session::update_have_rec_enabled_diskstream ()
3742 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
3743 DiskstreamList::iterator i = dsl->begin ();
3744 while (i != dsl->end () && (*i)->record_enabled () == false) {
3748 int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
3750 g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
3752 if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
3753 RecordStateChanged (); /* EMIT SIGNAL */
3758 Session::listen_position_changed ()
3762 switch (Config->get_listen_position()) {
3763 case AfterFaderListen:
3767 case PreFaderListen:
3772 boost::shared_ptr<RouteList> r = routes.reader ();
3774 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3775 (*i)->put_monitor_send_at (p);
3780 Session::solo_control_mode_changed ()
3782 /* cancel all solo or all listen when solo control mode changes */
3785 set_solo (get_routes(), false);
3786 } else if (listening()) {
3787 set_listen (get_routes(), false);
3792 Session::route_group_changed ()
3794 RouteGroupChanged (); /* EMIT SIGNAL */
3798 Session::get_available_sync_options () const
3800 vector<SyncSource> ret;
3802 ret.push_back (JACK);
3805 ret.push_back (MTC);
3808 if (midi_clock_port()) {
3809 ret.push_back (MIDIClock);
3815 boost::shared_ptr<RouteList>
3816 Session::get_routes_with_regions_at (nframes64_t const p) const
3818 shared_ptr<RouteList> r = routes.reader ();
3819 shared_ptr<RouteList> rl (new RouteList);
3821 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3822 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3827 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
3832 boost::shared_ptr<Playlist> pl = ds->playlist ();
3837 if (pl->has_region_at (p)) {