2 Copyright (C) 1999-2004 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 */
32 #include <glibmm/thread.h>
33 #include <glibmm/miscutils.h>
34 #include <glibmm/fileutils.h>
35 #include <glibmm/thread.h>
37 #include "pbd/error.h"
38 #include "pbd/boost_debug.h"
39 #include "pbd/pathscanner.h"
40 #include "pbd/stl_delete.h"
41 #include "pbd/basename.h"
42 #include "pbd/stacktrace.h"
43 #include "pbd/file_utils.h"
44 #include "pbd/convert.h"
46 #include "ardour/amp.h"
47 #include "ardour/analyser.h"
48 #include "ardour/audio_buffer.h"
49 #include "ardour/audio_diskstream.h"
50 #include "ardour/audio_port.h"
51 #include "ardour/audio_track.h"
52 #include "ardour/audioengine.h"
53 #include "ardour/audiofilesource.h"
54 #include "ardour/audioplaylist.h"
55 #include "ardour/audioregion.h"
56 #include "ardour/auditioner.h"
57 #include "ardour/buffer_set.h"
58 #include "ardour/bundle.h"
59 #include "ardour/butler.h"
60 #include "ardour/click.h"
61 #include "ardour/configuration.h"
62 #include "ardour/crossfade.h"
63 #include "ardour/cycle_timer.h"
64 #include "ardour/data_type.h"
65 #include "ardour/debug.h"
66 #include "ardour/filename_extensions.h"
67 #include "ardour/internal_send.h"
68 #include "ardour/io_processor.h"
69 #include "ardour/midi_diskstream.h"
70 #include "ardour/midi_playlist.h"
71 #include "ardour/midi_region.h"
72 #include "ardour/midi_track.h"
73 #include "ardour/midi_ui.h"
74 #include "ardour/named_selection.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),
134 _scratch_buffers(new BufferSet()),
135 _silent_buffers(new BufferSet()),
136 _mix_buffers(new BufferSet()),
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 diskstreams (new DiskstreamList),
148 routes (new RouteList),
149 _total_free_4k_blocks (0),
150 _bundles (new BundleList),
151 _bundle_xml_node (0),
154 click_emphasis_data (0),
156 _metadata (new SessionMetadata()),
157 _have_rec_enabled_diskstream (false)
160 playlists.reset (new SessionPlaylists);
162 interpolation.add_channel_to (0, 0);
164 if (!eng.connected()) {
165 throw failed_constructor();
168 n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
169 n_physical_inputs = _engine.n_physical_inputs(DataType::AUDIO);
171 first_stage_init (fullpath, snapshot_name);
173 _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
176 if (create (mix_template, compute_initial_length(), bus_profile)) {
178 throw failed_constructor ();
182 if (second_stage_init ()) {
184 throw failed_constructor ();
187 store_recent_sessions(_name, _path);
189 bool was_dirty = dirty();
191 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
193 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
194 config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
197 DirtyChanged (); /* EMIT SIGNAL */
211 vector<void*> debug_pointers;
213 /* if we got to here, leaving pending capture state around
217 remove_pending_capture_state ();
219 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
221 _engine.remove_session ();
223 /* clear history so that no references to objects are held any more */
227 /* clear state tree so that no references to objects are held any more */
231 /* reset dynamic state version back to default */
233 Stateful::loading_state_version = 0;
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 delete _scratch_buffers;
249 delete _silent_buffers;
252 /* clear out any pending dead wood from RCU managed objects */
255 diskstreams.flush ();
258 AudioDiskstream::free_working_buffers();
260 /* tell everyone who is still standing that we're about to die */
263 /* tell everyone to drop references and delete objects as we go */
265 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
266 named_selections.clear ();
268 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
269 RegionFactory::delete_all_regions ();
271 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
273 /* reset these three references to special routes before we do the usual route delete thing */
276 _master_out.reset ();
277 _monitor_out.reset ();
280 RCUWriter<RouteList> writer (routes);
281 boost::shared_ptr<RouteList> r = writer.get_copy ();
283 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
284 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
285 (*i)->drop_references ();
289 /* writer goes out of scope and updates master */
293 boost::shared_ptr<RouteList> r = routes.reader ();
295 DEBUG_TRACE (DEBUG::Destruction, "delete diskstreams\n");
297 RCUWriter<DiskstreamList> dwriter (diskstreams);
298 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
299 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
300 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for diskstream %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
301 (*i)->drop_references ();
306 diskstreams.flush ();
308 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
309 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
310 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
311 i->second->drop_references ();
316 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
317 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
322 Crossfade::set_buffer_size (0);
326 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
329 boost_debug_list_ptrs ();
331 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
335 Session::set_worst_io_latencies ()
337 _worst_output_latency = 0;
338 _worst_input_latency = 0;
340 if (!_engine.connected()) {
344 boost::shared_ptr<RouteList> r = routes.reader ();
346 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
347 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
348 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
353 Session::when_engine_running ()
355 string first_physical_output;
357 BootMessage (_("Set block size and sample rate"));
359 set_block_size (_engine.frames_per_cycle());
360 set_frame_rate (_engine.frame_rate());
362 BootMessage (_("Using configuration"));
364 boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
365 boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
367 Config->map_parameters (ff);
368 config.map_parameters (ft);
370 /* every time we reconnect, recompute worst case output latencies */
372 _engine.Running.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies, this));
374 if (synced_to_jack()) {
375 _engine.transport_stop ();
378 if (config.get_jack_time_master()) {
379 _engine.transport_locate (_transport_frame);
387 _click_io.reset (new ClickIO (*this, "click"));
389 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
391 /* existing state for Click */
394 if (Stateful::loading_state_version < 3000) {
395 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
397 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
402 _clicking = Config->get_clicking ();
406 error << _("could not setup Click I/O") << endmsg;
413 /* default state for Click: dual-mono to first 2 physical outputs */
415 for (int physport = 0; physport < 2; ++physport) {
416 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
418 if (physical_output.length()) {
419 if (_click_io->add_port (physical_output, this)) {
420 // relax, even though its an error
425 if (_click_io->n_ports () > ChanCount::ZERO) {
426 _clicking = Config->get_clicking ();
431 catch (failed_constructor& err) {
432 error << _("cannot setup Click I/O") << endmsg;
435 BootMessage (_("Compute I/O Latencies"));
437 set_worst_io_latencies ();
440 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
443 BootMessage (_("Set up standard connections"));
445 /* Create a set of Bundle objects that map
446 to the physical I/O currently available. We create both
447 mono and stereo bundles, so that the common cases of mono
448 and stereo tracks get bundles to put in their mixer strip
449 in / out menus. There may be a nicer way of achieving that;
450 it doesn't really scale that well to higher channel counts
453 /* mono output bundles */
455 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
457 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
459 shared_ptr<Bundle> c (new Bundle (buf, true));
460 c->add_channel (_("mono"));
461 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
466 /* stereo output bundles */
468 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
469 if (np + 1 < n_physical_outputs) {
471 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
472 shared_ptr<Bundle> c (new Bundle (buf, true));
473 c->add_channel (_("L"));
474 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
475 c->add_channel (_("R"));
476 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
482 /* mono input bundles */
484 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
486 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
488 shared_ptr<Bundle> c (new Bundle (buf, false));
489 c->add_channel (_("mono"));
490 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
495 /* stereo input bundles */
497 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
498 if (np + 1 < n_physical_inputs) {
500 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
502 shared_ptr<Bundle> c (new Bundle (buf, false));
503 c->add_channel (_("L"));
504 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
505 c->add_channel (_("R"));
506 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
512 BootMessage (_("Setup signal flow and plugins"));
516 if (_is_new && !no_auto_connect()) {
518 /* don't connect the master bus outputs if there is a monitor bus */
520 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
522 /* if requested auto-connect the outputs to the first N physical ports.
525 uint32_t limit = _master_out->n_outputs().n_total();
527 for (uint32_t n = 0; n < limit; ++n) {
528 Port* p = _master_out->output()->nth (n);
529 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
531 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
532 if (_master_out->output()->connect (p, connect_to, this)) {
533 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
543 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
544 are undefined, at best.
547 /* control out listens to master bus (but ignores it
548 under some conditions)
551 uint32_t limit = _monitor_out->n_inputs().n_audio();
554 for (uint32_t n = 0; n < limit; ++n) {
555 AudioPort* p = _monitor_out->input()->ports().nth_audio_port (n);
556 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
559 string connect_to = o->name();
560 if (_monitor_out->input()->connect (p, connect_to, this)) {
561 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
569 /* if control out is not connected, connect control out to physical outs
572 if (!_monitor_out->output()->connected ()) {
574 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
576 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
579 _monitor_out->output()->connect_ports_to_bundle (b, this);
581 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
582 Config->get_monitor_bus_preferred_bundle())
588 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
589 uint32_t mod = _engine.n_physical_outputs (*t);
590 uint32_t limit = _monitor_out->n_outputs().get(*t);
592 for (uint32_t n = 0; n < limit; ++n) {
594 Port* p = _monitor_out->output()->ports().port(*t, n);
595 string connect_to = _engine.get_nth_physical_output (*t, (n % mod));
597 if (!connect_to.empty()) {
598 if (_monitor_out->output()->connect (p, connect_to, this)) {
599 error << string_compose (
600 _("cannot connect control output %1 to %2"),
613 /* catch up on send+insert cnts */
615 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
617 /* hook us up to the engine */
619 BootMessage (_("Connect to engine"));
621 _engine.set_session (this);
625 Session::hookup_io ()
627 /* stop graph reordering notifications from
628 causing resorts, etc.
631 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
636 /* we delay creating the auditioner till now because
637 it makes its own connections to ports.
641 Auditioner* a = new Auditioner (*this);
644 throw failed_constructor();
646 a->use_new_diskstream ();
647 auditioner.reset (a);
650 catch (failed_constructor& err) {
651 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
655 /* load bundles, which we may have postponed earlier on */
656 if (_bundle_xml_node) {
657 load_bundles (*_bundle_xml_node);
658 delete _bundle_xml_node;
661 /* Tell all IO objects to connect themselves together */
663 IO::enable_connecting ();
664 MIDI::JACK_MidiPort::MakeConnections ();
666 /* Now reset all panners */
668 Delivery::reset_panners ();
670 /* Connect tracks to monitor/listen bus if there is one.
671 Note that in an existing session, the internal sends will
672 already exist, but we want the routes to notice that
673 they connect to the control out specifically.
677 boost::shared_ptr<RouteList> r = routes.reader ();
678 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
680 if ((*x)->is_monitor()) {
684 } else if ((*x)->is_master()) {
690 (*x)->listen_via (_monitor_out,
691 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
697 /* Anyone who cares about input state, wake up and do something */
699 IOConnectionsComplete (); /* EMIT SIGNAL */
701 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
703 /* now handle the whole enchilada as if it was one
709 /* update the full solo state, which can't be
710 correctly determined on a per-route basis, but
711 needs the global overview that only the session
715 update_route_solo_state ();
719 Session::playlist_length_changed ()
721 /* we can't just increase end_location->end() if pl->get_maximum_extent()
722 if larger. if the playlist used to be the longest playlist,
723 and its now shorter, we have to decrease end_location->end(). hence,
724 we have to iterate over all diskstreams and check the
725 playlists currently in use.
731 Session::diskstream_playlist_changed (boost::weak_ptr<Diskstream> wp)
733 boost::shared_ptr<Diskstream> dstream = wp.lock ();
738 boost::shared_ptr<Playlist> playlist;
740 if ((playlist = dstream->playlist()) != 0) {
741 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
744 /* see comment in playlist_length_changed () */
749 Session::record_enabling_legal () const
751 /* this used to be in here, but survey says.... we don't need to restrict it */
752 // if (record_status() == Recording) {
756 if (Config->get_all_safe()) {
763 Session::reset_input_monitor_state ()
765 if (transport_rolling()) {
767 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
769 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
770 if ((*i)->record_enabled ()) {
771 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
772 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
776 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
778 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
779 if ((*i)->record_enabled ()) {
780 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
781 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
788 Session::auto_punch_start_changed (Location* location)
790 replace_event (SessionEvent::PunchIn, location->start());
792 if (get_record_enabled() && config.get_punch_in()) {
793 /* capture start has been changed, so save new pending state */
794 save_state ("", true);
799 Session::auto_punch_end_changed (Location* location)
801 nframes_t when_to_stop = location->end();
802 // when_to_stop += _worst_output_latency + _worst_input_latency;
803 replace_event (SessionEvent::PunchOut, when_to_stop);
807 Session::auto_punch_changed (Location* location)
809 nframes_t when_to_stop = location->end();
811 replace_event (SessionEvent::PunchIn, location->start());
812 //when_to_stop += _worst_output_latency + _worst_input_latency;
813 replace_event (SessionEvent::PunchOut, when_to_stop);
817 Session::auto_loop_changed (Location* location)
819 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
821 if (transport_rolling() && play_loop) {
824 // if (_transport_frame > location->end()) {
826 if (_transport_frame < location->start() || _transport_frame > location->end()) {
827 // relocate to beginning of loop
828 clear_events (SessionEvent::LocateRoll);
830 request_locate (location->start(), true);
833 else if (Config->get_seamless_loop() && !loop_changing) {
835 // schedule a locate-roll to refill the diskstreams at the
837 loop_changing = true;
839 if (location->end() > last_loopend) {
840 clear_events (SessionEvent::LocateRoll);
841 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
848 last_loopend = location->end();
852 Session::set_auto_punch_location (Location* location)
856 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
857 punch_connections.drop_connections();
858 existing->set_auto_punch (false, this);
859 remove_event (existing->start(), SessionEvent::PunchIn);
860 clear_events (SessionEvent::PunchOut);
861 auto_punch_location_changed (0);
870 if (location->end() <= location->start()) {
871 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
875 punch_connections.drop_connections ();
877 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
878 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
879 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
881 location->set_auto_punch (true, this);
883 auto_punch_changed (location);
885 auto_punch_location_changed (location);
889 Session::set_auto_loop_location (Location* location)
893 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
894 loop_connections.drop_connections ();
895 existing->set_auto_loop (false, this);
896 remove_event (existing->end(), SessionEvent::AutoLoop);
897 auto_loop_location_changed (0);
906 if (location->end() <= location->start()) {
907 error << _("Session: you can't use a mark for auto loop") << endmsg;
911 last_loopend = location->end();
913 loop_connections.drop_connections ();
915 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
916 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
917 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
919 location->set_auto_loop (true, this);
921 /* take care of our stuff first */
923 auto_loop_changed (location);
925 /* now tell everyone else */
927 auto_loop_location_changed (location);
931 Session::locations_added (Location *)
937 Session::locations_changed ()
939 _locations.apply (*this, &Session::handle_locations_changed);
943 Session::handle_locations_changed (Locations::LocationList& locations)
945 Locations::LocationList::iterator i;
947 bool set_loop = false;
948 bool set_punch = false;
950 for (i = locations.begin(); i != locations.end(); ++i) {
954 if (location->is_auto_punch()) {
955 set_auto_punch_location (location);
958 if (location->is_auto_loop()) {
959 set_auto_loop_location (location);
963 if (location->is_start()) {
964 start_location = location;
966 if (location->is_end()) {
967 end_location = location;
972 set_auto_loop_location (0);
975 set_auto_punch_location (0);
982 Session::enable_record ()
984 /* XXX really atomic compare+swap here */
985 if (g_atomic_int_get (&_record_status) != Recording) {
986 g_atomic_int_set (&_record_status, Recording);
987 _last_record_location = _transport_frame;
988 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
990 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
991 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
992 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
993 if ((*i)->record_enabled ()) {
994 (*i)->monitor_input (true);
999 RecordStateChanged ();
1004 Session::disable_record (bool rt_context, bool force)
1008 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1010 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1011 g_atomic_int_set (&_record_status, Disabled);
1013 if (rs == Recording) {
1014 g_atomic_int_set (&_record_status, Enabled);
1018 // FIXME: timestamp correct? [DR]
1019 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1020 // does this /need/ to be sent in all cases?
1022 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1025 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1026 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1028 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1029 if ((*i)->record_enabled ()) {
1030 (*i)->monitor_input (false);
1035 RecordStateChanged (); /* emit signal */
1038 remove_pending_capture_state ();
1044 Session::step_back_from_record ()
1046 /* XXX really atomic compare+swap here */
1047 if (g_atomic_int_get (&_record_status) == Recording) {
1048 g_atomic_int_set (&_record_status, Enabled);
1050 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1051 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1053 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1054 if ((*i)->record_enabled ()) {
1055 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1056 (*i)->monitor_input (false);
1064 Session::maybe_enable_record ()
1066 g_atomic_int_set (&_record_status, Enabled);
1068 /* this function is currently called from somewhere other than an RT thread.
1069 this save_state() call therefore doesn't impact anything.
1072 save_state ("", true);
1074 if (_transport_speed) {
1075 if (!config.get_punch_in()) {
1079 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1080 RecordStateChanged (); /* EMIT SIGNAL */
1087 Session::audible_frame () const
1093 /* the first of these two possible settings for "offset"
1094 mean that the audible frame is stationary until
1095 audio emerges from the latency compensation
1098 the second means that the audible frame is stationary
1099 until audio would emerge from a physical port
1100 in the absence of any plugin latency compensation
1103 offset = _worst_output_latency;
1105 if (offset > current_block_size) {
1106 offset -= current_block_size;
1108 /* XXX is this correct? if we have no external
1109 physical connections and everything is internal
1110 then surely this is zero? still, how
1111 likely is that anyway?
1113 offset = current_block_size;
1116 if (synced_to_jack()) {
1117 tf = _engine.transport_frame();
1119 tf = _transport_frame;
1124 if (!non_realtime_work_pending()) {
1128 /* check to see if we have passed the first guaranteed
1129 audible frame past our last start position. if not,
1130 return that last start point because in terms
1131 of audible frames, we have not moved yet.
1134 if (_transport_speed > 0.0f) {
1136 if (!play_loop || !have_looped) {
1137 if (tf < _last_roll_location + offset) {
1138 return _last_roll_location;
1146 } else if (_transport_speed < 0.0f) {
1148 /* XXX wot? no backward looping? */
1150 if (tf > _last_roll_location - offset) {
1151 return _last_roll_location;
1163 Session::set_frame_rate (nframes_t frames_per_second)
1165 /** \fn void Session::set_frame_size(nframes_t)
1166 the AudioEngine object that calls this guarantees
1167 that it will not be called while we are also in
1168 ::process(). Its fine to do things that block
1172 _base_frame_rate = frames_per_second;
1176 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1180 // XXX we need some equivalent to this, somehow
1181 // SndFileSource::setup_standard_crossfades (frames_per_second);
1185 /* XXX need to reset/reinstantiate all LADSPA plugins */
1189 Session::set_block_size (nframes_t nframes)
1191 /* the AudioEngine guarantees
1192 that it will not be called while we are also in
1193 ::process(). It is therefore fine to do things that block
1198 current_block_size = nframes;
1200 ensure_buffers(_scratch_buffers->available());
1202 delete [] _gain_automation_buffer;
1203 _gain_automation_buffer = new gain_t[nframes];
1205 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1207 boost::shared_ptr<RouteList> r = routes.reader ();
1209 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1210 (*i)->set_block_size (nframes);
1213 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1214 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1215 (*i)->set_block_size (nframes);
1218 set_worst_io_latencies ();
1223 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1226 nframes_t fade_frames;
1228 /* Don't allow fade of less 1 frame */
1230 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1237 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1241 default_fade_msecs = fade_msecs;
1242 default_fade_steepness = steepness;
1245 // jlc, WTF is this!
1246 Glib::RWLock::ReaderLock lm (route_lock);
1247 AudioRegion::set_default_fade (steepness, fade_frames);
1252 /* XXX have to do this at some point */
1253 /* foreach region using default fade, reset, then
1254 refill_all_diskstream_buffers ();
1259 struct RouteSorter {
1260 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1261 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1263 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1266 if (r1->fed_by.empty()) {
1267 if (r2->fed_by.empty()) {
1268 /* no ardour-based connections inbound to either route. just use signal order */
1269 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1271 /* r2 has connections, r1 does not; run r1 early */
1275 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1282 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1284 shared_ptr<Route> r2;
1286 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1287 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1291 /* make a copy of the existing list of routes that feed r1 */
1293 set<weak_ptr<Route> > existing = r1->fed_by;
1295 /* for each route that feeds r1, recurse, marking it as feeding
1299 for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1300 if (!(r2 = (*i).lock ())) {
1301 /* (*i) went away, ignore it */
1305 /* r2 is a route that feeds r1 which somehow feeds base. mark
1306 base as being fed by r2
1309 rbase->fed_by.insert (r2);
1313 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1317 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1321 /* now recurse, so that we can mark base as being fed by
1322 all routes that feed r2
1325 trace_terminal (r2, rbase);
1332 Session::resort_routes ()
1334 /* don't do anything here with signals emitted
1335 by Routes while we are being destroyed.
1338 if (_state_of_the_state & Deletion) {
1345 RCUWriter<RouteList> writer (routes);
1346 shared_ptr<RouteList> r = writer.get_copy ();
1347 resort_routes_using (r);
1348 /* writer goes out of scope and forces update */
1353 Session::resort_routes_using (shared_ptr<RouteList> r)
1355 RouteList::iterator i, j;
1357 for (i = r->begin(); i != r->end(); ++i) {
1359 (*i)->fed_by.clear ();
1361 for (j = r->begin(); j != r->end(); ++j) {
1363 /* although routes can feed themselves, it will
1364 cause an endless recursive descent if we
1365 detect it. so don't bother checking for
1373 if ((*j)->feeds (*i)) {
1374 (*i)->fed_by.insert (*j);
1379 for (i = r->begin(); i != r->end(); ++i) {
1380 trace_terminal (*i, *i);
1387 cerr << "finished route resort\n";
1389 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1390 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1397 /** Find the route name starting with \a base with the lowest \a id.
1399 * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1400 * The available route name with the lowest ID will be used, and \a id
1401 * will be set to the ID.
1403 * \return false if a route name could not be found, and \a track_name
1404 * and \a id do not reflect a free route name.
1407 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1410 snprintf (name, name_len, "%s %" PRIu32, base, id);
1412 if (route_by_name (name) == 0) {
1418 } while (id < (UINT_MAX-1));
1424 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1426 in = ChanCount::ZERO;
1427 out = ChanCount::ZERO;
1428 shared_ptr<RouteList> r = routes.reader ();
1429 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1430 if (!(*i)->is_hidden()) {
1431 in += (*i)->n_inputs();
1432 out += (*i)->n_outputs();
1437 list<boost::shared_ptr<MidiTrack> >
1438 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1440 char track_name[32];
1441 uint32_t track_id = 0;
1442 ChanCount existing_inputs;
1443 ChanCount existing_outputs;
1445 RouteList new_routes;
1446 list<boost::shared_ptr<MidiTrack> > ret;
1447 uint32_t control_id;
1449 count_existing_route_channels (existing_inputs, existing_outputs);
1451 control_id = ntracks() + nbusses();
1454 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1455 error << "cannot find name for new midi track" << endmsg;
1459 shared_ptr<MidiTrack> track;
1462 MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1469 mt->use_new_diskstream();
1471 boost_debug_shared_ptr_mark_interesting (mt, "Track");
1472 track = boost::shared_ptr<MidiTrack>(mt);
1474 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1475 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1480 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1481 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1485 auto_connect_route (track, existing_inputs, existing_outputs);
1487 track->midi_diskstream()->non_realtime_input_change();
1489 route_group->add (track);
1492 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1493 track->set_remote_control_id (control_id);
1495 new_routes.push_back (track);
1496 ret.push_back (track);
1499 catch (failed_constructor &err) {
1500 error << _("Session: could not create new midi track.") << endmsg;
1503 /* we need to get rid of this, since the track failed to be created */
1504 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1507 RCUWriter<DiskstreamList> writer (diskstreams);
1508 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1509 ds->remove (track->midi_diskstream());
1516 catch (AudioEngine::PortRegistrationFailure& pfe) {
1518 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;
1521 /* we need to get rid of this, since the track failed to be created */
1522 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1525 RCUWriter<DiskstreamList> writer (diskstreams);
1526 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1527 ds->remove (track->midi_diskstream());
1538 if (!new_routes.empty()) {
1539 add_routes (new_routes, false);
1540 save_state (_current_snapshot_name);
1547 Session::auto_connect_route (boost::shared_ptr<Route> route,
1548 ChanCount& existing_inputs, ChanCount& existing_outputs)
1550 /* If both inputs and outputs are auto-connected to physical ports,
1551 use the max of input and output offsets to ensure auto-connected
1552 port numbers always match up (e.g. the first audio input and the
1553 first audio output of the route will have the same physical
1554 port number). Otherwise just use the lowest input or output
1557 const bool in_out_physical =
1558 (Config->get_input_auto_connect() & AutoConnectPhysical)
1559 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1561 const ChanCount in_offset = in_out_physical
1562 ? ChanCount::max(existing_inputs, existing_outputs)
1565 const ChanCount out_offset = in_out_physical
1566 ? ChanCount::max(existing_inputs, existing_outputs)
1569 static string empty_string;
1570 string& port = empty_string;
1572 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1573 vector<string> physinputs;
1574 vector<string> physoutputs;
1576 _engine.get_physical_outputs (*t, physoutputs);
1577 _engine.get_physical_inputs (*t, physinputs);
1579 if (!physinputs.empty()) {
1580 uint32_t nphysical_in = physinputs.size();
1581 for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1582 port = empty_string;
1584 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1585 port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1588 if (!port.empty() && route->input()->connect (
1589 route->input()->ports().port(*t, i), port, this)) {
1595 if (!physoutputs.empty()) {
1596 uint32_t nphysical_out = physoutputs.size();
1597 for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1598 port = empty_string;
1600 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1601 port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1602 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1603 if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1604 port = _master_out->input()->ports().port(*t,
1605 i % _master_out->input()->n_ports().get(*t))->name();
1609 if (!port.empty() && route->output()->connect (
1610 route->output()->ports().port(*t, i), port, this)) {
1617 existing_inputs += route->n_inputs();
1618 existing_outputs += route->n_outputs();
1621 list< boost::shared_ptr<AudioTrack> >
1622 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1624 char track_name[32];
1625 uint32_t track_id = 0;
1626 ChanCount existing_inputs;
1627 ChanCount existing_outputs;
1629 RouteList new_routes;
1630 list<boost::shared_ptr<AudioTrack> > ret;
1631 uint32_t control_id;
1633 count_existing_route_channels (existing_inputs, existing_outputs);
1635 control_id = ntracks() + nbusses() + 1;
1638 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1639 error << "cannot find name for new audio track" << endmsg;
1643 shared_ptr<AudioTrack> track;
1646 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1653 at->use_new_diskstream();
1655 boost_debug_shared_ptr_mark_interesting (at, "Track");
1656 track = boost::shared_ptr<AudioTrack>(at);
1658 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1659 error << string_compose (
1660 _("cannot configure %1 in/%2 out configuration for new audio track"),
1661 input_channels, output_channels)
1666 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1667 error << string_compose (
1668 _("cannot configure %1 in/%2 out configuration for new audio track"),
1669 input_channels, output_channels)
1674 auto_connect_route (track, existing_inputs, existing_outputs);
1677 route_group->add (track);
1680 track->audio_diskstream()->non_realtime_input_change();
1682 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1683 track->set_remote_control_id (control_id);
1686 new_routes.push_back (track);
1687 ret.push_back (track);
1690 catch (failed_constructor &err) {
1691 error << _("Session: could not create new audio track.") << endmsg;
1694 /* we need to get rid of this, since the track failed to be created */
1695 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1698 RCUWriter<DiskstreamList> writer (diskstreams);
1699 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1700 ds->remove (track->audio_diskstream());
1707 catch (AudioEngine::PortRegistrationFailure& pfe) {
1709 error << pfe.what() << endmsg;
1712 /* we need to get rid of this, since the track failed to be created */
1713 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1716 RCUWriter<DiskstreamList> writer (diskstreams);
1717 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1718 ds->remove (track->audio_diskstream());
1729 if (!new_routes.empty()) {
1730 add_routes (new_routes, true);
1737 Session::set_remote_control_ids ()
1739 RemoteModel m = Config->get_remote_model();
1740 bool emit_signal = false;
1742 shared_ptr<RouteList> r = routes.reader ();
1744 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1745 if (MixerOrdered == m) {
1746 long order = (*i)->order_key(N_("signal"));
1747 (*i)->set_remote_control_id (order+1, false);
1749 } else if (EditorOrdered == m) {
1750 long order = (*i)->order_key(N_("editor"));
1751 (*i)->set_remote_control_id (order+1, false);
1753 } else if (UserOrdered == m) {
1754 //do nothing ... only changes to remote id's are initiated by user
1759 Route::RemoteControlIDChange();
1765 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1768 uint32_t bus_id = 0;
1769 ChanCount existing_inputs;
1770 ChanCount existing_outputs;
1773 uint32_t control_id;
1775 count_existing_route_channels (existing_inputs, existing_outputs);
1777 control_id = ntracks() + nbusses() + 1;
1780 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1781 error << "cannot find name for new audio bus" << endmsg;
1786 Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1793 boost_debug_shared_ptr_mark_interesting (rt, "Route");
1794 shared_ptr<Route> bus (rt);
1796 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1797 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1798 input_channels, output_channels)
1804 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1805 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1806 input_channels, output_channels)
1811 auto_connect_route (bus, existing_inputs, existing_outputs);
1814 route_group->add (bus);
1816 bus->set_remote_control_id (control_id);
1820 bus->add_internal_return ();
1823 ret.push_back (bus);
1827 catch (failed_constructor &err) {
1828 error << _("Session: could not create new audio route.") << endmsg;
1832 catch (AudioEngine::PortRegistrationFailure& pfe) {
1833 error << pfe.what() << endmsg;
1843 add_routes (ret, true);
1851 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1855 uint32_t control_id;
1857 uint32_t number = 0;
1859 if (!tree.read (template_path.c_str())) {
1863 XMLNode* node = tree.root();
1865 control_id = ntracks() + nbusses() + 1;
1869 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1871 std::string node_name = IO::name_from_state (*node_copy.children().front());
1873 /* generate a new name by adding a number to the end of the template name */
1874 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1875 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1879 IO::set_name_in_state (*node_copy.children().front(), name);
1881 Track::zero_diskstream_id_in_xml (node_copy);
1884 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1887 error << _("Session: cannot create track/bus from template description") << endmsg;
1891 if (boost::dynamic_pointer_cast<Track>(route)) {
1892 /* force input/output change signals so that the new diskstream
1893 picks up the configuration of the route. During session
1894 loading this normally happens in a different way.
1896 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1897 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1900 route->set_remote_control_id (control_id);
1903 ret.push_back (route);
1906 catch (failed_constructor &err) {
1907 error << _("Session: could not create new route from template") << endmsg;
1911 catch (AudioEngine::PortRegistrationFailure& pfe) {
1912 error << pfe.what() << endmsg;
1921 add_routes (ret, true);
1928 Session::add_routes (RouteList& new_routes, bool save)
1931 RCUWriter<RouteList> writer (routes);
1932 shared_ptr<RouteList> r = writer.get_copy ();
1933 r->insert (r->end(), new_routes.begin(), new_routes.end());
1936 /* if there is no control out and we're not in the middle of loading,
1937 resort the graph here. if there is a control out, we will resort
1938 toward the end of this method. if we are in the middle of loading,
1939 we will resort when done.
1942 if (!_monitor_out && IO::connecting_legal) {
1943 resort_routes_using (r);
1947 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1949 boost::weak_ptr<Route> wpr (*x);
1950 boost::shared_ptr<Route> r (*x);
1952 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1953 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, wpr));
1954 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1955 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1956 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1957 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
1959 if (r->is_master()) {
1963 if (r->is_monitor()) {
1968 if (_monitor_out && IO::connecting_legal) {
1970 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1971 if ((*x)->is_monitor()) {
1973 } else if ((*x)->is_master()) {
1976 (*x)->listen_via (_monitor_out,
1977 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
1988 save_state (_current_snapshot_name);
1991 RouteAdded (new_routes); /* EMIT SIGNAL */
1992 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
1996 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
1998 boost::shared_ptr<RouteList> r = routes.reader ();
1999 boost::shared_ptr<Send> s;
2003 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2004 if (boost::dynamic_pointer_cast<Track>(*i)) {
2005 if ((s = (*i)->internal_send_for (dest)) != 0) {
2006 s->amp()->gain_control()->set_value (0.0);
2013 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2015 boost::shared_ptr<RouteList> r = routes.reader ();
2016 boost::shared_ptr<Send> s;
2020 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2021 if (boost::dynamic_pointer_cast<Track>(*i)) {
2022 if ((s = (*i)->internal_send_for (dest)) != 0) {
2023 s->amp()->gain_control()->set_value (1.0);
2030 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2032 boost::shared_ptr<RouteList> r = routes.reader ();
2033 boost::shared_ptr<Send> s;
2037 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2038 if (boost::dynamic_pointer_cast<Track>(*i)) {
2039 if ((s = (*i)->internal_send_for (dest)) != 0) {
2040 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2047 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2049 boost::shared_ptr<RouteList> r = routes.reader ();
2050 boost::shared_ptr<RouteList> t (new RouteList);
2052 /* only send tracks */
2054 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2055 if (boost::dynamic_pointer_cast<Track>(*i)) {
2060 add_internal_sends (dest, p, t);
2064 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2066 if (dest->is_monitor() || dest->is_master()) {
2070 if (!dest->internal_return()) {
2071 dest->add_internal_return();
2074 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2076 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2080 (*i)->listen_via (dest, p, true, true);
2087 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2089 /* need to do this in case we're rolling at the time, to prevent false underruns */
2090 dstream->do_refill_with_alloc ();
2092 dstream->set_block_size (current_block_size);
2095 RCUWriter<DiskstreamList> writer (diskstreams);
2096 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2097 ds->push_back (dstream);
2098 /* writer goes out of scope, copies ds back to main */
2101 dstream->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::diskstream_playlist_changed, this, boost::weak_ptr<Diskstream> (dstream)));
2102 /* this will connect to future changes, and check the current length */
2103 diskstream_playlist_changed (boost::weak_ptr<Diskstream> (dstream));
2105 dstream->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_diskstream, this));
2107 dstream->prepare ();
2112 Session::remove_route (shared_ptr<Route> route)
2115 RCUWriter<RouteList> writer (routes);
2116 shared_ptr<RouteList> rs = writer.get_copy ();
2120 /* deleting the master out seems like a dumb
2121 idea, but its more of a UI policy issue
2125 if (route == _master_out) {
2126 _master_out = shared_ptr<Route> ();
2129 if (route == _monitor_out) {
2131 /* cancel control outs for all routes */
2133 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2134 (*r)->drop_listen (_monitor_out);
2137 _monitor_out.reset ();
2140 update_route_solo_state ();
2142 /* writer goes out of scope, forces route list update */
2145 boost::shared_ptr<Track> t;
2146 boost::shared_ptr<Diskstream> ds;
2148 if ((t = boost::dynamic_pointer_cast<Track>(route)) != 0) {
2149 ds = t->diskstream();
2155 RCUWriter<DiskstreamList> dsl (diskstreams);
2156 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2161 find_current_end ();
2163 // We need to disconnect the routes inputs and outputs
2165 route->input()->disconnect (0);
2166 route->output()->disconnect (0);
2168 /* if the route had internal sends sending to it, remove them */
2169 if (route->internal_return()) {
2171 boost::shared_ptr<RouteList> r = routes.reader ();
2172 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2173 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2175 (*i)->remove_processor (s);
2180 update_latency_compensation (false, false);
2183 /* get rid of it from the dead wood collection in the route list manager */
2185 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2189 /* try to cause everyone to drop their references */
2191 route->drop_references ();
2193 sync_order_keys (N_("session"));
2195 Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2197 /* save the new state of the world */
2199 if (save_state (_current_snapshot_name)) {
2200 save_history (_current_snapshot_name);
2205 Session::route_mute_changed (void* /*src*/)
2211 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2213 boost::shared_ptr<Route> route = wpr.lock();
2215 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2219 if (route->listening()) {
2221 } else if (_listen_cnt > 0) {
2227 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2229 if (solo_update_disabled) {
2234 boost::shared_ptr<Route> route = wpr.lock ();
2237 /* should not happen */
2238 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2242 shared_ptr<RouteList> r = routes.reader ();
2245 if (route->self_soloed()) {
2251 /* now mod the solo level of all other routes except master & control outs
2252 so that they will be silent if appropriate.
2255 solo_update_disabled = true;
2257 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2258 bool via_sends_only;
2260 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2262 } else if ((*i)->feeds (route, &via_sends_only)) {
2263 if (!via_sends_only) {
2264 (*i)->mod_solo_by_others (delta);
2269 /* make sure master is never muted by solo */
2271 if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2272 _master_out->mod_solo_by_others (1);
2275 /* ditto for control outs make sure master is never muted by solo */
2277 if (_monitor_out && route != _monitor_out && _monitor_out && _monitor_out->soloed_by_others() == 0) {
2278 _monitor_out->mod_solo_by_others (1);
2281 solo_update_disabled = false;
2282 update_route_solo_state (r);
2283 SoloChanged (); /* EMIT SIGNAL */
2288 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2290 /* now figure out if anything that matters is soloed (or is "listening")*/
2292 bool something_soloed = false;
2293 uint32_t listeners = 0;
2296 r = routes.reader();
2299 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2300 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2301 something_soloed = true;
2305 if (!(*i)->is_hidden() && (*i)->listening()) {
2310 if (something_soloed != _non_soloed_outs_muted) {
2311 _non_soloed_outs_muted = something_soloed;
2312 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2316 _listen_cnt = listeners;
2320 boost::shared_ptr<RouteList>
2321 Session::get_routes_with_internal_returns() const
2323 shared_ptr<RouteList> r = routes.reader ();
2324 boost::shared_ptr<RouteList> rl (new RouteList);
2326 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2327 if ((*i)->internal_return ()) {
2335 Session::route_by_name (string name)
2337 shared_ptr<RouteList> r = routes.reader ();
2339 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2340 if ((*i)->name() == name) {
2345 return shared_ptr<Route> ((Route*) 0);
2349 Session::route_by_id (PBD::ID id)
2351 shared_ptr<RouteList> r = routes.reader ();
2353 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2354 if ((*i)->id() == id) {
2359 return shared_ptr<Route> ((Route*) 0);
2363 Session::route_by_remote_id (uint32_t id)
2365 shared_ptr<RouteList> r = routes.reader ();
2367 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2368 if ((*i)->remote_control_id() == id) {
2373 return shared_ptr<Route> ((Route*) 0);
2377 Session::find_current_end ()
2379 if (_state_of_the_state & Loading) {
2383 nframes_t max = get_maximum_extent ();
2385 if (max > end_location->end()) {
2386 end_location->set_end (max);
2388 DurationChanged(); /* EMIT SIGNAL */
2393 Session::get_maximum_extent () const
2398 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2400 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2401 if ((*i)->destructive()) //ignore tape tracks when getting max extents
2403 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2404 if ((me = pl->get_maximum_extent()) > max) {
2412 boost::shared_ptr<Diskstream>
2413 Session::diskstream_by_name (string name)
2415 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2417 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2418 if ((*i)->name() == name) {
2423 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2426 boost::shared_ptr<Diskstream>
2427 Session::diskstream_by_id (const PBD::ID& id)
2429 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2431 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2432 if ((*i)->id() == id) {
2437 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2440 /* Region management */
2443 Session::new_region_name (string old)
2445 string::size_type last_period;
2447 string::size_type len = old.length() + 64;
2450 if ((last_period = old.find_last_of ('.')) == string::npos) {
2452 /* no period present - add one explicitly */
2455 last_period = old.length() - 1;
2460 number = atoi (old.substr (last_period+1).c_str());
2464 while (number < (UINT_MAX-1)) {
2466 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2467 RegionFactory::RegionMap::const_iterator i;
2472 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2475 for (i = regions.begin(); i != regions.end(); ++i) {
2476 if (i->second->name() == sbuf) {
2481 if (i == regions.end()) {
2486 if (number != (UINT_MAX-1)) {
2490 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2495 Session::region_name (string& result, string base, bool newlevel)
2500 if (base.find("/") != string::npos) {
2501 base = base.substr(base.find_last_of("/") + 1);
2506 snprintf (buf, sizeof (buf), "%d", RegionFactory::nregions() + 1);
2515 string::size_type pos;
2517 pos = base.find_last_of ('.');
2519 /* pos may be npos, but then we just use entire base */
2521 subbase = base.substr (0, pos);
2526 Glib::Mutex::Lock lm (region_lock);
2528 map<string,uint32_t>::iterator x;
2532 if ((x = region_name_map.find (subbase)) == region_name_map.end()) {
2534 region_name_map[subbase] = 1;
2537 snprintf (buf, sizeof (buf), ".%d", x->second);
2548 Session::add_region (boost::shared_ptr<Region> region)
2550 vector<boost::shared_ptr<Region> > v;
2551 v.push_back (region);
2556 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2558 /* mark dirty because something has changed
2563 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2565 boost::shared_ptr<Region> region = *ii;
2568 region->PropertyChanged.connect_same_thread (*this, boost::bind (&Session::region_changed, this, _1, boost::weak_ptr<Region>(region)));
2569 update_region_name_map (region);
2572 if (!new_regions.empty()) {
2573 RegionsAdded (new_regions); /* EMIT SIGNAL */
2578 Session::update_region_name_map (boost::shared_ptr<Region> region)
2580 string::size_type last_period = region->name().find_last_of ('.');
2582 if (last_period != string::npos && last_period < region->name().length() - 1) {
2584 string base = region->name().substr (0, last_period);
2585 string number = region->name().substr (last_period+1);
2586 map<string,uint32_t>::iterator x;
2588 /* note that if there is no number, we get zero from atoi,
2592 region_name_map[base] = atoi (number);
2597 Session::region_changed (const PropertyChange& what_changed, boost::weak_ptr<Region> weak_region)
2599 boost::shared_ptr<Region> region (weak_region.lock ());
2605 if (what_changed.contains (Properties::hidden)) {
2606 /* relay hidden changes */
2607 RegionHiddenChange (region);
2610 if (what_changed.contains (Properties::name)) {
2611 update_region_name_map (region);
2616 Session::remove_region (boost::weak_ptr<Region> weak_region)
2618 boost::shared_ptr<Region> region (weak_region.lock ());
2624 RegionFactory::map_remove (region);
2627 RegionRemoved(region); /* EMIT SIGNAL */
2630 boost::shared_ptr<Region>
2631 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2633 const RegionFactory::RegionMap& regions (RegionFactory::regions());
2634 RegionFactory::RegionMap::const_iterator i;
2635 boost::shared_ptr<Region> region;
2637 Glib::Mutex::Lock lm (region_lock);
2639 for (i = regions.begin(); i != regions.end(); ++i) {
2643 if (region->whole_file()) {
2645 if (child->source_equivalent (region)) {
2651 return boost::shared_ptr<Region> ();
2655 Session::destroy_region (boost::shared_ptr<Region> region)
2657 vector<boost::shared_ptr<Source> > srcs;
2660 if (region->playlist()) {
2661 region->playlist()->destroy_region (region);
2664 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2665 srcs.push_back (region->source (n));
2669 region->drop_references ();
2671 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2673 (*i)->mark_for_remove ();
2674 (*i)->drop_references ();
2676 cerr << "source was not used by any playlist\n";
2683 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2685 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2686 destroy_region (*i);
2692 Session::remove_last_capture ()
2694 list<boost::shared_ptr<Region> > r;
2696 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2698 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2699 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2702 r.insert (r.end(), l.begin(), l.end());
2707 destroy_regions (r);
2709 save_state (_current_snapshot_name);
2714 /* Source Management */
2717 Session::add_source (boost::shared_ptr<Source> source)
2719 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2720 pair<SourceMap::iterator,bool> result;
2722 entry.first = source->id();
2723 entry.second = source;
2726 Glib::Mutex::Lock lm (source_lock);
2727 result = sources.insert (entry);
2730 if (result.second) {
2734 boost::shared_ptr<AudioFileSource> afs;
2736 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2737 if (Config->get_auto_analyse_audio()) {
2738 Analyser::queue_source_for_analysis (source, false);
2744 Session::remove_source (boost::weak_ptr<Source> src)
2746 SourceMap::iterator i;
2747 boost::shared_ptr<Source> source = src.lock();
2754 Glib::Mutex::Lock lm (source_lock);
2756 if ((i = sources.find (source->id())) != sources.end()) {
2761 if (!_state_of_the_state & InCleanup) {
2763 /* save state so we don't end up with a session file
2764 referring to non-existent sources.
2767 save_state (_current_snapshot_name);
2771 boost::shared_ptr<Source>
2772 Session::source_by_id (const PBD::ID& id)
2774 Glib::Mutex::Lock lm (source_lock);
2775 SourceMap::iterator i;
2776 boost::shared_ptr<Source> source;
2778 if ((i = sources.find (id)) != sources.end()) {
2785 boost::shared_ptr<Source>
2786 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2788 Glib::Mutex::Lock lm (source_lock);
2790 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2791 cerr << "comparing " << path << " with " << i->second->name() << endl;
2792 boost::shared_ptr<AudioFileSource> afs
2793 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2795 if (afs && afs->path() == path && chn == afs->channel()) {
2799 return boost::shared_ptr<Source>();
2804 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2807 string old_basename = PBD::basename_nosuffix (oldname);
2808 string new_legalized = legalize_for_path (newname);
2810 /* note: we know (or assume) the old path is already valid */
2814 /* destructive file sources have a name of the form:
2816 /path/to/Tnnnn-NAME(%[LR])?.wav
2818 the task here is to replace NAME with the new name.
2821 /* find last slash */
2825 string::size_type slash;
2826 string::size_type dash;
2828 if ((slash = path.find_last_of ('/')) == string::npos) {
2832 dir = path.substr (0, slash+1);
2834 /* '-' is not a legal character for the NAME part of the path */
2836 if ((dash = path.find_last_of ('-')) == string::npos) {
2840 prefix = path.substr (slash+1, dash-(slash+1));
2845 path += new_legalized;
2846 path += ".wav"; /* XXX gag me with a spoon */
2850 /* non-destructive file sources have a name of the form:
2852 /path/to/NAME-nnnnn(%[LR])?.ext
2854 the task here is to replace NAME with the new name.
2859 string::size_type slash;
2860 string::size_type dash;
2861 string::size_type postfix;
2863 /* find last slash */
2865 if ((slash = path.find_last_of ('/')) == string::npos) {
2869 dir = path.substr (0, slash+1);
2871 /* '-' is not a legal character for the NAME part of the path */
2873 if ((dash = path.find_last_of ('-')) == string::npos) {
2877 suffix = path.substr (dash+1);
2879 // Suffix is now everything after the dash. Now we need to eliminate
2880 // the nnnnn part, which is done by either finding a '%' or a '.'
2882 postfix = suffix.find_last_of ("%");
2883 if (postfix == string::npos) {
2884 postfix = suffix.find_last_of ('.');
2887 if (postfix != string::npos) {
2888 suffix = suffix.substr (postfix);
2890 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2894 const uint32_t limit = 10000;
2895 char buf[PATH_MAX+1];
2897 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2899 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2901 if (access (buf, F_OK) != 0) {
2909 error << "FATAL ERROR! Could not find a " << endl;
2917 /** Return the full path (in some session directory) for a new within-session source.
2918 * \a name must be a session-unique name that does not contain slashes
2919 * (e.g. as returned by new_*_source_name)
2922 Session::new_source_path_from_name (DataType type, const string& name)
2924 assert(name.find("/") == string::npos);
2926 SessionDirectory sdir(get_best_session_directory_for_new_source());
2929 if (type == DataType::AUDIO) {
2930 p = sdir.sound_path();
2931 } else if (type == DataType::MIDI) {
2932 p = sdir.midi_path();
2934 error << "Unknown source type, unable to create file path" << endmsg;
2939 return p.to_string();
2943 Session::peak_path (Glib::ustring base) const
2945 sys::path peakfile_path(_session_dir->peak_path());
2946 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2947 return peakfile_path.to_string();
2950 /** Return a unique name based on \a base for a new internal audio source */
2952 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2956 char buf[PATH_MAX+1];
2957 const uint32_t limit = 10000;
2961 legalized = legalize_for_path (base);
2963 // Find a "version" of the base name that doesn't exist in any of the possible directories.
2964 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2966 vector<space_and_path>::iterator i;
2967 uint32_t existing = 0;
2969 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2971 SessionDirectory sdir((*i).path);
2973 spath = sdir.sound_path().to_string();
2978 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2979 spath.c_str(), cnt, legalized.c_str());
2980 } else if (nchan == 2) {
2982 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2983 spath.c_str(), cnt, legalized.c_str());
2985 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2986 spath.c_str(), cnt, legalized.c_str());
2988 } else if (nchan < 26) {
2989 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2990 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2992 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2993 spath.c_str(), cnt, legalized.c_str());
3002 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3003 } else if (nchan == 2) {
3005 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3007 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3009 } else if (nchan < 26) {
3010 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3012 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3016 if (sys::exists(buf)) {
3022 if (existing == 0) {
3027 error << string_compose(
3028 _("There are already %1 recordings for %2, which I consider too many."),
3029 limit, base) << endmsg;
3031 throw failed_constructor();
3035 return Glib::path_get_basename(buf);
3038 /** Create a new within-session audio source */
3039 boost::shared_ptr<AudioFileSource>
3040 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3042 const size_t n_chans = ds.n_channels().n_audio();
3043 const string name = new_audio_source_name (ds.name(), n_chans, chan, destructive);
3044 const string path = new_source_path_from_name(DataType::AUDIO, name);
3046 return boost::dynamic_pointer_cast<AudioFileSource> (
3047 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3050 /** Return a unique name based on \a base for a new internal MIDI source */
3052 Session::new_midi_source_name (const string& base)
3055 char buf[PATH_MAX+1];
3056 const uint32_t limit = 10000;
3060 legalized = legalize_for_path (base);
3062 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3063 for (cnt = 1; cnt <= limit; ++cnt) {
3065 vector<space_and_path>::iterator i;
3066 uint32_t existing = 0;
3068 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3070 SessionDirectory sdir((*i).path);
3072 sys::path p = sdir.midi_path();
3075 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
3077 if (sys::exists (buf)) {
3082 if (existing == 0) {
3087 error << string_compose(
3088 _("There are already %1 recordings for %2, which I consider too many."),
3089 limit, base) << endmsg;
3091 throw failed_constructor();
3095 return Glib::path_get_basename(buf);
3099 /** Create a new within-session MIDI source */
3100 boost::shared_ptr<MidiSource>
3101 Session::create_midi_source_for_session (MidiDiskstream& ds)
3103 const string name = new_midi_source_name (ds.name());
3104 const string path = new_source_path_from_name (DataType::MIDI, name);
3106 return boost::dynamic_pointer_cast<SMFSource> (
3107 SourceFactory::createWritable (
3108 DataType::MIDI, *this, path, false, frame_rate()));
3113 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3115 if (playlist->hidden()) {
3119 playlists->add (playlist);
3122 playlist->release();
3129 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3131 if (_state_of_the_state & Deletion) {
3135 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3141 playlists->remove (playlist);
3147 Session::set_audition (boost::shared_ptr<Region> r)
3149 pending_audition_region = r;
3150 add_post_transport_work (PostTransportAudition);
3151 _butler->schedule_transport_work ();
3155 Session::audition_playlist ()
3157 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3158 ev->region.reset ();
3163 Session::non_realtime_set_audition ()
3165 if (!pending_audition_region) {
3166 auditioner->audition_current_playlist ();
3168 auditioner->audition_region (pending_audition_region);
3169 pending_audition_region.reset ();
3171 AuditionActive (true); /* EMIT SIGNAL */
3175 Session::audition_region (boost::shared_ptr<Region> r)
3177 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3183 Session::cancel_audition ()
3185 if (auditioner->auditioning()) {
3186 auditioner->cancel_audition ();
3187 AuditionActive (false); /* EMIT SIGNAL */
3192 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3194 if (a->is_monitor()) {
3197 if (b->is_monitor()) {
3200 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3204 Session::remove_empty_sounds ()
3206 vector<string> audio_filenames;
3208 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3210 Glib::Mutex::Lock lm (source_lock);
3212 TapeFileMatcher tape_file_matcher;
3214 remove_if (audio_filenames.begin(), audio_filenames.end(),
3215 boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3217 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3219 sys::path audio_file_path (_session_dir->sound_path());
3221 audio_file_path /= *i;
3223 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3227 sys::remove (audio_file_path);
3228 const string peakfile = peak_path (audio_file_path.to_string());
3229 sys::remove (peakfile);
3231 catch (const sys::filesystem_error& err)
3233 error << err.what() << endmsg;
3240 Session::is_auditioning () const
3242 /* can be called before we have an auditioner object */
3244 return auditioner->auditioning();
3251 Session::n_diskstreams () const
3255 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3257 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3258 if (!(*i)->hidden()) {
3266 Session::graph_reordered ()
3268 /* don't do this stuff if we are setting up connections
3269 from a set_state() call or creating new tracks. Ditto for deletion.
3272 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3276 /* every track/bus asked for this to be handled but it was deferred because
3277 we were connecting. do it now.
3280 request_input_change_handling ();
3284 /* force all diskstreams to update their capture offset values to
3285 reflect any changes in latencies within the graph.
3288 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3290 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3291 (*i)->set_capture_offset ();
3296 Session::add_processor (Processor* processor)
3298 /* Session does not own Processors (they belong to a Route) but we do want to track
3299 the arrival and departure of port inserts, sends and returns for naming
3302 processor->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_processor, this, processor));
3307 Session::remove_processor (Processor* processor)
3311 PortInsert* port_insert;
3313 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3314 insert_bitset[port_insert->bit_slot()] = false;
3315 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3316 send_bitset[send->bit_slot()] = false;
3317 } else if ((retrn = dynamic_cast<Return *> (processor)) != 0) {
3318 return_bitset[retrn->bit_slot()] = false;
3325 Session::available_capture_duration ()
3327 float sample_bytes_on_disk = 4.0; // keep gcc happy
3329 switch (config.get_native_file_data_format()) {
3331 sample_bytes_on_disk = 4.0;
3335 sample_bytes_on_disk = 3.0;
3339 sample_bytes_on_disk = 2.0;
3343 /* impossible, but keep some gcc versions happy */
3344 fatal << string_compose (_("programming error: %1"),
3345 X_("illegal native file data format"))
3350 double scale = 4096.0 / sample_bytes_on_disk;
3352 if (_total_free_4k_blocks * scale > (double) max_frames) {
3356 return (nframes_t) floor (_total_free_4k_blocks * scale);
3360 Session::add_bundle (shared_ptr<Bundle> bundle)
3363 RCUWriter<BundleList> writer (_bundles);
3364 boost::shared_ptr<BundleList> b = writer.get_copy ();
3365 b->push_back (bundle);
3368 BundleAdded (bundle); /* EMIT SIGNAL */
3374 Session::remove_bundle (shared_ptr<Bundle> bundle)
3376 bool removed = false;
3379 RCUWriter<BundleList> writer (_bundles);
3380 boost::shared_ptr<BundleList> b = writer.get_copy ();
3381 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3383 if (i != b->end()) {
3390 BundleRemoved (bundle); /* EMIT SIGNAL */
3397 Session::bundle_by_name (string name) const
3399 boost::shared_ptr<BundleList> b = _bundles.reader ();
3401 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3402 if ((*i)->name() == name) {
3407 return boost::shared_ptr<Bundle> ();
3411 Session::tempo_map_changed (const PropertyChange&)
3415 playlists->update_after_tempo_map_change ();
3420 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3421 * the given count with the current block size.
3424 Session::ensure_buffers (ChanCount howmany)
3426 if (current_block_size == 0) {
3427 return; // too early? (is this ok?)
3430 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3431 size_t count = std::max(_scratch_buffers->available().get(*t), howmany.get(*t));
3432 _scratch_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3433 _mix_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3434 _silent_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3437 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3441 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3443 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3444 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3449 Session::next_insert_id ()
3451 /* this doesn't really loop forever. just think about it */
3454 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3455 if (!insert_bitset[n]) {
3456 insert_bitset[n] = true;
3462 /* none available, so resize and try again */
3464 insert_bitset.resize (insert_bitset.size() + 16, false);
3469 Session::next_send_id ()
3471 /* this doesn't really loop forever. just think about it */
3474 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3475 if (!send_bitset[n]) {
3476 send_bitset[n] = true;
3482 /* none available, so resize and try again */
3484 send_bitset.resize (send_bitset.size() + 16, false);
3489 Session::next_return_id ()
3491 /* this doesn't really loop forever. just think about it */
3494 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3495 if (!return_bitset[n]) {
3496 return_bitset[n] = true;
3502 /* none available, so resize and try again */
3504 return_bitset.resize (return_bitset.size() + 16, false);
3509 Session::mark_send_id (uint32_t id)
3511 if (id >= send_bitset.size()) {
3512 send_bitset.resize (id+16, false);
3514 if (send_bitset[id]) {
3515 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3517 send_bitset[id] = true;
3521 Session::mark_return_id (uint32_t id)
3523 if (id >= return_bitset.size()) {
3524 return_bitset.resize (id+16, false);
3526 if (return_bitset[id]) {
3527 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3529 return_bitset[id] = true;
3533 Session::mark_insert_id (uint32_t id)
3535 if (id >= insert_bitset.size()) {
3536 insert_bitset.resize (id+16, false);
3538 if (insert_bitset[id]) {
3539 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3541 insert_bitset[id] = true;
3544 /* Named Selection management */
3546 boost::shared_ptr<NamedSelection>
3547 Session::named_selection_by_name (string name)
3549 Glib::Mutex::Lock lm (named_selection_lock);
3550 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3551 if ((*i)->name == name) {
3555 return boost::shared_ptr<NamedSelection>();
3559 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3562 Glib::Mutex::Lock lm (named_selection_lock);
3563 named_selections.insert (named_selections.begin(), named_selection);
3568 NamedSelectionAdded (); /* EMIT SIGNAL */
3572 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3574 bool removed = false;
3577 Glib::Mutex::Lock lm (named_selection_lock);
3579 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3581 if (i != named_selections.end()) {
3582 named_selections.erase (i);
3589 NamedSelectionRemoved (); /* EMIT SIGNAL */
3594 Session::reset_native_file_format ()
3596 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3598 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3599 (*i)->reset_write_sources (false);
3604 Session::route_name_unique (string n) const
3606 shared_ptr<RouteList> r = routes.reader ();
3608 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3609 if ((*i)->name() == n) {
3618 Session::route_name_internal (string n) const
3620 if (auditioner && auditioner->name() == n) {
3624 if (_click_io && _click_io->name() == n) {
3632 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3634 if (!force && howmany <= _npan_buffers) {
3638 if (_pan_automation_buffer) {
3640 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3641 delete [] _pan_automation_buffer[i];
3644 delete [] _pan_automation_buffer;
3647 _pan_automation_buffer = new pan_t*[howmany];
3649 for (uint32_t i = 0; i < howmany; ++i) {
3650 _pan_automation_buffer[i] = new pan_t[nframes];
3653 _npan_buffers = howmany;
3657 Session::freeze_all (InterThreadInfo& itt)
3659 shared_ptr<RouteList> r = routes.reader ();
3661 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3663 boost::shared_ptr<Track> t;
3665 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3666 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3676 boost::shared_ptr<Region>
3677 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3678 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3679 InterThreadInfo& itt, bool enable_processing)
3681 boost::shared_ptr<Region> result;
3682 boost::shared_ptr<Playlist> playlist;
3683 boost::shared_ptr<AudioFileSource> fsource;
3685 char buf[PATH_MAX+1];
3686 ChanCount nchans(track.audio_diskstream()->n_channels());
3688 nframes_t this_chunk;
3691 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3692 const string sound_dir = sdir.sound_path().to_string();
3693 nframes_t len = end - start;
3696 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3697 end, start) << endmsg;
3701 const nframes_t chunk_size = (256 * 1024)/4;
3703 // block all process callback handling
3705 block_processing ();
3707 /* call tree *MUST* hold route_lock */
3709 if ((playlist = track.diskstream()->playlist()) == 0) {
3713 /* external redirects will be a problem */
3715 if (track.has_external_redirects()) {
3719 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3721 for (x = 0; x < 99999; ++x) {
3722 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3723 if (access (buf, F_OK) != 0) {
3729 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3734 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3735 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3738 catch (failed_constructor& err) {
3739 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3743 srcs.push_back (fsource);
3746 /* XXX need to flush all redirects */
3751 /* create a set of reasonably-sized buffers */
3752 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3753 buffers.set_count(nchans);
3755 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3756 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3758 afs->prepare_for_peakfile_writes ();
3761 while (to_do && !itt.cancel) {
3763 this_chunk = min (to_do, chunk_size);
3765 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3770 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3771 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3774 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3780 start += this_chunk;
3781 to_do -= this_chunk;
3783 itt.progress = (float) (1.0 - ((double) to_do / len));
3792 xnow = localtime (&now);
3794 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3795 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3798 afs->update_header (position, *xnow, now);
3799 afs->flush_header ();
3803 /* construct a region to represent the bounced material */
3807 plist.add (Properties::start, 0);
3808 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3809 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3811 result = RegionFactory::create (srcs, plist);
3817 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3818 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3821 afs->mark_for_remove ();
3824 (*src)->drop_references ();
3828 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3829 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3832 afs->done_with_peakfile_writes ();
3836 unblock_processing ();
3842 Session::get_silent_buffers (ChanCount count)
3844 assert(_silent_buffers->available() >= count);
3845 _silent_buffers->set_count(count);
3847 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3848 for (size_t i= 0; i < count.get(*t); ++i) {
3849 _silent_buffers->get(*t, i).clear();
3853 return *_silent_buffers;
3857 Session::get_scratch_buffers (ChanCount count)
3859 if (count != ChanCount::ZERO) {
3860 assert(_scratch_buffers->available() >= count);
3861 _scratch_buffers->set_count(count);
3863 _scratch_buffers->set_count (_scratch_buffers->available());
3866 return *_scratch_buffers;
3870 Session::get_mix_buffers (ChanCount count)
3872 assert(_mix_buffers->available() >= count);
3873 _mix_buffers->set_count(count);
3874 return *_mix_buffers;
3878 Session::ntracks () const
3881 shared_ptr<RouteList> r = routes.reader ();
3883 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3884 if (boost::dynamic_pointer_cast<Track> (*i)) {
3893 Session::nbusses () const
3896 shared_ptr<RouteList> r = routes.reader ();
3898 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3899 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3908 Session::add_automation_list(AutomationList *al)
3910 automation_lists[al->id()] = al;
3914 Session::compute_initial_length ()
3916 return _engine.frame_rate() * 60 * 5;
3920 Session::sync_order_keys (std::string const & base)
3922 if (deletion_in_progress()) {
3926 if (!Config->get_sync_all_route_ordering()) {
3927 /* leave order keys as they are */
3931 boost::shared_ptr<RouteList> r = routes.reader ();
3933 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3934 (*i)->sync_order_keys (base);
3937 Route::SyncOrderKeys (base); // EMIT SIGNAL
3939 /* this might not do anything */
3941 set_remote_control_ids ();
3944 /** @return true if there is at least one record-enabled diskstream, otherwise false */
3946 Session::have_rec_enabled_diskstream () const
3948 return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
3951 /** Update the state of our rec-enabled diskstreams flag */
3953 Session::update_have_rec_enabled_diskstream ()
3955 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
3956 DiskstreamList::iterator i = dsl->begin ();
3957 while (i != dsl->end () && (*i)->record_enabled () == false) {
3961 int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
3963 g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
3965 if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
3966 RecordStateChanged (); /* EMIT SIGNAL */
3971 Session::listen_position_changed ()
3975 switch (Config->get_listen_position()) {
3976 case AfterFaderListen:
3980 case PreFaderListen:
3985 boost::shared_ptr<RouteList> r = routes.reader ();
3987 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3988 (*i)->put_monitor_send_at (p);
3993 Session::solo_control_mode_changed ()
3995 /* cancel all solo or all listen when solo control mode changes */
3998 set_solo (get_routes(), false);
3999 } else if (listening()) {
4000 set_listen (get_routes(), false);
4005 Session::route_group_changed ()
4007 RouteGroupChanged (); /* EMIT SIGNAL */
4011 Session::get_available_sync_options () const
4013 vector<SyncSource> ret;
4015 ret.push_back (JACK);
4018 ret.push_back (MTC);
4021 if (midi_clock_port()) {
4022 ret.push_back (MIDIClock);
4028 boost::shared_ptr<RouteList>
4029 Session::get_routes_with_regions_at (nframes64_t const p) const
4031 shared_ptr<RouteList> r = routes.reader ();
4032 shared_ptr<RouteList> rl (new RouteList);
4034 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4035 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4040 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
4045 boost::shared_ptr<Playlist> pl = ds->playlist ();
4050 if (pl->has_region_at (p)) {