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>
36 #include "pbd/error.h"
37 #include <glibmm/thread.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"
45 #include "ardour/amp.h"
46 #include "ardour/analyser.h"
47 #include "ardour/audio_buffer.h"
48 #include "ardour/audio_diskstream.h"
49 #include "ardour/audio_port.h"
50 #include "ardour/audio_track.h"
51 #include "ardour/audioengine.h"
52 #include "ardour/audiofilesource.h"
53 #include "ardour/audioplaylist.h"
54 #include "ardour/audioregion.h"
55 #include "ardour/auditioner.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/playlist.h"
75 #include "ardour/plugin_insert.h"
76 #include "ardour/port_insert.h"
77 #include "ardour/processor.h"
78 #include "ardour/rc_configuration.h"
79 #include "ardour/recent_sessions.h"
80 #include "ardour/region_factory.h"
81 #include "ardour/return.h"
82 #include "ardour/route_group.h"
83 #include "ardour/send.h"
84 #include "ardour/session.h"
85 #include "ardour/session_directory.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_metadata.h"
88 #include "ardour/session_playlists.h"
89 #include "ardour/slave.h"
90 #include "ardour/smf_source.h"
91 #include "ardour/source_factory.h"
92 #include "ardour/tape_file_matcher.h"
93 #include "ardour/tempo.h"
94 #include "ardour/utils.h"
99 using namespace ARDOUR;
101 using boost::shared_ptr;
102 using boost::weak_ptr;
104 bool Session::_disable_all_loaded_plugins = false;
106 PBD::Signal1<void,std::string> Session::Dialog;
107 PBD::Signal0<int> Session::AskAboutPendingState;
108 PBD::Signal2<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
109 PBD::Signal0<void> Session::SendFeedback;
111 PBD::Signal0<void> Session::TimecodeOffsetChanged;
112 PBD::Signal0<void> Session::StartTimeChanged;
113 PBD::Signal0<void> Session::EndTimeChanged;
114 PBD::Signal0<void> Session::AutoBindingOn;
115 PBD::Signal0<void> Session::AutoBindingOff;
116 PBD::Signal2<void,std::string, std::string> Session::Exported;
117 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
119 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
120 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
122 Session::Session (AudioEngine &eng,
123 const string& fullpath,
124 const string& snapshot_name,
128 _target_transport_speed (0.0),
129 _requested_return_frame (-1),
130 _scratch_buffers(new BufferSet()),
131 _silent_buffers(new BufferSet()),
132 _mix_buffers(new BufferSet()),
134 _mmc_port (default_mmc_port),
135 _mtc_port (default_mtc_port),
136 _midi_port (default_midi_port),
137 _midi_clock_port (default_midi_clock_port),
138 _session_dir (new SessionDirectory(fullpath)),
140 _butler (new Butler (*this)),
141 _post_transport_work (0),
142 _send_timecode_update (false),
143 diskstreams (new DiskstreamList),
144 routes (new RouteList),
145 _total_free_4k_blocks (0),
146 _bundles (new BundleList),
147 _bundle_xml_node (0),
150 click_emphasis_data (0),
152 _metadata (new SessionMetadata()),
153 _have_rec_enabled_diskstream (false)
156 playlists.reset (new SessionPlaylists);
160 interpolation.add_channel_to (0, 0);
162 if (!eng.connected()) {
163 throw failed_constructor();
166 info << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
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 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
176 if (create (new_session, mix_template, compute_initial_length())) {
178 throw failed_constructor ();
182 if (second_stage_init (new_session)) {
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 */
201 Session::Session (AudioEngine &eng,
203 string snapshot_name,
204 AutoConnectOption input_ac,
205 AutoConnectOption output_ac,
206 uint32_t control_out_channels,
207 uint32_t master_out_channels,
208 uint32_t requested_physical_in,
209 uint32_t requested_physical_out,
210 nframes_t initial_length)
213 _target_transport_speed (0.0),
214 _requested_return_frame (-1),
215 _scratch_buffers(new BufferSet()),
216 _silent_buffers(new BufferSet()),
217 _mix_buffers(new BufferSet()),
219 _mmc_port (default_mmc_port),
220 _mtc_port (default_mtc_port),
221 _midi_port (default_midi_port),
222 _midi_clock_port (default_midi_clock_port),
223 _session_dir ( new SessionDirectory(fullpath)),
225 _butler (new Butler (*this)),
226 _post_transport_work (0),
227 _send_timecode_update (false),
228 diskstreams (new DiskstreamList),
229 routes (new RouteList),
230 _total_free_4k_blocks (0),
231 _bundles (new BundleList),
232 _bundle_xml_node (0),
233 _click_io ((IO *) 0),
235 click_emphasis_data (0),
237 _metadata (new SessionMetadata()),
238 _have_rec_enabled_diskstream (false)
240 playlists.reset (new SessionPlaylists);
244 interpolation.add_channel_to (0, 0);
246 if (!eng.connected()) {
247 throw failed_constructor();
250 info << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
252 n_physical_outputs = _engine.n_physical_outputs (DataType::AUDIO);
253 n_physical_inputs = _engine.n_physical_inputs (DataType::AUDIO);
255 if (n_physical_inputs) {
256 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
259 if (n_physical_outputs) {
260 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
263 first_stage_init (fullpath, snapshot_name);
265 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
268 if (create (new_session, string(), initial_length)) {
270 throw failed_constructor ();
275 /* set up Master Out and Control Out if necessary */
280 if (master_out_channels) {
281 ChanCount count(DataType::AUDIO, master_out_channels);
282 Route* rt = new Route (*this, _("master"), Route::MasterOut, DataType::AUDIO);
283 boost_debug_shared_ptr_mark_interesting (rt, typeid (rt).name());
284 shared_ptr<Route> r (rt);
285 r->input()->ensure_io (count, false, this);
286 r->output()->ensure_io (count, false, this);
287 r->set_remote_control_id (control_id);
291 /* prohibit auto-connect to master, because there isn't one */
292 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
295 if (control_out_channels) {
296 ChanCount count(DataType::AUDIO, control_out_channels);
297 Route* rt = new Route (*this, _("monitor"), Route::ControlOut, DataType::AUDIO);
298 boost_debug_shared_ptr_mark_interesting (rt, typeid (rt).name());
299 shared_ptr<Route> r (rt);
300 r->input()->ensure_io (count, false, this);
301 r->output()->ensure_io (count, false, this);
302 r->set_remote_control_id (control_id++);
308 add_routes (rl, false);
313 if (no_auto_connect()) {
314 input_ac = AutoConnectOption (0);
315 output_ac = AutoConnectOption (0);
318 Config->set_input_auto_connect (input_ac);
319 Config->set_output_auto_connect (output_ac);
321 if (second_stage_init (new_session)) {
323 throw failed_constructor ();
326 store_recent_sessions (_name, _path);
328 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
330 Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
341 vector<void*> debug_pointers;
343 /* if we got to here, leaving pending capture state around
347 remove_pending_capture_state ();
349 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
351 _engine.remove_session ();
353 /* clear history so that no references to objects are held any more */
357 /* clear state tree so that no references to objects are held any more */
361 /* reset dynamic state version back to default */
363 Stateful::loading_state_version = 0;
365 _butler->terminate_thread ();
367 delete midi_control_ui;
369 if (click_data != default_click) {
370 delete [] click_data;
373 if (click_emphasis_data != default_click_emphasis) {
374 delete [] click_emphasis_data;
379 delete _scratch_buffers;
380 delete _silent_buffers;
383 /* clear out any pending dead wood from RCU managed objects */
386 diskstreams.flush ();
389 AudioDiskstream::free_working_buffers();
391 /* tell everyone who is still standing that we're about to die */
394 /* tell everyone to drop references and delete objects as we go */
396 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
397 named_selections.clear ();
399 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
400 for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
401 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for region %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
402 i->second->drop_references ();
406 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
408 /* reset these three references to special routes before we do the usual route delete thing */
411 _master_out.reset ();
412 _control_out.reset ();
415 RCUWriter<RouteList> writer (routes);
416 boost::shared_ptr<RouteList> r = writer.get_copy ();
418 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
419 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
420 (*i)->drop_references ();
424 /* writer goes out of scope and updates master */
428 DEBUG_TRACE (DEBUG::Destruction, "delete diskstreams\n");
430 RCUWriter<DiskstreamList> dwriter (diskstreams);
431 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
432 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
433 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for diskstream %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
434 (*i)->drop_references ();
439 diskstreams.flush ();
441 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
442 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
443 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
444 i->second->drop_references ();
449 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
450 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
455 Crossfade::set_buffer_size (0);
459 /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
462 boost_debug_list_ptrs ();
464 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
468 Session::set_worst_io_latencies ()
470 _worst_output_latency = 0;
471 _worst_input_latency = 0;
473 if (!_engine.connected()) {
477 boost::shared_ptr<RouteList> r = routes.reader ();
479 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
480 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
481 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
486 Session::when_engine_running ()
488 string first_physical_output;
490 BootMessage (_("Set block size and sample rate"));
492 set_block_size (_engine.frames_per_cycle());
493 set_frame_rate (_engine.frame_rate());
495 BootMessage (_("Using configuration"));
497 boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
498 boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
500 Config->map_parameters (ff);
501 config.map_parameters (ft);
503 /* every time we reconnect, recompute worst case output latencies */
505 _engine.Running.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies, this));
507 if (synced_to_jack()) {
508 _engine.transport_stop ();
511 if (config.get_jack_time_master()) {
512 _engine.transport_locate (_transport_frame);
520 _click_io.reset (new ClickIO (*this, "click"));
522 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
524 /* existing state for Click */
527 if (Stateful::loading_state_version < 3000) {
528 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
530 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
535 _clicking = Config->get_clicking ();
539 error << _("could not setup Click I/O") << endmsg;
546 /* default state for Click: dual-mono to first 2 physical outputs */
548 for (int physport = 0; physport < 2; ++physport) {
549 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
551 if (physical_output.length()) {
552 if (_click_io->add_port (physical_output, this)) {
553 // relax, even though its an error
558 if (_click_io->n_ports () > ChanCount::ZERO) {
559 _clicking = Config->get_clicking ();
564 catch (failed_constructor& err) {
565 error << _("cannot setup Click I/O") << endmsg;
568 BootMessage (_("Compute I/O Latencies"));
570 set_worst_io_latencies ();
573 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
576 BootMessage (_("Set up standard connections"));
578 /* Create a set of Bundle objects that map
579 to the physical I/O currently available. We create both
580 mono and stereo bundles, so that the common cases of mono
581 and stereo tracks get bundles to put in their mixer strip
582 in / out menus. There may be a nicer way of achieving that;
583 it doesn't really scale that well to higher channel counts
586 /* mono output bundles */
588 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
590 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
592 shared_ptr<Bundle> c (new Bundle (buf, true));
593 c->add_channel (_("mono"));
594 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
599 /* stereo output bundles */
601 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
602 if (np + 1 < n_physical_outputs) {
604 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
605 shared_ptr<Bundle> c (new Bundle (buf, true));
606 c->add_channel (_("L"));
607 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
608 c->add_channel (_("R"));
609 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
615 /* mono input bundles */
617 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
619 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
621 shared_ptr<Bundle> c (new Bundle (buf, false));
622 c->add_channel (_("mono"));
623 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
628 /* stereo input bundles */
630 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
631 if (np + 1 < n_physical_inputs) {
633 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
635 shared_ptr<Bundle> c (new Bundle (buf, false));
636 c->add_channel (_("L"));
637 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
638 c->add_channel (_("R"));
639 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
645 BootMessage (_("Setup signal flow and plugins"));
649 if (!no_auto_connect()) {
651 if (_master_out && Config->get_auto_connect_standard_busses()) {
653 /* if requested auto-connect the outputs to the first N physical ports.
656 uint32_t limit = _master_out->n_outputs().n_total();
658 for (uint32_t n = 0; n < limit; ++n) {
659 Port* p = _master_out->output()->nth (n);
660 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
662 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
663 if (_master_out->output()->connect (p, connect_to, this)) {
664 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
674 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
675 are undefined, at best.
678 /* control out listens to master bus (but ignores it
679 under some conditions)
682 uint32_t limit = _control_out->n_inputs().n_audio();
685 for (uint32_t n = 0; n < limit; ++n) {
686 AudioPort* p = _control_out->input()->ports().nth_audio_port (n);
687 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
690 string connect_to = o->name();
691 if (_control_out->input()->connect (p, connect_to, this)) {
692 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
700 /* if control out is not connected,
701 connect control out to physical outs, but use ones after the master if possible
704 if (!_control_out->output()->connected_to (boost::shared_ptr<IO>())) {
706 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
708 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
711 _control_out->output()->connect_ports_to_bundle (b, this);
713 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
714 Config->get_monitor_bus_preferred_bundle())
720 /* XXX this logic is wrong for mixed port types */
722 uint32_t shift = _master_out->n_outputs().n_audio();
723 uint32_t mod = _engine.n_physical_outputs (DataType::AUDIO);
724 limit = _control_out->n_outputs().n_audio();
726 cerr << "Connecting " << limit << " control out ports, shift is " << shift << " mod is " << mod << endl;
728 for (uint32_t n = 0; n < limit; ++n) {
730 Port* p = _control_out->output()->nth (n);
731 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), (n+shift) % mod);
733 if (!connect_to.empty()) {
734 if (_control_out->output()->connect (p, connect_to, this)) {
735 error << string_compose (_("cannot connect control output %1 to %2"), n, connect_to)
746 /* catch up on send+insert cnts */
748 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
750 /* hook us up to the engine */
752 BootMessage (_("Connect to engine"));
754 _engine.set_session (this);
758 Session::hookup_io ()
760 /* stop graph reordering notifications from
761 causing resorts, etc.
764 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
769 /* we delay creating the auditioner till now because
770 it makes its own connections to ports.
771 the engine has to be running for this to work.
775 auditioner.reset (new Auditioner (*this));
778 catch (failed_constructor& err) {
779 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
783 /* load bundles, which we may have postponed earlier on */
784 if (_bundle_xml_node) {
785 load_bundles (*_bundle_xml_node);
786 delete _bundle_xml_node;
789 /* Tell all IO objects to connect themselves together */
791 IO::enable_connecting ();
793 /* Now reset all panners */
795 Delivery::reset_panners ();
797 /* Connect tracks to listen/solo etc. busses XXX generalize this beyond control_out */
801 boost::shared_ptr<RouteList> r = routes.reader ();
803 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
805 if ((*x)->is_control() || (*x)->is_master()) {
809 (*x)->listen_via (_control_out,
810 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
815 /* Anyone who cares about input state, wake up and do something */
817 IOConnectionsComplete (); /* EMIT SIGNAL */
819 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
821 /* now handle the whole enchilada as if it was one
827 /* update the full solo state, which can't be
828 correctly determined on a per-route basis, but
829 needs the global overview that only the session
833 update_route_solo_state ();
837 Session::playlist_length_changed ()
839 /* we can't just increase end_location->end() if pl->get_maximum_extent()
840 if larger. if the playlist used to be the longest playlist,
841 and its now shorter, we have to decrease end_location->end(). hence,
842 we have to iterate over all diskstreams and check the
843 playlists currently in use.
849 Session::diskstream_playlist_changed (boost::weak_ptr<Diskstream> wp)
851 boost::shared_ptr<Diskstream> dstream = wp.lock ();
856 boost::shared_ptr<Playlist> playlist;
858 if ((playlist = dstream->playlist()) != 0) {
859 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
862 /* see comment in playlist_length_changed () */
867 Session::record_enabling_legal () const
869 /* this used to be in here, but survey says.... we don't need to restrict it */
870 // if (record_status() == Recording) {
874 if (Config->get_all_safe()) {
881 Session::reset_input_monitor_state ()
883 if (transport_rolling()) {
885 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
887 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
888 if ((*i)->record_enabled ()) {
889 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
890 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
894 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
896 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
897 if ((*i)->record_enabled ()) {
898 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
899 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
906 Session::auto_punch_start_changed (Location* location)
908 replace_event (SessionEvent::PunchIn, location->start());
910 if (get_record_enabled() && config.get_punch_in()) {
911 /* capture start has been changed, so save new pending state */
912 save_state ("", true);
917 Session::auto_punch_end_changed (Location* location)
919 nframes_t when_to_stop = location->end();
920 // when_to_stop += _worst_output_latency + _worst_input_latency;
921 replace_event (SessionEvent::PunchOut, when_to_stop);
925 Session::auto_punch_changed (Location* location)
927 nframes_t when_to_stop = location->end();
929 replace_event (SessionEvent::PunchIn, location->start());
930 //when_to_stop += _worst_output_latency + _worst_input_latency;
931 replace_event (SessionEvent::PunchOut, when_to_stop);
935 Session::auto_loop_changed (Location* location)
937 replace_event (SessionEvent::AutoLoop, location->end(), location->start());
939 if (transport_rolling() && play_loop) {
942 // if (_transport_frame > location->end()) {
944 if (_transport_frame < location->start() || _transport_frame > location->end()) {
945 // relocate to beginning of loop
946 clear_events (SessionEvent::LocateRoll);
948 request_locate (location->start(), true);
951 else if (Config->get_seamless_loop() && !loop_changing) {
953 // schedule a locate-roll to refill the diskstreams at the
955 loop_changing = true;
957 if (location->end() > last_loopend) {
958 clear_events (SessionEvent::LocateRoll);
959 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
966 last_loopend = location->end();
970 Session::set_auto_punch_location (Location* location)
974 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
975 punch_connections.drop_connections();
976 existing->set_auto_punch (false, this);
977 remove_event (existing->start(), SessionEvent::PunchIn);
978 clear_events (SessionEvent::PunchOut);
979 auto_punch_location_changed (0);
988 if (location->end() <= location->start()) {
989 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
993 punch_connections.drop_connections ();
995 location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
996 location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
997 location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
999 location->set_auto_punch (true, this);
1001 auto_punch_changed (location);
1003 auto_punch_location_changed (location);
1007 Session::set_auto_loop_location (Location* location)
1011 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1012 loop_connections.drop_connections ();
1013 existing->set_auto_loop (false, this);
1014 remove_event (existing->end(), SessionEvent::AutoLoop);
1015 auto_loop_location_changed (0);
1020 if (location == 0) {
1024 if (location->end() <= location->start()) {
1025 error << _("Session: you can't use a mark for auto loop") << endmsg;
1029 last_loopend = location->end();
1031 loop_connections.drop_connections ();
1033 location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1034 location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1035 location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1037 location->set_auto_loop (true, this);
1039 /* take care of our stuff first */
1041 auto_loop_changed (location);
1043 /* now tell everyone else */
1045 auto_loop_location_changed (location);
1049 Session::locations_added (Location *)
1055 Session::locations_changed ()
1057 _locations.apply (*this, &Session::handle_locations_changed);
1061 Session::handle_locations_changed (Locations::LocationList& locations)
1063 Locations::LocationList::iterator i;
1065 bool set_loop = false;
1066 bool set_punch = false;
1068 for (i = locations.begin(); i != locations.end(); ++i) {
1072 if (location->is_auto_punch()) {
1073 set_auto_punch_location (location);
1076 if (location->is_auto_loop()) {
1077 set_auto_loop_location (location);
1081 if (location->is_start()) {
1082 start_location = location;
1084 if (location->is_end()) {
1085 end_location = location;
1090 set_auto_loop_location (0);
1093 set_auto_punch_location (0);
1100 Session::enable_record ()
1102 /* XXX really atomic compare+swap here */
1103 if (g_atomic_int_get (&_record_status) != Recording) {
1104 g_atomic_int_set (&_record_status, Recording);
1105 _last_record_location = _transport_frame;
1106 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1108 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1109 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1110 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1111 if ((*i)->record_enabled ()) {
1112 (*i)->monitor_input (true);
1117 RecordStateChanged ();
1122 Session::disable_record (bool rt_context, bool force)
1126 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1128 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1129 g_atomic_int_set (&_record_status, Disabled);
1131 if (rs == Recording) {
1132 g_atomic_int_set (&_record_status, Enabled);
1136 // FIXME: timestamp correct? [DR]
1137 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1138 // does this /need/ to be sent in all cases?
1140 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1143 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1144 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1146 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1147 if ((*i)->record_enabled ()) {
1148 (*i)->monitor_input (false);
1153 RecordStateChanged (); /* emit signal */
1156 remove_pending_capture_state ();
1162 Session::step_back_from_record ()
1164 /* XXX really atomic compare+swap here */
1165 if (g_atomic_int_get (&_record_status) == Recording) {
1166 g_atomic_int_set (&_record_status, Enabled);
1168 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1169 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1171 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1172 if ((*i)->record_enabled ()) {
1173 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1174 (*i)->monitor_input (false);
1182 Session::maybe_enable_record ()
1184 g_atomic_int_set (&_record_status, Enabled);
1186 /* this function is currently called from somewhere other than an RT thread.
1187 this save_state() call therefore doesn't impact anything.
1190 save_state ("", true);
1192 if (_transport_speed) {
1193 if (!config.get_punch_in()) {
1197 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1198 RecordStateChanged (); /* EMIT SIGNAL */
1205 Session::audible_frame () const
1211 /* the first of these two possible settings for "offset"
1212 mean that the audible frame is stationary until
1213 audio emerges from the latency compensation
1216 the second means that the audible frame is stationary
1217 until audio would emerge from a physical port
1218 in the absence of any plugin latency compensation
1221 offset = _worst_output_latency;
1223 if (offset > current_block_size) {
1224 offset -= current_block_size;
1226 /* XXX is this correct? if we have no external
1227 physical connections and everything is internal
1228 then surely this is zero? still, how
1229 likely is that anyway?
1231 offset = current_block_size;
1234 if (synced_to_jack()) {
1235 tf = _engine.transport_frame();
1237 tf = _transport_frame;
1242 if (!non_realtime_work_pending()) {
1246 /* check to see if we have passed the first guaranteed
1247 audible frame past our last start position. if not,
1248 return that last start point because in terms
1249 of audible frames, we have not moved yet.
1252 if (_transport_speed > 0.0f) {
1254 if (!play_loop || !have_looped) {
1255 if (tf < _last_roll_location + offset) {
1256 return _last_roll_location;
1264 } else if (_transport_speed < 0.0f) {
1266 /* XXX wot? no backward looping? */
1268 if (tf > _last_roll_location - offset) {
1269 return _last_roll_location;
1281 Session::set_frame_rate (nframes_t frames_per_second)
1283 /** \fn void Session::set_frame_size(nframes_t)
1284 the AudioEngine object that calls this guarantees
1285 that it will not be called while we are also in
1286 ::process(). Its fine to do things that block
1290 _base_frame_rate = frames_per_second;
1294 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1298 // XXX we need some equivalent to this, somehow
1299 // SndFileSource::setup_standard_crossfades (frames_per_second);
1303 /* XXX need to reset/reinstantiate all LADSPA plugins */
1307 Session::set_block_size (nframes_t nframes)
1309 /* the AudioEngine guarantees
1310 that it will not be called while we are also in
1311 ::process(). It is therefore fine to do things that block
1316 current_block_size = nframes;
1318 ensure_buffers(_scratch_buffers->available());
1320 delete [] _gain_automation_buffer;
1321 _gain_automation_buffer = new gain_t[nframes];
1323 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1325 boost::shared_ptr<RouteList> r = routes.reader ();
1327 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1328 (*i)->set_block_size (nframes);
1331 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1332 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1333 (*i)->set_block_size (nframes);
1336 set_worst_io_latencies ();
1341 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1344 nframes_t fade_frames;
1346 /* Don't allow fade of less 1 frame */
1348 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1355 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1359 default_fade_msecs = fade_msecs;
1360 default_fade_steepness = steepness;
1363 // jlc, WTF is this!
1364 Glib::RWLock::ReaderLock lm (route_lock);
1365 AudioRegion::set_default_fade (steepness, fade_frames);
1370 /* XXX have to do this at some point */
1371 /* foreach region using default fade, reset, then
1372 refill_all_diskstream_buffers ();
1377 struct RouteSorter {
1378 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1379 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1381 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1384 if (r1->fed_by.empty()) {
1385 if (r2->fed_by.empty()) {
1386 /* no ardour-based connections inbound to either route. just use signal order */
1387 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1389 /* r2 has connections, r1 does not; run r1 early */
1393 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1400 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1402 shared_ptr<Route> r2;
1404 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1405 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1409 /* make a copy of the existing list of routes that feed r1 */
1411 set<weak_ptr<Route> > existing = r1->fed_by;
1413 /* for each route that feeds r1, recurse, marking it as feeding
1417 for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1418 if (!(r2 = (*i).lock ())) {
1419 /* (*i) went away, ignore it */
1423 /* r2 is a route that feeds r1 which somehow feeds base. mark
1424 base as being fed by r2
1427 rbase->fed_by.insert (r2);
1431 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1435 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1439 /* now recurse, so that we can mark base as being fed by
1440 all routes that feed r2
1443 trace_terminal (r2, rbase);
1450 Session::resort_routes ()
1452 /* don't do anything here with signals emitted
1453 by Routes while we are being destroyed.
1456 if (_state_of_the_state & Deletion) {
1463 RCUWriter<RouteList> writer (routes);
1464 shared_ptr<RouteList> r = writer.get_copy ();
1465 resort_routes_using (r);
1466 /* writer goes out of scope and forces update */
1471 Session::resort_routes_using (shared_ptr<RouteList> r)
1473 RouteList::iterator i, j;
1475 for (i = r->begin(); i != r->end(); ++i) {
1477 (*i)->fed_by.clear ();
1479 for (j = r->begin(); j != r->end(); ++j) {
1481 /* although routes can feed themselves, it will
1482 cause an endless recursive descent if we
1483 detect it. so don't bother checking for
1491 if ((*j)->feeds (*i)) {
1492 (*i)->fed_by.insert (*j);
1497 for (i = r->begin(); i != r->end(); ++i) {
1498 trace_terminal (*i, *i);
1505 cerr << "finished route resort\n";
1507 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1508 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1515 list<boost::shared_ptr<MidiTrack> >
1516 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1518 char track_name[32];
1519 uint32_t track_id = 0;
1522 RouteList new_routes;
1523 list<boost::shared_ptr<MidiTrack> > ret;
1524 //uint32_t control_id;
1526 // FIXME: need physical I/O and autoconnect stuff for MIDI
1528 /* count existing midi tracks */
1531 shared_ptr<RouteList> r = routes.reader ();
1533 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1534 if (boost::dynamic_pointer_cast<MidiTrack>(*i) != 0) {
1535 if (!(*i)->is_hidden()) {
1537 //channels_used += (*i)->n_inputs().n_midi();
1543 vector<string> physinputs;
1544 vector<string> physoutputs;
1546 _engine.get_physical_outputs (DataType::MIDI, physoutputs);
1547 _engine.get_physical_inputs (DataType::MIDI, physinputs);
1549 // control_id = ntracks() + nbusses();
1553 /* check for duplicate route names, since we might have pre-existing
1554 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1555 save, close,restart,add new route - first named route is now
1563 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1565 if (route_by_name (track_name) == 0) {
1569 } while (track_id < (UINT_MAX-1));
1571 shared_ptr<MidiTrack> track;
1574 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1576 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1577 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1582 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1583 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1589 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1593 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1594 port = physinputs[(channels_used+x)%nphysical_in];
1597 if (port.length() && track->connect_input (track->input (x), port, this)) {
1603 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1607 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1608 port = physoutputs[(channels_used+x)%nphysical_out];
1609 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1611 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1615 if (port.length() && track->connect_output (track->output (x), port, this)) {
1620 channels_used += track->n_inputs ().n_midi();
1624 track->midi_diskstream()->non_realtime_input_change();
1626 route_group->add (track);
1629 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1630 //track->set_remote_control_id (control_id);
1632 new_routes.push_back (track);
1633 ret.push_back (track);
1636 catch (failed_constructor &err) {
1637 error << _("Session: could not create new midi track.") << endmsg;
1640 /* we need to get rid of this, since the track failed to be created */
1641 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1644 RCUWriter<DiskstreamList> writer (diskstreams);
1645 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1646 ds->remove (track->midi_diskstream());
1653 catch (AudioEngine::PortRegistrationFailure& pfe) {
1655 error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
1658 /* we need to get rid of this, since the track failed to be created */
1659 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1662 RCUWriter<DiskstreamList> writer (diskstreams);
1663 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1664 ds->remove (track->midi_diskstream());
1675 if (!new_routes.empty()) {
1676 add_routes (new_routes, false);
1677 save_state (_current_snapshot_name);
1683 list<boost::shared_ptr<AudioTrack> >
1684 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1686 char track_name[32];
1687 uint32_t track_id = 0;
1689 uint32_t channels_used = 0;
1691 RouteList new_routes;
1692 list<boost::shared_ptr<AudioTrack> > ret;
1693 uint32_t control_id;
1695 /* count existing audio tracks */
1698 shared_ptr<RouteList> r = routes.reader ();
1700 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1701 if (boost::dynamic_pointer_cast<AudioTrack>(*i) != 0) {
1702 if (!(*i)->is_hidden()) {
1704 channels_used += (*i)->n_inputs().n_audio();
1710 vector<string> physinputs;
1711 vector<string> physoutputs;
1713 _engine.get_physical_outputs (DataType::AUDIO, physoutputs);
1714 _engine.get_physical_inputs (DataType::AUDIO, physinputs);
1716 control_id = ntracks() + nbusses() + 1;
1720 /* check for duplicate route names, since we might have pre-existing
1721 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1722 save, close,restart,add new route - first named route is now
1730 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1732 if (route_by_name (track_name) == 0) {
1736 } while (track_id < (UINT_MAX-1));
1738 shared_ptr<AudioTrack> track;
1741 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1742 boost_debug_shared_ptr_mark_interesting (at, typeid (at).name());
1743 track = boost::shared_ptr<AudioTrack>(at);
1745 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1746 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1747 input_channels, output_channels)
1752 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1753 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1754 input_channels, output_channels)
1759 if (!physinputs.empty()) {
1760 uint32_t nphysical_in = physinputs.size();
1762 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1766 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1767 port = physinputs[(channels_used+x)%nphysical_in];
1770 if (port.length() && track->input()->connect (track->input()->nth(x), port, this)) {
1776 if (!physoutputs.empty()) {
1777 uint32_t nphysical_out = physoutputs.size();
1779 for (uint32_t x = 0; x < track->n_outputs().n_audio(); ++x) {
1782 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1783 port = physoutputs[(channels_used+x)%nphysical_out];
1784 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1785 if (_master_out && _master_out->n_inputs().n_audio() > 0) {
1786 port = _master_out->input()->nth (x % _master_out->input()->n_ports().n_audio())->name();
1790 if (port.length() && track->output()->connect (track->output()->nth(x), port, this)) {
1796 channels_used += track->n_inputs ().n_audio();
1799 route_group->add (track);
1802 track->audio_diskstream()->non_realtime_input_change();
1804 track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1805 track->set_remote_control_id (control_id);
1808 new_routes.push_back (track);
1809 ret.push_back (track);
1812 catch (failed_constructor &err) {
1813 error << _("Session: could not create new audio track.") << endmsg;
1816 /* we need to get rid of this, since the track failed to be created */
1817 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1820 RCUWriter<DiskstreamList> writer (diskstreams);
1821 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1822 ds->remove (track->audio_diskstream());
1829 catch (AudioEngine::PortRegistrationFailure& pfe) {
1831 error << pfe.what() << endmsg;
1834 /* we need to get rid of this, since the track failed to be created */
1835 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1838 RCUWriter<DiskstreamList> writer (diskstreams);
1839 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1840 ds->remove (track->audio_diskstream());
1851 if (!new_routes.empty()) {
1852 add_routes (new_routes, true);
1859 Session::set_remote_control_ids ()
1861 RemoteModel m = Config->get_remote_model();
1863 shared_ptr<RouteList> r = routes.reader ();
1865 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1866 if ( MixerOrdered == m) {
1867 long order = (*i)->order_key(N_("signal"));
1868 (*i)->set_remote_control_id( order+1 );
1869 } else if ( EditorOrdered == m) {
1870 long order = (*i)->order_key(N_("editor"));
1871 (*i)->set_remote_control_id( order+1 );
1872 } else if ( UserOrdered == m) {
1873 //do nothing ... only changes to remote id's are initiated by user
1880 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1883 uint32_t bus_id = 1;
1885 uint32_t channels_used = 0;
1888 uint32_t control_id;
1890 /* count existing audio busses */
1893 shared_ptr<RouteList> r = routes.reader ();
1895 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1896 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
1898 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1901 channels_used += (*i)->n_inputs().n_audio();
1907 vector<string> physinputs;
1908 vector<string> physoutputs;
1910 _engine.get_physical_outputs (DataType::AUDIO, physoutputs);
1911 _engine.get_physical_inputs (DataType::AUDIO, physinputs);
1913 n_physical_audio_outputs = physoutputs.size();
1914 n_physical_audio_inputs = physinputs.size();
1916 control_id = ntracks() + nbusses() + 1;
1921 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1925 if (route_by_name (bus_name) == 0) {
1929 } while (bus_id < (UINT_MAX-1));
1932 Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1933 boost_debug_shared_ptr_mark_interesting (rt, typeid (rt).name());
1934 shared_ptr<Route> bus (rt);
1936 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1937 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1938 input_channels, output_channels)
1944 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1945 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1946 input_channels, output_channels)
1951 for (uint32_t x = 0; n_physical_audio_inputs && x < bus->input()->n_ports().n_audio(); ++x) {
1954 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1955 port = physinputs[((n+x)%n_physical_audio_inputs)];
1958 if (port.length() && bus->input()->connect (bus->input()->nth (x), port, this)) {
1963 for (uint32_t x = 0; n_physical_audio_outputs && x < bus->n_outputs().n_audio(); ++x) {
1966 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1967 port = physoutputs[((n+x)%n_physical_outputs)];
1968 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1970 port = _master_out->input()->nth (x%_master_out->input()->n_ports().n_audio())->name();
1974 if (port.length() && bus->output()->connect (bus->output()->nth(x), port, this)) {
1979 channels_used += bus->n_inputs ().n_audio();
1982 route_group->add (bus);
1984 bus->set_remote_control_id (control_id);
1988 bus->add_internal_return ();
1991 ret.push_back (bus);
1995 catch (failed_constructor &err) {
1996 error << _("Session: could not create new audio route.") << endmsg;
2000 catch (AudioEngine::PortRegistrationFailure& pfe) {
2001 error << pfe.what() << endmsg;
2011 add_routes (ret, true);
2019 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
2023 uint32_t control_id;
2025 uint32_t number = 1;
2027 if (!tree.read (template_path.c_str())) {
2031 XMLNode* node = tree.root();
2033 control_id = ntracks() + nbusses() + 1;
2037 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
2039 std::string node_name = IO::name_from_state (*node_copy.children().front());
2041 /* generate a new name by adding a number to the end of the template name */
2044 snprintf (name, sizeof (name), "%s %" PRIu32, node_name.c_str(), number);
2048 if (route_by_name (name) == 0) {
2052 } while (number < UINT_MAX);
2054 if (number == UINT_MAX) {
2055 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2059 IO::set_name_in_state (*node_copy.children().front(), name);
2061 Track::zero_diskstream_id_in_xml (node_copy);
2064 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2067 error << _("Session: cannot create track/bus from template description") << endmsg;
2071 if (boost::dynamic_pointer_cast<Track>(route)) {
2072 /* force input/output change signals so that the new diskstream
2073 picks up the configuration of the route. During session
2074 loading this normally happens in a different way.
2076 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
2077 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
2080 route->set_remote_control_id (control_id);
2083 ret.push_back (route);
2086 catch (failed_constructor &err) {
2087 error << _("Session: could not create new route from template") << endmsg;
2091 catch (AudioEngine::PortRegistrationFailure& pfe) {
2092 error << pfe.what() << endmsg;
2101 add_routes (ret, true);
2108 Session::add_routes (RouteList& new_routes, bool save)
2111 RCUWriter<RouteList> writer (routes);
2112 shared_ptr<RouteList> r = writer.get_copy ();
2113 r->insert (r->end(), new_routes.begin(), new_routes.end());
2116 /* if there is no control out and we're not in the middle of loading,
2117 resort the graph here. if there is a control out, we will resort
2118 toward the end of this method. if we are in the middle of loading,
2119 we will resort when done.
2122 if (!_control_out && IO::connecting_legal) {
2123 resort_routes_using (r);
2127 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2129 boost::weak_ptr<Route> wpr (*x);
2131 (*x)->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2132 (*x)->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, wpr));
2133 (*x)->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2134 (*x)->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2135 (*x)->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2136 (*x)->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
2138 if ((*x)->is_master()) {
2142 if ((*x)->is_control()) {
2143 _control_out = (*x);
2147 if (_control_out && IO::connecting_legal) {
2149 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2150 if ((*x)->is_control() || (*x)->is_master()) {
2153 (*x)->listen_via (_control_out,
2154 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
2164 save_state (_current_snapshot_name);
2167 RouteAdded (new_routes); /* EMIT SIGNAL */
2171 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2173 boost::shared_ptr<RouteList> r = routes.reader ();
2174 boost::shared_ptr<Send> s;
2178 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2179 if (boost::dynamic_pointer_cast<Track>(*i)) {
2180 if ((s = (*i)->internal_send_for (dest)) != 0) {
2181 s->amp()->gain_control()->set_value (0.0);
2188 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2190 boost::shared_ptr<RouteList> r = routes.reader ();
2191 boost::shared_ptr<Send> s;
2195 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2196 if (boost::dynamic_pointer_cast<Track>(*i)) {
2197 if ((s = (*i)->internal_send_for (dest)) != 0) {
2198 s->amp()->gain_control()->set_value (1.0);
2205 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2207 boost::shared_ptr<RouteList> r = routes.reader ();
2208 boost::shared_ptr<Send> s;
2212 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2213 if (boost::dynamic_pointer_cast<Track>(*i)) {
2214 if ((s = (*i)->internal_send_for (dest)) != 0) {
2215 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2222 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2224 boost::shared_ptr<RouteList> r = routes.reader ();
2225 boost::shared_ptr<RouteList> t (new RouteList);
2227 /* only send tracks */
2229 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2230 if (boost::dynamic_pointer_cast<Track>(*i)) {
2235 add_internal_sends (dest, p, t);
2239 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2241 if (dest->is_control() || dest->is_master()) {
2245 if (!dest->internal_return()) {
2246 dest->add_internal_return();
2249 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2251 if ((*i)->is_control() || (*i)->is_master() || (*i) == dest) {
2255 (*i)->listen_via (dest, p, true, true);
2262 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2264 /* need to do this in case we're rolling at the time, to prevent false underruns */
2265 dstream->do_refill_with_alloc ();
2267 dstream->set_block_size (current_block_size);
2270 RCUWriter<DiskstreamList> writer (diskstreams);
2271 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2272 ds->push_back (dstream);
2273 /* writer goes out of scope, copies ds back to main */
2276 dstream->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::diskstream_playlist_changed, this, boost::weak_ptr<Diskstream> (dstream)));
2277 /* this will connect to future changes, and check the current length */
2278 diskstream_playlist_changed (boost::weak_ptr<Diskstream> (dstream));
2280 dstream->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_diskstream, this));
2282 dstream->prepare ();
2287 Session::remove_route (shared_ptr<Route> route)
2290 RCUWriter<RouteList> writer (routes);
2291 shared_ptr<RouteList> rs = writer.get_copy ();
2295 /* deleting the master out seems like a dumb
2296 idea, but its more of a UI policy issue
2300 if (route == _master_out) {
2301 _master_out = shared_ptr<Route> ();
2304 if (route == _control_out) {
2306 /* cancel control outs for all routes */
2308 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2309 (*r)->drop_listen (_control_out);
2312 _control_out.reset ();
2315 update_route_solo_state ();
2317 /* writer goes out of scope, forces route list update */
2320 boost::shared_ptr<Track> t;
2321 boost::shared_ptr<Diskstream> ds;
2323 if ((t = boost::dynamic_pointer_cast<Track>(route)) != 0) {
2324 ds = t->diskstream();
2330 RCUWriter<DiskstreamList> dsl (diskstreams);
2331 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2336 find_current_end ();
2338 // We need to disconnect the routes inputs and outputs
2340 route->input()->disconnect (0);
2341 route->output()->disconnect (0);
2343 /* if the route had internal sends sending to it, remove them */
2344 if (route->internal_return()) {
2346 boost::shared_ptr<RouteList> r = routes.reader ();
2347 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2348 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2350 (*i)->remove_processor (s);
2355 update_latency_compensation (false, false);
2358 /* get rid of it from the dead wood collection in the route list manager */
2360 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2364 /* try to cause everyone to drop their references */
2366 route->drop_references ();
2368 sync_order_keys (N_("session"));
2370 /* save the new state of the world */
2372 if (save_state (_current_snapshot_name)) {
2373 save_history (_current_snapshot_name);
2378 Session::route_mute_changed (void* /*src*/)
2384 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2386 boost::shared_ptr<Route> route = wpr.lock();
2388 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2392 if (route->listening()) {
2394 } else if (_listen_cnt > 0) {
2400 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2402 if (solo_update_disabled) {
2407 boost::shared_ptr<Route> route = wpr.lock ();
2410 /* should not happen */
2411 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2415 shared_ptr<RouteList> r = routes.reader ();
2418 if (route->self_soloed()) {
2424 /* now mod the solo level of all other routes except master & control outs
2425 so that they will be silent if appropriate.
2428 solo_update_disabled = true;
2430 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2431 bool via_sends_only;
2434 if ((*i) == route || !(*i)->solo_isolated() || !(*i)->is_master() || !(*i)->is_control() || (*i)->is_hidden()) {
2436 } else if ((*i)->feeds (route, &via_sends_only)) {
2437 if (!via_sends_only) {
2438 (*i)->mod_solo_by_others (delta);
2443 /* make sure master is never muted by solo */
2445 if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2446 _master_out->mod_solo_by_others (1);
2449 /* ditto for control outs make sure master is never muted by solo */
2451 if (_control_out && route != _control_out && _control_out && _control_out->soloed_by_others() == 0) {
2452 _control_out->mod_solo_by_others (1);
2455 solo_update_disabled = false;
2456 update_route_solo_state (r);
2457 SoloChanged (); /* EMIT SIGNAL */
2462 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2464 /* now figure out if anything that matters is soloed */
2466 bool something_soloed = false;
2469 r = routes.reader();
2472 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2473 if (!(*i)->is_master() && !(*i)->is_control() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2474 something_soloed = true;
2479 if (something_soloed != _non_soloed_outs_muted) {
2480 _non_soloed_outs_muted = something_soloed;
2481 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2485 boost::shared_ptr<RouteList>
2486 Session::get_routes_with_internal_returns() const
2488 shared_ptr<RouteList> r = routes.reader ();
2489 boost::shared_ptr<RouteList> rl (new RouteList);
2491 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2492 if ((*i)->internal_return ()) {
2500 Session::route_by_name (string name)
2502 shared_ptr<RouteList> r = routes.reader ();
2504 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2505 if ((*i)->name() == name) {
2510 return shared_ptr<Route> ((Route*) 0);
2514 Session::route_by_id (PBD::ID id)
2516 shared_ptr<RouteList> r = routes.reader ();
2518 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2519 if ((*i)->id() == id) {
2524 return shared_ptr<Route> ((Route*) 0);
2528 Session::route_by_remote_id (uint32_t id)
2530 shared_ptr<RouteList> r = routes.reader ();
2532 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2533 if ((*i)->remote_control_id() == id) {
2538 return shared_ptr<Route> ((Route*) 0);
2542 Session::find_current_end ()
2544 if (_state_of_the_state & Loading) {
2548 nframes_t max = get_maximum_extent ();
2550 if (max > end_location->end()) {
2551 end_location->set_end (max);
2553 DurationChanged(); /* EMIT SIGNAL */
2558 Session::get_maximum_extent () const
2563 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2565 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2566 if ((*i)->destructive()) //ignore tape tracks when getting max extents
2568 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2569 if ((me = pl->get_maximum_extent()) > max) {
2577 boost::shared_ptr<Diskstream>
2578 Session::diskstream_by_name (string name)
2580 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2582 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2583 if ((*i)->name() == name) {
2588 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2591 boost::shared_ptr<Diskstream>
2592 Session::diskstream_by_id (const PBD::ID& id)
2594 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2596 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2597 if ((*i)->id() == id) {
2602 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2605 /* Region management */
2608 Session::new_region_name (string old)
2610 string::size_type last_period;
2612 string::size_type len = old.length() + 64;
2615 if ((last_period = old.find_last_of ('.')) == string::npos) {
2617 /* no period present - add one explicitly */
2620 last_period = old.length() - 1;
2625 number = atoi (old.substr (last_period+1).c_str());
2629 while (number < (UINT_MAX-1)) {
2631 RegionList::const_iterator i;
2636 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2639 for (i = regions.begin(); i != regions.end(); ++i) {
2640 if (i->second->name() == sbuf) {
2645 if (i == regions.end()) {
2650 if (number != (UINT_MAX-1)) {
2654 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2659 Session::region_name (string& result, string base, bool newlevel)
2664 if (base.find("/") != string::npos) {
2665 base = base.substr(base.find_last_of("/") + 1);
2670 Glib::Mutex::Lock lm (region_lock);
2672 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2681 string::size_type pos;
2683 pos = base.find_last_of ('.');
2685 /* pos may be npos, but then we just use entire base */
2687 subbase = base.substr (0, pos);
2692 Glib::Mutex::Lock lm (region_lock);
2694 map<string,uint32_t>::iterator x;
2698 if ((x = region_name_map.find (subbase)) == region_name_map.end()) {
2700 region_name_map[subbase] = 1;
2703 snprintf (buf, sizeof (buf), ".%d", x->second);
2714 Session::add_region (boost::shared_ptr<Region> region)
2716 vector<boost::shared_ptr<Region> > v;
2717 v.push_back (region);
2722 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2727 Glib::Mutex::Lock lm (region_lock);
2729 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2731 boost::shared_ptr<Region> region = *ii;
2735 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2739 RegionList::iterator x;
2741 for (x = regions.begin(); x != regions.end(); ++x) {
2743 if (region->region_list_equivalent (x->second)) {
2748 if (x == regions.end()) {
2750 pair<RegionList::key_type,RegionList::mapped_type> entry;
2752 entry.first = region->id();
2753 entry.second = region;
2755 pair<RegionList::iterator,bool> x = regions.insert (entry);
2767 /* mark dirty because something has changed even if we didn't
2768 add the region to the region list.
2775 vector<boost::weak_ptr<Region> > v;
2776 boost::shared_ptr<Region> first_r;
2778 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2780 boost::shared_ptr<Region> region = *ii;
2784 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2787 v.push_back (region);
2794 region->StateChanged.connect_same_thread (*this, boost::bind (&Session::region_changed, this, _1, boost::weak_ptr<Region>(region)));
2795 update_region_name_map (region);
2799 RegionsAdded (v); /* EMIT SIGNAL */
2805 Session::update_region_name_map (boost::shared_ptr<Region> region)
2807 string::size_type last_period = region->name().find_last_of ('.');
2809 if (last_period != string::npos && last_period < region->name().length() - 1) {
2811 string base = region->name().substr (0, last_period);
2812 string number = region->name().substr (last_period+1);
2813 map<string,uint32_t>::iterator x;
2815 /* note that if there is no number, we get zero from atoi,
2819 region_name_map[base] = atoi (number);
2824 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2826 boost::shared_ptr<Region> region (weak_region.lock ());
2832 if (what_changed & Region::HiddenChanged) {
2833 /* relay hidden changes */
2834 RegionHiddenChange (region);
2837 if (what_changed & NameChanged) {
2838 update_region_name_map (region);
2843 Session::remove_region (boost::weak_ptr<Region> weak_region)
2845 RegionList::iterator i;
2846 boost::shared_ptr<Region> region (weak_region.lock ());
2852 bool removed = false;
2855 Glib::Mutex::Lock lm (region_lock);
2857 if ((i = regions.find (region->id())) != regions.end()) {
2863 /* mark dirty because something has changed even if we didn't
2864 remove the region from the region list.
2870 RegionRemoved(region); /* EMIT SIGNAL */
2874 boost::shared_ptr<Region>
2875 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2877 RegionList::iterator i;
2878 boost::shared_ptr<Region> region;
2880 Glib::Mutex::Lock lm (region_lock);
2882 for (i = regions.begin(); i != regions.end(); ++i) {
2886 if (region->whole_file()) {
2888 if (child->source_equivalent (region)) {
2894 return boost::shared_ptr<Region> ();
2898 Session::destroy_region (boost::shared_ptr<Region> region)
2900 vector<boost::shared_ptr<Source> > srcs;
2903 if (region->playlist()) {
2904 region->playlist()->destroy_region (region);
2907 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2908 srcs.push_back (region->source (n));
2912 region->drop_references ();
2914 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2916 (*i)->mark_for_remove ();
2917 (*i)->drop_references ();
2919 cerr << "source was not used by any playlist\n";
2926 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2928 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2929 destroy_region (*i);
2935 Session::remove_last_capture ()
2937 list<boost::shared_ptr<Region> > r;
2939 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2941 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2942 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2945 r.insert (r.end(), l.begin(), l.end());
2950 destroy_regions (r);
2952 save_state (_current_snapshot_name);
2958 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2964 /* Source Management */
2967 Session::add_source (boost::shared_ptr<Source> source)
2969 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2970 pair<SourceMap::iterator,bool> result;
2972 entry.first = source->id();
2973 entry.second = source;
2976 Glib::Mutex::Lock lm (source_lock);
2977 result = sources.insert (entry);
2980 if (result.second) {
2984 boost::shared_ptr<AudioFileSource> afs;
2986 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2987 if (Config->get_auto_analyse_audio()) {
2988 Analyser::queue_source_for_analysis (source, false);
2994 Session::remove_source (boost::weak_ptr<Source> src)
2996 SourceMap::iterator i;
2997 boost::shared_ptr<Source> source = src.lock();
3004 Glib::Mutex::Lock lm (source_lock);
3006 if ((i = sources.find (source->id())) != sources.end()) {
3011 if (!_state_of_the_state & InCleanup) {
3013 /* save state so we don't end up with a session file
3014 referring to non-existent sources.
3017 save_state (_current_snapshot_name);
3021 boost::shared_ptr<Source>
3022 Session::source_by_id (const PBD::ID& id)
3024 Glib::Mutex::Lock lm (source_lock);
3025 SourceMap::iterator i;
3026 boost::shared_ptr<Source> source;
3028 if ((i = sources.find (id)) != sources.end()) {
3035 boost::shared_ptr<Source>
3036 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
3038 Glib::Mutex::Lock lm (source_lock);
3040 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3041 cerr << "comparing " << path << " with " << i->second->name() << endl;
3042 boost::shared_ptr<AudioFileSource> afs
3043 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3045 if (afs && afs->path() == path && chn == afs->channel()) {
3049 return boost::shared_ptr<Source>();
3054 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3057 string old_basename = PBD::basename_nosuffix (oldname);
3058 string new_legalized = legalize_for_path (newname);
3060 /* note: we know (or assume) the old path is already valid */
3064 /* destructive file sources have a name of the form:
3066 /path/to/Tnnnn-NAME(%[LR])?.wav
3068 the task here is to replace NAME with the new name.
3071 /* find last slash */
3075 string::size_type slash;
3076 string::size_type dash;
3078 if ((slash = path.find_last_of ('/')) == string::npos) {
3082 dir = path.substr (0, slash+1);
3084 /* '-' is not a legal character for the NAME part of the path */
3086 if ((dash = path.find_last_of ('-')) == string::npos) {
3090 prefix = path.substr (slash+1, dash-(slash+1));
3095 path += new_legalized;
3096 path += ".wav"; /* XXX gag me with a spoon */
3100 /* non-destructive file sources have a name of the form:
3102 /path/to/NAME-nnnnn(%[LR])?.ext
3104 the task here is to replace NAME with the new name.
3109 string::size_type slash;
3110 string::size_type dash;
3111 string::size_type postfix;
3113 /* find last slash */
3115 if ((slash = path.find_last_of ('/')) == string::npos) {
3119 dir = path.substr (0, slash+1);
3121 /* '-' is not a legal character for the NAME part of the path */
3123 if ((dash = path.find_last_of ('-')) == string::npos) {
3127 suffix = path.substr (dash+1);
3129 // Suffix is now everything after the dash. Now we need to eliminate
3130 // the nnnnn part, which is done by either finding a '%' or a '.'
3132 postfix = suffix.find_last_of ("%");
3133 if (postfix == string::npos) {
3134 postfix = suffix.find_last_of ('.');
3137 if (postfix != string::npos) {
3138 suffix = suffix.substr (postfix);
3140 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3144 const uint32_t limit = 10000;
3145 char buf[PATH_MAX+1];
3147 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3149 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3151 if (access (buf, F_OK) != 0) {
3159 error << "FATAL ERROR! Could not find a " << endl;
3167 /** Return the full path (in some session directory) for a new within-session source.
3168 * \a name must be a session-unique name that does not contain slashes
3169 * (e.g. as returned by new_*_source_name)
3172 Session::new_source_path_from_name (DataType type, const string& name)
3174 assert(name.find("/") == string::npos);
3176 SessionDirectory sdir(get_best_session_directory_for_new_source());
3179 if (type == DataType::AUDIO) {
3180 p = sdir.sound_path();
3181 } else if (type == DataType::MIDI) {
3182 p = sdir.midi_path();
3184 error << "Unknown source type, unable to create file path" << endmsg;
3189 return p.to_string();
3193 Session::peak_path (Glib::ustring base) const
3195 sys::path peakfile_path(_session_dir->peak_path());
3196 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
3197 return peakfile_path.to_string();
3200 /** Return a unique name based on \a base for a new internal audio source */
3202 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3206 char buf[PATH_MAX+1];
3207 const uint32_t limit = 10000;
3211 legalized = legalize_for_path (base);
3213 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3214 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3216 vector<space_and_path>::iterator i;
3217 uint32_t existing = 0;
3219 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3221 SessionDirectory sdir((*i).path);
3223 spath = sdir.sound_path().to_string();
3228 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3229 spath.c_str(), cnt, legalized.c_str());
3230 } else if (nchan == 2) {
3232 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
3233 spath.c_str(), cnt, legalized.c_str());
3235 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
3236 spath.c_str(), cnt, legalized.c_str());
3238 } else if (nchan < 26) {
3239 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
3240 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3242 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3243 spath.c_str(), cnt, legalized.c_str());
3252 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3253 } else if (nchan == 2) {
3255 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3257 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3259 } else if (nchan < 26) {
3260 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3262 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3266 if (sys::exists(buf)) {
3272 if (existing == 0) {
3277 error << string_compose(
3278 _("There are already %1 recordings for %2, which I consider too many."),
3279 limit, base) << endmsg;
3281 throw failed_constructor();
3285 return Glib::path_get_basename(buf);
3288 /** Create a new within-session audio source */
3289 boost::shared_ptr<AudioFileSource>
3290 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3292 const size_t n_chans = ds.n_channels().n_audio();
3293 const string name = new_audio_source_name (ds.name(), n_chans, chan, destructive);
3294 const string path = new_source_path_from_name(DataType::AUDIO, name);
3296 return boost::dynamic_pointer_cast<AudioFileSource> (
3297 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3300 /** Return a unique name based on \a base for a new internal MIDI source */
3302 Session::new_midi_source_name (const string& base)
3305 char buf[PATH_MAX+1];
3306 const uint32_t limit = 10000;
3310 legalized = legalize_for_path (base);
3312 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3313 for (cnt = 1; cnt <= limit; ++cnt) {
3315 vector<space_and_path>::iterator i;
3316 uint32_t existing = 0;
3318 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3320 SessionDirectory sdir((*i).path);
3322 sys::path p = sdir.midi_path();
3325 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
3327 if (sys::exists (buf)) {
3332 if (existing == 0) {
3337 error << string_compose(
3338 _("There are already %1 recordings for %2, which I consider too many."),
3339 limit, base) << endmsg;
3341 throw failed_constructor();
3345 return Glib::path_get_basename(buf);
3349 /** Create a new within-session MIDI source */
3350 boost::shared_ptr<MidiSource>
3351 Session::create_midi_source_for_session (MidiDiskstream& ds)
3353 const string name = new_midi_source_name (ds.name());
3354 const string path = new_source_path_from_name (DataType::MIDI, name);
3356 return boost::dynamic_pointer_cast<SMFSource> (
3357 SourceFactory::createWritable (
3358 DataType::MIDI, *this, path, false, frame_rate()));
3363 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3365 if (playlist->hidden()) {
3369 playlists->add (playlist);
3372 playlist->release();
3379 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3381 if (_state_of_the_state & Deletion) {
3385 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3391 playlists->remove (playlist);
3397 Session::set_audition (boost::shared_ptr<Region> r)
3399 pending_audition_region = r;
3400 add_post_transport_work (PostTransportAudition);
3401 _butler->schedule_transport_work ();
3405 Session::audition_playlist ()
3407 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3408 ev->region.reset ();
3413 Session::non_realtime_set_audition ()
3415 if (!pending_audition_region) {
3416 auditioner->audition_current_playlist ();
3418 auditioner->audition_region (pending_audition_region);
3419 pending_audition_region.reset ();
3421 AuditionActive (true); /* EMIT SIGNAL */
3425 Session::audition_region (boost::shared_ptr<Region> r)
3427 SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3433 Session::cancel_audition ()
3435 if (auditioner->active()) {
3436 auditioner->cancel_audition ();
3437 AuditionActive (false); /* EMIT SIGNAL */
3442 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3444 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3448 Session::remove_empty_sounds ()
3450 vector<string> audio_filenames;
3452 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3454 Glib::Mutex::Lock lm (source_lock);
3456 TapeFileMatcher tape_file_matcher;
3458 remove_if (audio_filenames.begin(), audio_filenames.end(),
3459 boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3461 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3463 sys::path audio_file_path (_session_dir->sound_path());
3465 audio_file_path /= *i;
3467 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3471 sys::remove (audio_file_path);
3472 const string peakfile = peak_path (audio_file_path.to_string());
3473 sys::remove (peakfile);
3475 catch (const sys::filesystem_error& err)
3477 error << err.what() << endmsg;
3484 Session::is_auditioning () const
3486 /* can be called before we have an auditioner object */
3488 return auditioner->active();
3495 Session::n_diskstreams () const
3499 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3501 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3502 if (!(*i)->hidden()) {
3510 Session::graph_reordered ()
3512 /* don't do this stuff if we are setting up connections
3513 from a set_state() call or creating new tracks. Ditto for deletion.
3516 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3520 /* every track/bus asked for this to be handled but it was deferred because
3521 we were connecting. do it now.
3524 request_input_change_handling ();
3528 /* force all diskstreams to update their capture offset values to
3529 reflect any changes in latencies within the graph.
3532 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3534 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3535 (*i)->set_capture_offset ();
3540 Session::add_processor (Processor* processor)
3542 /* Session does not own Processors (they belong to a Route) but we do want to track
3543 the arrival and departure of port inserts, sends and returns for naming
3546 processor->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_processor, this, processor));
3551 Session::remove_processor (Processor* processor)
3555 PortInsert* port_insert;
3557 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3558 insert_bitset[port_insert->bit_slot()] = false;
3559 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3560 send_bitset[send->bit_slot()] = false;
3561 } else if ((retrn = dynamic_cast<Return *> (processor)) != 0) {
3562 return_bitset[retrn->bit_slot()] = false;
3569 Session::available_capture_duration ()
3571 float sample_bytes_on_disk = 4.0; // keep gcc happy
3573 switch (config.get_native_file_data_format()) {
3575 sample_bytes_on_disk = 4.0;
3579 sample_bytes_on_disk = 3.0;
3583 sample_bytes_on_disk = 2.0;
3587 /* impossible, but keep some gcc versions happy */
3588 fatal << string_compose (_("programming error: %1"),
3589 X_("illegal native file data format"))
3594 double scale = 4096.0 / sample_bytes_on_disk;
3596 if (_total_free_4k_blocks * scale > (double) max_frames) {
3600 return (nframes_t) floor (_total_free_4k_blocks * scale);
3604 Session::add_bundle (shared_ptr<Bundle> bundle)
3607 RCUWriter<BundleList> writer (_bundles);
3608 boost::shared_ptr<BundleList> b = writer.get_copy ();
3609 b->push_back (bundle);
3612 BundleAdded (bundle); /* EMIT SIGNAL */
3618 Session::remove_bundle (shared_ptr<Bundle> bundle)
3620 bool removed = false;
3623 RCUWriter<BundleList> writer (_bundles);
3624 boost::shared_ptr<BundleList> b = writer.get_copy ();
3625 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3627 if (i != b->end()) {
3634 BundleRemoved (bundle); /* EMIT SIGNAL */
3641 Session::bundle_by_name (string name) const
3643 boost::shared_ptr<BundleList> b = _bundles.reader ();
3645 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3646 if ((*i)->name() == name) {
3651 return boost::shared_ptr<Bundle> ();
3655 Session::tempo_map_changed (Change)
3659 playlists->update_after_tempo_map_change ();
3664 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3665 * the given count with the current block size.
3668 Session::ensure_buffers (ChanCount howmany)
3670 if (current_block_size == 0) {
3671 return; // too early? (is this ok?)
3674 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3675 size_t count = std::max(_scratch_buffers->available().get(*t), howmany.get(*t));
3676 _scratch_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3677 _mix_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3678 _silent_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3681 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3685 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3687 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3688 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3693 Session::next_insert_id ()
3695 /* this doesn't really loop forever. just think about it */
3698 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3699 if (!insert_bitset[n]) {
3700 insert_bitset[n] = true;
3706 /* none available, so resize and try again */
3708 insert_bitset.resize (insert_bitset.size() + 16, false);
3713 Session::next_send_id ()
3715 /* this doesn't really loop forever. just think about it */
3718 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3719 if (!send_bitset[n]) {
3720 send_bitset[n] = true;
3726 /* none available, so resize and try again */
3728 send_bitset.resize (send_bitset.size() + 16, false);
3733 Session::next_return_id ()
3735 /* this doesn't really loop forever. just think about it */
3738 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3739 if (!return_bitset[n]) {
3740 return_bitset[n] = true;
3746 /* none available, so resize and try again */
3748 return_bitset.resize (return_bitset.size() + 16, false);
3753 Session::mark_send_id (uint32_t id)
3755 if (id >= send_bitset.size()) {
3756 send_bitset.resize (id+16, false);
3758 if (send_bitset[id]) {
3759 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3761 send_bitset[id] = true;
3765 Session::mark_return_id (uint32_t id)
3767 if (id >= return_bitset.size()) {
3768 return_bitset.resize (id+16, false);
3770 if (return_bitset[id]) {
3771 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3773 return_bitset[id] = true;
3777 Session::mark_insert_id (uint32_t id)
3779 if (id >= insert_bitset.size()) {
3780 insert_bitset.resize (id+16, false);
3782 if (insert_bitset[id]) {
3783 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3785 insert_bitset[id] = true;
3788 /* Named Selection management */
3790 boost::shared_ptr<NamedSelection>
3791 Session::named_selection_by_name (string name)
3793 Glib::Mutex::Lock lm (named_selection_lock);
3794 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3795 if ((*i)->name == name) {
3799 return boost::shared_ptr<NamedSelection>();
3803 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3806 Glib::Mutex::Lock lm (named_selection_lock);
3807 named_selections.insert (named_selections.begin(), named_selection);
3812 NamedSelectionAdded (); /* EMIT SIGNAL */
3816 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3818 bool removed = false;
3821 Glib::Mutex::Lock lm (named_selection_lock);
3823 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3825 if (i != named_selections.end()) {
3826 named_selections.erase (i);
3833 NamedSelectionRemoved (); /* EMIT SIGNAL */
3838 Session::reset_native_file_format ()
3840 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3842 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3843 (*i)->reset_write_sources (false);
3848 Session::route_name_unique (string n) const
3850 shared_ptr<RouteList> r = routes.reader ();
3852 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3853 if ((*i)->name() == n) {
3862 Session::route_name_internal (string n) const
3864 if (auditioner && auditioner->name() == n) {
3868 if (_click_io && _click_io->name() == n) {
3876 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3878 if (!force && howmany <= _npan_buffers) {
3882 if (_pan_automation_buffer) {
3884 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3885 delete [] _pan_automation_buffer[i];
3888 delete [] _pan_automation_buffer;
3891 _pan_automation_buffer = new pan_t*[howmany];
3893 for (uint32_t i = 0; i < howmany; ++i) {
3894 _pan_automation_buffer[i] = new pan_t[nframes];
3897 _npan_buffers = howmany;
3901 Session::freeze (InterThreadInfo& itt)
3903 shared_ptr<RouteList> r = routes.reader ();
3905 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3907 boost::shared_ptr<Track> t;
3909 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3910 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3920 boost::shared_ptr<Region>
3921 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3922 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3923 InterThreadInfo& itt, bool enable_processing)
3925 boost::shared_ptr<Region> result;
3926 boost::shared_ptr<Playlist> playlist;
3927 boost::shared_ptr<AudioFileSource> fsource;
3929 char buf[PATH_MAX+1];
3930 ChanCount nchans(track.audio_diskstream()->n_channels());
3932 nframes_t this_chunk;
3935 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3936 const string sound_dir = sdir.sound_path().to_string();
3937 nframes_t len = end - start;
3940 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3941 end, start) << endmsg;
3945 const nframes_t chunk_size = (256 * 1024)/4;
3947 // block all process callback handling
3949 block_processing ();
3951 /* call tree *MUST* hold route_lock */
3953 if ((playlist = track.diskstream()->playlist()) == 0) {
3957 /* external redirects will be a problem */
3959 if (track.has_external_redirects()) {
3963 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3965 for (x = 0; x < 99999; ++x) {
3966 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3967 if (access (buf, F_OK) != 0) {
3973 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3978 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3979 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3982 catch (failed_constructor& err) {
3983 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3987 srcs.push_back (fsource);
3990 /* XXX need to flush all redirects */
3995 /* create a set of reasonably-sized buffers */
3996 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3997 buffers.set_count(nchans);
3999 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4000 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4002 afs->prepare_for_peakfile_writes ();
4005 while (to_do && !itt.cancel) {
4007 this_chunk = min (to_do, chunk_size);
4009 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
4014 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4015 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4018 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4024 start += this_chunk;
4025 to_do -= this_chunk;
4027 itt.progress = (float) (1.0 - ((double) to_do / len));
4036 xnow = localtime (&now);
4038 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4039 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4042 afs->update_header (position, *xnow, now);
4043 afs->flush_header ();
4047 /* construct a region to represent the bounced material */
4049 result = RegionFactory::create (srcs, 0,
4050 srcs.front()->length(srcs.front()->timeline_position()),
4051 region_name_from_path (srcs.front()->name(), true));
4056 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4057 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4060 afs->mark_for_remove ();
4063 (*src)->drop_references ();
4067 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4068 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4071 afs->done_with_peakfile_writes ();
4075 unblock_processing ();
4081 Session::get_silent_buffers (ChanCount count)
4083 assert(_silent_buffers->available() >= count);
4084 _silent_buffers->set_count(count);
4086 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4087 for (size_t i= 0; i < count.get(*t); ++i) {
4088 _silent_buffers->get(*t, i).clear();
4092 return *_silent_buffers;
4096 Session::get_scratch_buffers (ChanCount count)
4098 if (count != ChanCount::ZERO) {
4099 assert(_scratch_buffers->available() >= count);
4100 _scratch_buffers->set_count(count);
4102 _scratch_buffers->set_count (_scratch_buffers->available());
4105 return *_scratch_buffers;
4109 Session::get_mix_buffers (ChanCount count)
4111 assert(_mix_buffers->available() >= count);
4112 _mix_buffers->set_count(count);
4113 return *_mix_buffers;
4117 Session::ntracks () const
4120 shared_ptr<RouteList> r = routes.reader ();
4122 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4123 if (boost::dynamic_pointer_cast<Track> (*i)) {
4132 Session::nbusses () const
4135 shared_ptr<RouteList> r = routes.reader ();
4137 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4138 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4147 Session::add_automation_list(AutomationList *al)
4149 automation_lists[al->id()] = al;
4153 Session::compute_initial_length ()
4155 return _engine.frame_rate() * 60 * 5;
4159 Session::sync_order_keys (std::string const & base)
4161 if (deletion_in_progress()) {
4165 if (!Config->get_sync_all_route_ordering()) {
4166 /* leave order keys as they are */
4170 boost::shared_ptr<RouteList> r = routes.reader ();
4172 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4173 (*i)->sync_order_keys (base);
4176 Route::SyncOrderKeys (base); // EMIT SIGNAL
4180 /** @return true if there is at least one record-enabled diskstream, otherwise false */
4182 Session::have_rec_enabled_diskstream () const
4184 return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
4187 /** Update the state of our rec-enabled diskstreams flag */
4189 Session::update_have_rec_enabled_diskstream ()
4191 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
4192 DiskstreamList::iterator i = dsl->begin ();
4193 while (i != dsl->end () && (*i)->record_enabled () == false) {
4197 int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
4199 g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
4201 if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
4202 RecordStateChanged (); /* EMIT SIGNAL */
4207 Session::listen_position_changed ()
4211 switch (Config->get_listen_position()) {
4212 case AfterFaderListen:
4216 case PreFaderListen:
4221 boost::shared_ptr<RouteList> r = routes.reader ();
4223 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4224 (*i)->put_control_outs_at (p);
4229 Session::solo_control_mode_changed ()
4231 /* cancel all solo or all listen when solo control mode changes */
4233 if (Config->get_solo_control_is_listen_control()) {
4234 set_solo (routes.reader(), false);
4236 set_listen (routes.reader(), false);
4241 Session::route_group_changed ()
4243 RouteGroupChanged (); /* EMIT SIGNAL */
4247 Session::get_available_sync_options () const
4249 vector<SyncSource> ret;
4251 ret.push_back (JACK);
4254 ret.push_back (MTC);
4257 if (midi_clock_port()) {
4258 ret.push_back (MIDIClock);
4264 boost::shared_ptr<RouteList>
4265 Session::get_routes_with_regions_at (nframes64_t const p) const
4267 shared_ptr<RouteList> r = routes.reader ();
4268 shared_ptr<RouteList> rl (new RouteList);
4270 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4271 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4276 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
4281 boost::shared_ptr<Playlist> pl = ds->playlist ();
4286 if (pl->has_region_at (p)) {