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 */
31 #include <sigc++/bind.h>
32 #include <sigc++/retype.h>
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
36 #include <glibmm/fileutils.h>
38 #include "pbd/error.h"
39 #include <glibmm/thread.h>
40 #include "pbd/boost_debug.h"
41 #include "pbd/pathscanner.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
47 #include "ardour/amp.h"
48 #include "ardour/analyser.h"
49 #include "ardour/audio_buffer.h"
50 #include "ardour/audio_diskstream.h"
51 #include "ardour/audio_port.h"
52 #include "ardour/audio_track.h"
53 #include "ardour/audioengine.h"
54 #include "ardour/audiofilesource.h"
55 #include "ardour/audioplaylist.h"
56 #include "ardour/audioregion.h"
57 #include "ardour/auditioner.h"
58 #include "ardour/buffer_set.h"
59 #include "ardour/bundle.h"
60 #include "ardour/butler.h"
61 #include "ardour/click.h"
62 #include "ardour/configuration.h"
63 #include "ardour/crossfade.h"
64 #include "ardour/cycle_timer.h"
65 #include "ardour/data_type.h"
66 #include "ardour/debug.h"
67 #include "ardour/filename_extensions.h"
68 #include "ardour/internal_send.h"
69 #include "ardour/io_processor.h"
70 #include "ardour/midi_diskstream.h"
71 #include "ardour/midi_playlist.h"
72 #include "ardour/midi_region.h"
73 #include "ardour/midi_track.h"
74 #include "ardour/named_selection.h"
75 #include "ardour/playlist.h"
76 #include "ardour/plugin_insert.h"
77 #include "ardour/port_insert.h"
78 #include "ardour/processor.h"
79 #include "ardour/rc_configuration.h"
80 #include "ardour/recent_sessions.h"
81 #include "ardour/region_factory.h"
82 #include "ardour/return.h"
83 #include "ardour/route_group.h"
84 #include "ardour/send.h"
85 #include "ardour/session.h"
86 #include "ardour/session_directory.h"
87 #include "ardour/session_directory.h"
88 #include "ardour/session_metadata.h"
89 #include "ardour/session_playlists.h"
90 #include "ardour/slave.h"
91 #include "ardour/smf_source.h"
92 #include "ardour/source_factory.h"
93 #include "ardour/tape_file_matcher.h"
94 #include "ardour/tempo.h"
95 #include "ardour/utils.h"
100 using namespace ARDOUR;
102 using boost::shared_ptr;
103 using boost::weak_ptr;
105 bool Session::_disable_all_loaded_plugins = false;
107 sigc::signal<void,std::string> Session::Dialog;
108 sigc::signal<int> Session::AskAboutPendingState;
109 sigc::signal<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
110 sigc::signal<void> Session::SendFeedback;
112 sigc::signal<void> Session::TimecodeOffsetChanged;
113 sigc::signal<void> Session::StartTimeChanged;
114 sigc::signal<void> Session::EndTimeChanged;
115 sigc::signal<void> Session::AutoBindingOn;
116 sigc::signal<void> Session::AutoBindingOff;
117 sigc::signal<void, std::string, std::string> Session::Exported;
119 Session::Session (AudioEngine &eng,
120 const string& fullpath,
121 const string& snapshot_name,
125 _target_transport_speed (0.0),
126 _requested_return_frame (-1),
127 _scratch_buffers(new BufferSet()),
128 _silent_buffers(new BufferSet()),
129 _mix_buffers(new BufferSet()),
131 _mmc_port (default_mmc_port),
132 _mtc_port (default_mtc_port),
133 _midi_port (default_midi_port),
134 _midi_clock_port (default_midi_clock_port),
135 _session_dir (new SessionDirectory(fullpath)),
136 pending_events (2048),
138 _butler (new Butler (this)),
139 _post_transport_work (0),
140 _send_timecode_update (false),
141 midi_thread (pthread_t (0)),
142 midi_requests (128), // the size of this should match the midi request pool size
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)
158 interpolation.add_channel_to (0, 0);
160 if (!eng.connected()) {
161 throw failed_constructor();
164 info << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
166 n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
167 n_physical_inputs = _engine.n_physical_inputs(DataType::AUDIO);
169 first_stage_init (fullpath, snapshot_name);
171 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
174 if (create (new_session, mix_template, compute_initial_length())) {
176 throw failed_constructor ();
180 if (second_stage_init (new_session)) {
182 throw failed_constructor ();
185 store_recent_sessions(_name, _path);
187 bool was_dirty = dirty();
189 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
191 Config->ParameterChanged.connect (bind (mem_fun (*this, &Session::config_changed), false));
192 config.ParameterChanged.connect (bind (mem_fun (*this, &Session::config_changed), true));
195 DirtyChanged (); /* EMIT SIGNAL */
199 Session::Session (AudioEngine &eng,
201 string snapshot_name,
202 AutoConnectOption input_ac,
203 AutoConnectOption output_ac,
204 uint32_t control_out_channels,
205 uint32_t master_out_channels,
206 uint32_t requested_physical_in,
207 uint32_t requested_physical_out,
208 nframes_t initial_length)
211 _target_transport_speed (0.0),
212 _requested_return_frame (-1),
213 _scratch_buffers(new BufferSet()),
214 _silent_buffers(new BufferSet()),
215 _mix_buffers(new BufferSet()),
217 _mmc_port (default_mmc_port),
218 _mtc_port (default_mtc_port),
219 _midi_port (default_midi_port),
220 _midi_clock_port (default_midi_clock_port),
221 _session_dir ( new SessionDirectory(fullpath)),
222 pending_events (2048),
224 _butler (new Butler (this)),
225 _post_transport_work (0),
226 _send_timecode_update (false),
227 midi_thread (pthread_t (0)),
229 diskstreams (new DiskstreamList),
230 routes (new RouteList),
231 _total_free_4k_blocks (0),
232 _bundles (new BundleList),
233 _bundle_xml_node (0),
234 _click_io ((IO *) 0),
236 click_emphasis_data (0),
238 _metadata (new SessionMetadata()),
239 _have_rec_enabled_diskstream (false)
243 interpolation.add_channel_to (0, 0);
245 if (!eng.connected()) {
246 throw failed_constructor();
249 info << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
251 n_physical_outputs = _engine.n_physical_outputs (DataType::AUDIO);
252 n_physical_inputs = _engine.n_physical_inputs (DataType::AUDIO);
254 if (n_physical_inputs) {
255 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
258 if (n_physical_outputs) {
259 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
262 first_stage_init (fullpath, snapshot_name);
264 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
267 if (create (new_session, string(), initial_length)) {
269 throw failed_constructor ();
274 /* set up Master Out and Control Out if necessary */
279 if (master_out_channels) {
280 ChanCount count(DataType::AUDIO, master_out_channels);
281 shared_ptr<Route> r (new Route (*this, _("master"), Route::MasterOut, DataType::AUDIO));
282 r->input()->ensure_io (count, false, this);
283 r->output()->ensure_io (count, false, this);
284 r->set_remote_control_id (control_id);
288 /* prohibit auto-connect to master, because there isn't one */
289 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
292 if (control_out_channels) {
293 ChanCount count(DataType::AUDIO, control_out_channels);
294 shared_ptr<Route> r (new Route (*this, _("monitor"), Route::ControlOut, DataType::AUDIO));
295 r->input()->ensure_io (count, false, this);
296 r->output()->ensure_io (count, false, this);
297 r->set_remote_control_id (control_id++);
303 add_routes (rl, false);
308 if (no_auto_connect()) {
309 input_ac = AutoConnectOption (0);
310 output_ac = AutoConnectOption (0);
313 Config->set_input_auto_connect (input_ac);
314 Config->set_output_auto_connect (output_ac);
316 if (second_stage_init (new_session)) {
318 throw failed_constructor ();
321 store_recent_sessions (_name, _path);
323 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
325 Config->ParameterChanged.connect (bind (mem_fun (*this, &Session::config_changed), false));
336 vector<void*> debug_pointers;
338 /* if we got to here, leaving pending capture state around
342 remove_pending_capture_state ();
344 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
346 _engine.remove_session ();
348 GoingAway (); /* EMIT SIGNAL */
354 /* clear history so that no references to objects are held any more */
358 /* clear state tree so that no references to objects are held any more */
362 /* reset dynamic state version back to default */
364 Stateful::loading_state_version = 0;
366 _butler->terminate_thread ();
367 //terminate_midi_thread ();
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 Route::SyncOrderKeys.clear();
393 DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
394 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
395 NamedSelectionList::iterator tmp;
404 DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
405 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
406 RegionList::iterator tmp;
411 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for region %1 (%2); pre-ref = %2\n", i->second->name(), i->second.get(), i->second.use_count()));
412 i->second->drop_references ();
413 DEBUG_TRACE(DEBUG::Destruction, string_compose ("region post ref = %1\n", i->second.use_count()));
419 DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
421 /* reset these three references to special routes before we do the usual route delete thing */
424 _master_out.reset ();
425 _control_out.reset ();
428 RCUWriter<RouteList> writer (routes);
429 boost::shared_ptr<RouteList> r = writer.get_copy ();
430 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
431 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
432 (*i)->drop_references ();
435 /* writer goes out of scope and updates master */
439 DEBUG_TRACE (DEBUG::Destruction, "delete diskstreams\n");
441 RCUWriter<DiskstreamList> dwriter (diskstreams);
442 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
443 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
444 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for diskstream %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
445 (*i)->drop_references ();
449 diskstreams.flush ();
451 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
452 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
453 SourceMap::iterator tmp;
458 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
459 i->second->drop_references ();
467 DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
468 for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
472 Crossfade::set_buffer_size (0);
476 boost_debug_list_ptrs ();
478 DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
482 Session::set_worst_io_latencies ()
484 _worst_output_latency = 0;
485 _worst_input_latency = 0;
487 if (!_engine.connected()) {
491 boost::shared_ptr<RouteList> r = routes.reader ();
493 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
494 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
495 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
500 Session::when_engine_running ()
502 string first_physical_output;
504 BootMessage (_("Set block size and sample rate"));
506 set_block_size (_engine.frames_per_cycle());
507 set_frame_rate (_engine.frame_rate());
509 BootMessage (_("Using configuration"));
511 Config->map_parameters (bind (mem_fun (*this, &Session::config_changed), false));
512 config.map_parameters (bind (mem_fun (*this, &Session::config_changed), true));
514 /* every time we reconnect, recompute worst case output latencies */
516 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
518 if (synced_to_jack()) {
519 _engine.transport_stop ();
522 if (config.get_jack_time_master()) {
523 _engine.transport_locate (_transport_frame);
531 _click_io.reset (new ClickIO (*this, "click"));
533 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
535 /* existing state for Click */
538 if (Stateful::loading_state_version < 3000) {
539 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
541 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
546 _clicking = Config->get_clicking ();
550 error << _("could not setup Click I/O") << endmsg;
557 /* default state for Click: dual-mono to first 2 physical outputs */
559 for (int physport = 0; physport < 2; ++physport) {
560 string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
562 if (physical_output.length()) {
563 if (_click_io->add_port (physical_output, this)) {
564 // relax, even though its an error
569 if (_click_io->n_ports () > ChanCount::ZERO) {
570 _clicking = Config->get_clicking ();
575 catch (failed_constructor& err) {
576 error << _("cannot setup Click I/O") << endmsg;
579 BootMessage (_("Compute I/O Latencies"));
581 set_worst_io_latencies ();
584 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
587 BootMessage (_("Set up standard connections"));
589 /* Create a set of Bundle objects that map
590 to the physical I/O currently available. We create both
591 mono and stereo bundles, so that the common cases of mono
592 and stereo tracks get bundles to put in their mixer strip
593 in / out menus. There may be a nicer way of achieving that;
594 it doesn't really scale that well to higher channel counts
597 /* mono output bundles */
599 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
601 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
603 shared_ptr<Bundle> c (new Bundle (buf, true));
604 c->add_channel (_("mono"));
605 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
610 /* stereo output bundles */
612 for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
613 if (np + 1 < n_physical_outputs) {
615 snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
616 shared_ptr<Bundle> c (new Bundle (buf, true));
617 c->add_channel (_("L"));
618 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
619 c->add_channel (_("R"));
620 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
626 /* mono input bundles */
628 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
630 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
632 shared_ptr<Bundle> c (new Bundle (buf, false));
633 c->add_channel (_("mono"));
634 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
639 /* stereo input bundles */
641 for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
642 if (np + 1 < n_physical_inputs) {
644 snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
646 shared_ptr<Bundle> c (new Bundle (buf, false));
647 c->add_channel (_("L"));
648 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
649 c->add_channel (_("R"));
650 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
656 BootMessage (_("Setup signal flow and plugins"));
660 if (!no_auto_connect()) {
662 if (_master_out && Config->get_auto_connect_standard_busses()) {
664 /* if requested auto-connect the outputs to the first N physical ports.
667 uint32_t limit = _master_out->n_outputs().n_total();
669 for (uint32_t n = 0; n < limit; ++n) {
670 Port* p = _master_out->output()->nth (n);
671 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
673 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
674 if (_master_out->output()->connect (p, connect_to, this)) {
675 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
685 /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
686 are undefined, at best.
689 /* control out listens to master bus (but ignores it
690 under some conditions)
693 uint32_t limit = _control_out->n_inputs().n_audio();
696 for (uint32_t n = 0; n < limit; ++n) {
697 AudioPort* p = _control_out->input()->ports().nth_audio_port (n);
698 AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
701 string connect_to = o->name();
702 if (_control_out->input()->connect (p, connect_to, this)) {
703 error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
711 /* if control out is not connected,
712 connect control out to physical outs, but use ones after the master if possible
715 if (!_control_out->output()->connected_to (boost::shared_ptr<IO>())) {
717 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
719 boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
722 _control_out->output()->connect_ports_to_bundle (b, this);
724 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
725 Config->get_monitor_bus_preferred_bundle())
731 /* XXX this logic is wrong for mixed port types */
733 uint32_t shift = _master_out->n_outputs().n_audio();
734 uint32_t mod = _engine.n_physical_outputs (DataType::AUDIO);
735 limit = _control_out->n_outputs().n_audio();
737 cerr << "Connecting " << limit << " control out ports, shift is " << shift << " mod is " << mod << endl;
739 for (uint32_t n = 0; n < limit; ++n) {
741 Port* p = _control_out->output()->nth (n);
742 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), (n+shift) % mod);
744 if (!connect_to.empty()) {
745 if (_control_out->output()->connect (p, connect_to, this)) {
746 error << string_compose (_("cannot connect control output %1 to %2"), n, connect_to)
757 /* catch up on send+insert cnts */
759 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
761 /* hook us up to the engine */
763 BootMessage (_("Connect to engine"));
765 _engine.set_session (this);
769 Session::hookup_io ()
771 /* stop graph reordering notifications from
772 causing resorts, etc.
775 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
780 /* we delay creating the auditioner till now because
781 it makes its own connections to ports.
782 the engine has to be running for this to work.
786 auditioner.reset (new Auditioner (*this));
789 catch (failed_constructor& err) {
790 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
794 /* load bundles, which we may have postponed earlier on */
795 if (_bundle_xml_node) {
796 load_bundles (*_bundle_xml_node);
797 delete _bundle_xml_node;
800 /* Tell all IO objects to connect themselves together */
802 IO::enable_connecting ();
804 /* Now reset all panners */
806 Delivery::reset_panners ();
808 /* Connect tracks to listen/solo etc. busses XXX generalize this beyond control_out */
812 boost::shared_ptr<RouteList> r = routes.reader ();
814 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
816 if ((*x)->is_control() || (*x)->is_master()) {
820 (*x)->listen_via (_control_out,
821 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
826 /* Anyone who cares about input state, wake up and do something */
828 IOConnectionsComplete (); /* EMIT SIGNAL */
830 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
832 /* now handle the whole enchilada as if it was one
838 /* update the full solo state, which can't be
839 correctly determined on a per-route basis, but
840 needs the global overview that only the session
844 update_route_solo_state ();
848 Session::playlist_length_changed ()
850 /* we can't just increase end_location->end() if pl->get_maximum_extent()
851 if larger. if the playlist used to be the longest playlist,
852 and its now shorter, we have to decrease end_location->end(). hence,
853 we have to iterate over all diskstreams and check the
854 playlists currently in use.
860 Session::diskstream_playlist_changed (boost::weak_ptr<Diskstream> wp)
862 boost::shared_ptr<Diskstream> dstream = wp.lock ();
867 boost::shared_ptr<Playlist> playlist;
869 if ((playlist = dstream->playlist()) != 0) {
870 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
873 /* see comment in playlist_length_changed () */
878 Session::record_enabling_legal () const
880 /* this used to be in here, but survey says.... we don't need to restrict it */
881 // if (record_status() == Recording) {
885 if (Config->get_all_safe()) {
892 Session::reset_input_monitor_state ()
894 if (transport_rolling()) {
896 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
898 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
899 if ((*i)->record_enabled ()) {
900 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
901 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
905 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
907 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
908 if ((*i)->record_enabled ()) {
909 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
910 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
917 Session::auto_punch_start_changed (Location* location)
919 replace_event (Event::PunchIn, location->start());
921 if (get_record_enabled() && config.get_punch_in()) {
922 /* capture start has been changed, so save new pending state */
923 save_state ("", true);
928 Session::auto_punch_end_changed (Location* location)
930 nframes_t when_to_stop = location->end();
931 // when_to_stop += _worst_output_latency + _worst_input_latency;
932 replace_event (Event::PunchOut, when_to_stop);
936 Session::auto_punch_changed (Location* location)
938 nframes_t when_to_stop = location->end();
940 replace_event (Event::PunchIn, location->start());
941 //when_to_stop += _worst_output_latency + _worst_input_latency;
942 replace_event (Event::PunchOut, when_to_stop);
946 Session::auto_loop_changed (Location* location)
948 replace_event (Event::AutoLoop, location->end(), location->start());
950 if (transport_rolling() && play_loop) {
953 // if (_transport_frame > location->end()) {
955 if (_transport_frame < location->start() || _transport_frame > location->end()) {
956 // relocate to beginning of loop
957 clear_events (Event::LocateRoll);
959 request_locate (location->start(), true);
962 else if (Config->get_seamless_loop() && !loop_changing) {
964 // schedule a locate-roll to refill the diskstreams at the
966 loop_changing = true;
968 if (location->end() > last_loopend) {
969 clear_events (Event::LocateRoll);
970 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
977 last_loopend = location->end();
981 Session::set_auto_punch_location (Location* location)
985 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
986 auto_punch_start_changed_connection.disconnect();
987 auto_punch_end_changed_connection.disconnect();
988 auto_punch_changed_connection.disconnect();
989 existing->set_auto_punch (false, this);
990 remove_event (existing->start(), Event::PunchIn);
991 clear_events (Event::PunchOut);
992 auto_punch_location_changed (0);
1001 if (location->end() <= location->start()) {
1002 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1006 auto_punch_start_changed_connection.disconnect();
1007 auto_punch_end_changed_connection.disconnect();
1008 auto_punch_changed_connection.disconnect();
1010 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1011 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1012 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1014 location->set_auto_punch (true, this);
1017 auto_punch_changed (location);
1019 auto_punch_location_changed (location);
1023 Session::set_auto_loop_location (Location* location)
1027 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1028 auto_loop_start_changed_connection.disconnect();
1029 auto_loop_end_changed_connection.disconnect();
1030 auto_loop_changed_connection.disconnect();
1031 existing->set_auto_loop (false, this);
1032 remove_event (existing->end(), Event::AutoLoop);
1033 auto_loop_location_changed (0);
1038 if (location == 0) {
1042 if (location->end() <= location->start()) {
1043 error << _("Session: you can't use a mark for auto loop") << endmsg;
1047 last_loopend = location->end();
1049 auto_loop_start_changed_connection.disconnect();
1050 auto_loop_end_changed_connection.disconnect();
1051 auto_loop_changed_connection.disconnect();
1053 auto_loop_start_changed_connection = location->start_changed.connect (
1054 mem_fun (this, &Session::auto_loop_changed));
1055 auto_loop_end_changed_connection = location->end_changed.connect (
1056 mem_fun (this, &Session::auto_loop_changed));
1057 auto_loop_changed_connection = location->changed.connect (
1058 mem_fun (this, &Session::auto_loop_changed));
1060 location->set_auto_loop (true, this);
1062 /* take care of our stuff first */
1064 auto_loop_changed (location);
1066 /* now tell everyone else */
1068 auto_loop_location_changed (location);
1072 Session::locations_added (Location *)
1078 Session::locations_changed ()
1080 _locations.apply (*this, &Session::handle_locations_changed);
1084 Session::handle_locations_changed (Locations::LocationList& locations)
1086 Locations::LocationList::iterator i;
1088 bool set_loop = false;
1089 bool set_punch = false;
1091 for (i = locations.begin(); i != locations.end(); ++i) {
1095 if (location->is_auto_punch()) {
1096 set_auto_punch_location (location);
1099 if (location->is_auto_loop()) {
1100 set_auto_loop_location (location);
1104 if (location->is_start()) {
1105 start_location = location;
1107 if (location->is_end()) {
1108 end_location = location;
1113 set_auto_loop_location (0);
1116 set_auto_punch_location (0);
1123 Session::enable_record ()
1125 /* XXX really atomic compare+swap here */
1126 if (g_atomic_int_get (&_record_status) != Recording) {
1127 g_atomic_int_set (&_record_status, Recording);
1128 _last_record_location = _transport_frame;
1129 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1131 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1132 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1133 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1134 if ((*i)->record_enabled ()) {
1135 (*i)->monitor_input (true);
1140 RecordStateChanged ();
1145 Session::disable_record (bool rt_context, bool force)
1149 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1151 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1152 g_atomic_int_set (&_record_status, Disabled);
1154 if (rs == Recording) {
1155 g_atomic_int_set (&_record_status, Enabled);
1159 // FIXME: timestamp correct? [DR]
1160 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1161 // does this /need/ to be sent in all cases?
1163 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1165 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1166 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1168 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1169 if ((*i)->record_enabled ()) {
1170 (*i)->monitor_input (false);
1175 RecordStateChanged (); /* emit signal */
1178 remove_pending_capture_state ();
1184 Session::step_back_from_record ()
1186 /* XXX really atomic compare+swap here */
1187 if (g_atomic_int_get (&_record_status) == Recording) {
1188 g_atomic_int_set (&_record_status, Enabled);
1190 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1191 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1193 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1194 if ((*i)->record_enabled ()) {
1195 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1196 (*i)->monitor_input (false);
1204 Session::maybe_enable_record ()
1206 g_atomic_int_set (&_record_status, Enabled);
1208 /* this function is currently called from somewhere other than an RT thread.
1209 this save_state() call therefore doesn't impact anything.
1212 save_state ("", true);
1214 if (_transport_speed) {
1215 if (!config.get_punch_in()) {
1219 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1220 RecordStateChanged (); /* EMIT SIGNAL */
1227 Session::audible_frame () const
1233 /* the first of these two possible settings for "offset"
1234 mean that the audible frame is stationary until
1235 audio emerges from the latency compensation
1238 the second means that the audible frame is stationary
1239 until audio would emerge from a physical port
1240 in the absence of any plugin latency compensation
1243 offset = _worst_output_latency;
1245 if (offset > current_block_size) {
1246 offset -= current_block_size;
1248 /* XXX is this correct? if we have no external
1249 physical connections and everything is internal
1250 then surely this is zero? still, how
1251 likely is that anyway?
1253 offset = current_block_size;
1256 if (synced_to_jack()) {
1257 tf = _engine.transport_frame();
1259 tf = _transport_frame;
1264 if (!non_realtime_work_pending()) {
1268 /* check to see if we have passed the first guaranteed
1269 audible frame past our last start position. if not,
1270 return that last start point because in terms
1271 of audible frames, we have not moved yet.
1274 if (_transport_speed > 0.0f) {
1276 if (!play_loop || !have_looped) {
1277 if (tf < _last_roll_location + offset) {
1278 return _last_roll_location;
1286 } else if (_transport_speed < 0.0f) {
1288 /* XXX wot? no backward looping? */
1290 if (tf > _last_roll_location - offset) {
1291 return _last_roll_location;
1303 Session::set_frame_rate (nframes_t frames_per_second)
1305 /** \fn void Session::set_frame_size(nframes_t)
1306 the AudioEngine object that calls this guarantees
1307 that it will not be called while we are also in
1308 ::process(). Its fine to do things that block
1312 _base_frame_rate = frames_per_second;
1316 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1320 // XXX we need some equivalent to this, somehow
1321 // SndFileSource::setup_standard_crossfades (frames_per_second);
1325 /* XXX need to reset/reinstantiate all LADSPA plugins */
1329 Session::set_block_size (nframes_t nframes)
1331 /* the AudioEngine guarantees
1332 that it will not be called while we are also in
1333 ::process(). It is therefore fine to do things that block
1338 current_block_size = nframes;
1340 ensure_buffers(_scratch_buffers->available());
1342 delete [] _gain_automation_buffer;
1343 _gain_automation_buffer = new gain_t[nframes];
1345 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1347 boost::shared_ptr<RouteList> r = routes.reader ();
1349 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1350 (*i)->set_block_size (nframes);
1353 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1354 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1355 (*i)->set_block_size (nframes);
1358 set_worst_io_latencies ();
1363 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1366 nframes_t fade_frames;
1368 /* Don't allow fade of less 1 frame */
1370 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1377 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1381 default_fade_msecs = fade_msecs;
1382 default_fade_steepness = steepness;
1385 // jlc, WTF is this!
1386 Glib::RWLock::ReaderLock lm (route_lock);
1387 AudioRegion::set_default_fade (steepness, fade_frames);
1392 /* XXX have to do this at some point */
1393 /* foreach region using default fade, reset, then
1394 refill_all_diskstream_buffers ();
1399 struct RouteSorter {
1400 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1401 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1403 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1406 if (r1->fed_by.empty()) {
1407 if (r2->fed_by.empty()) {
1408 /* no ardour-based connections inbound to either route. just use signal order */
1409 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1411 /* r2 has connections, r1 does not; run r1 early */
1415 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1422 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1424 shared_ptr<Route> r2;
1426 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1427 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1431 /* make a copy of the existing list of routes that feed r1 */
1433 set<weak_ptr<Route> > existing = r1->fed_by;
1435 /* for each route that feeds r1, recurse, marking it as feeding
1439 for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1440 if (!(r2 = (*i).lock ())) {
1441 /* (*i) went away, ignore it */
1445 /* r2 is a route that feeds r1 which somehow feeds base. mark
1446 base as being fed by r2
1449 rbase->fed_by.insert (r2);
1453 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1457 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1461 /* now recurse, so that we can mark base as being fed by
1462 all routes that feed r2
1465 trace_terminal (r2, rbase);
1472 Session::resort_routes ()
1474 /* don't do anything here with signals emitted
1475 by Routes while we are being destroyed.
1478 if (_state_of_the_state & Deletion) {
1485 RCUWriter<RouteList> writer (routes);
1486 shared_ptr<RouteList> r = writer.get_copy ();
1487 resort_routes_using (r);
1488 /* writer goes out of scope and forces update */
1493 Session::resort_routes_using (shared_ptr<RouteList> r)
1495 RouteList::iterator i, j;
1497 for (i = r->begin(); i != r->end(); ++i) {
1499 (*i)->fed_by.clear ();
1501 for (j = r->begin(); j != r->end(); ++j) {
1503 /* although routes can feed themselves, it will
1504 cause an endless recursive descent if we
1505 detect it. so don't bother checking for
1513 if ((*j)->feeds (*i)) {
1514 (*i)->fed_by.insert (*j);
1519 for (i = r->begin(); i != r->end(); ++i) {
1520 trace_terminal (*i, *i);
1527 cerr << "finished route resort\n";
1529 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1530 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1537 list<boost::shared_ptr<MidiTrack> >
1538 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1540 char track_name[32];
1541 uint32_t track_id = 0;
1544 RouteList new_routes;
1545 list<boost::shared_ptr<MidiTrack> > ret;
1546 //uint32_t control_id;
1548 // FIXME: need physical I/O and autoconnect stuff for MIDI
1550 /* count existing midi tracks */
1553 shared_ptr<RouteList> r = routes.reader ();
1555 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1556 if (boost::dynamic_pointer_cast<MidiTrack>(*i) != 0) {
1557 if (!(*i)->is_hidden()) {
1559 //channels_used += (*i)->n_inputs().n_midi();
1565 vector<string> physinputs;
1566 vector<string> physoutputs;
1568 _engine.get_physical_outputs (DataType::MIDI, physoutputs);
1569 _engine.get_physical_inputs (DataType::MIDI, physinputs);
1571 // control_id = ntracks() + nbusses();
1575 /* check for duplicate route names, since we might have pre-existing
1576 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1577 save, close,restart,add new route - first named route is now
1585 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1587 if (route_by_name (track_name) == 0) {
1591 } while (track_id < (UINT_MAX-1));
1593 shared_ptr<MidiTrack> track;
1596 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1598 if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1599 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1604 if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1605 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1611 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1615 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1616 port = physinputs[(channels_used+x)%nphysical_in];
1619 if (port.length() && track->connect_input (track->input (x), port, this)) {
1625 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1629 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1630 port = physoutputs[(channels_used+x)%nphysical_out];
1631 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1633 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1637 if (port.length() && track->connect_output (track->output (x), port, this)) {
1642 channels_used += track->n_inputs ().n_midi();
1646 track->midi_diskstream()->non_realtime_input_change();
1647 track->set_route_group (route_group, 0);
1649 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1650 //track->set_remote_control_id (control_id);
1652 new_routes.push_back (track);
1653 ret.push_back (track);
1656 catch (failed_constructor &err) {
1657 error << _("Session: could not create new midi track.") << endmsg;
1660 /* we need to get rid of this, since the track failed to be created */
1661 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1664 RCUWriter<DiskstreamList> writer (diskstreams);
1665 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1666 ds->remove (track->midi_diskstream());
1673 catch (AudioEngine::PortRegistrationFailure& pfe) {
1675 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;
1678 /* we need to get rid of this, since the track failed to be created */
1679 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1682 RCUWriter<DiskstreamList> writer (diskstreams);
1683 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1684 ds->remove (track->midi_diskstream());
1695 if (!new_routes.empty()) {
1696 add_routes (new_routes, false);
1697 save_state (_current_snapshot_name);
1703 list<boost::shared_ptr<AudioTrack> >
1704 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1706 char track_name[32];
1707 uint32_t track_id = 0;
1709 uint32_t channels_used = 0;
1711 RouteList new_routes;
1712 list<boost::shared_ptr<AudioTrack> > ret;
1713 uint32_t control_id;
1715 /* count existing audio tracks */
1718 shared_ptr<RouteList> r = routes.reader ();
1720 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1721 if (boost::dynamic_pointer_cast<AudioTrack>(*i) != 0) {
1722 if (!(*i)->is_hidden()) {
1724 channels_used += (*i)->n_inputs().n_audio();
1730 vector<string> physinputs;
1731 vector<string> physoutputs;
1733 _engine.get_physical_outputs (DataType::AUDIO, physoutputs);
1734 _engine.get_physical_inputs (DataType::AUDIO, physinputs);
1736 control_id = ntracks() + nbusses() + 1;
1740 /* check for duplicate route names, since we might have pre-existing
1741 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1742 save, close,restart,add new route - first named route is now
1750 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1752 if (route_by_name (track_name) == 0) {
1756 } while (track_id < (UINT_MAX-1));
1758 shared_ptr<AudioTrack> track;
1761 AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1762 // boost_debug_shared_ptr_mark_interesting (at, typeid (at).name());
1763 track = boost::shared_ptr<AudioTrack>(at);
1765 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1766 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1767 input_channels, output_channels)
1772 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1773 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1774 input_channels, output_channels)
1779 if (!physinputs.empty()) {
1780 uint32_t nphysical_in = physinputs.size();
1782 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1786 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1787 port = physinputs[(channels_used+x)%nphysical_in];
1790 if (port.length() && track->input()->connect (track->input()->nth(x), port, this)) {
1796 if (!physoutputs.empty()) {
1797 uint32_t nphysical_out = physoutputs.size();
1799 for (uint32_t x = 0; x < track->n_outputs().n_audio(); ++x) {
1802 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1803 port = physoutputs[(channels_used+x)%nphysical_out];
1804 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1805 if (_master_out && _master_out->n_inputs().n_audio() > 0) {
1806 port = _master_out->input()->nth (x % _master_out->input()->n_ports().n_audio())->name();
1810 if (port.length() && track->output()->connect (track->output()->nth(x), port, this)) {
1816 channels_used += track->n_inputs ().n_audio();
1818 track->set_route_group (route_group, 0);
1820 track->audio_diskstream()->non_realtime_input_change();
1822 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1823 track->set_remote_control_id (control_id);
1826 new_routes.push_back (track);
1827 ret.push_back (track);
1830 catch (failed_constructor &err) {
1831 error << _("Session: could not create new audio track.") << 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());
1847 catch (AudioEngine::PortRegistrationFailure& pfe) {
1849 error << pfe.what() << endmsg;
1852 /* we need to get rid of this, since the track failed to be created */
1853 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1856 RCUWriter<DiskstreamList> writer (diskstreams);
1857 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1858 ds->remove (track->audio_diskstream());
1869 if (!new_routes.empty()) {
1870 add_routes (new_routes, true);
1877 Session::set_remote_control_ids ()
1879 RemoteModel m = Config->get_remote_model();
1881 shared_ptr<RouteList> r = routes.reader ();
1883 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1884 if ( MixerOrdered == m) {
1885 long order = (*i)->order_key(N_("signal"));
1886 (*i)->set_remote_control_id( order+1 );
1887 } else if ( EditorOrdered == m) {
1888 long order = (*i)->order_key(N_("editor"));
1889 (*i)->set_remote_control_id( order+1 );
1890 } else if ( UserOrdered == m) {
1891 //do nothing ... only changes to remote id's are initiated by user
1898 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1901 uint32_t bus_id = 1;
1903 uint32_t channels_used = 0;
1906 uint32_t control_id;
1908 /* count existing audio busses */
1911 shared_ptr<RouteList> r = routes.reader ();
1913 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1914 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
1916 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1919 channels_used += (*i)->n_inputs().n_audio();
1925 vector<string> physinputs;
1926 vector<string> physoutputs;
1928 _engine.get_physical_outputs (DataType::AUDIO, physoutputs);
1929 _engine.get_physical_inputs (DataType::AUDIO, physinputs);
1931 n_physical_audio_outputs = physoutputs.size();
1932 n_physical_audio_inputs = physinputs.size();
1934 control_id = ntracks() + nbusses() + 1;
1939 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1943 if (route_by_name (bus_name) == 0) {
1947 } while (bus_id < (UINT_MAX-1));
1950 shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
1952 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1953 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1954 input_channels, output_channels)
1960 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1961 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1962 input_channels, output_channels)
1967 for (uint32_t x = 0; n_physical_audio_inputs && x < bus->input()->n_ports().n_audio(); ++x) {
1970 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1971 port = physinputs[((n+x)%n_physical_audio_inputs)];
1974 if (port.length() && bus->input()->connect (bus->input()->nth (x), port, this)) {
1979 for (uint32_t x = 0; n_physical_audio_outputs && x < bus->n_outputs().n_audio(); ++x) {
1982 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1983 port = physoutputs[((n+x)%n_physical_outputs)];
1984 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1986 port = _master_out->input()->nth (x%_master_out->input()->n_ports().n_audio())->name();
1990 if (port.length() && bus->output()->connect (bus->output()->nth(x), port, this)) {
1995 channels_used += bus->n_inputs ().n_audio();
1997 bus->set_route_group (route_group, 0);
1998 bus->set_remote_control_id (control_id);
2002 bus->add_internal_return ();
2005 ret.push_back (bus);
2009 catch (failed_constructor &err) {
2010 error << _("Session: could not create new audio route.") << endmsg;
2014 catch (AudioEngine::PortRegistrationFailure& pfe) {
2015 error << pfe.what() << endmsg;
2025 add_routes (ret, true);
2033 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
2037 uint32_t control_id;
2039 uint32_t number = 1;
2041 if (!tree.read (template_path.c_str())) {
2045 XMLNode* node = tree.root();
2047 control_id = ntracks() + nbusses() + 1;
2051 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
2053 std::string node_name = IO::name_from_state (*node_copy.children().front());
2055 /* generate a new name by adding a number to the end of the template name */
2058 snprintf (name, sizeof (name), "%s %" PRIu32, node_name.c_str(), number);
2062 if (route_by_name (name) == 0) {
2066 } while (number < UINT_MAX);
2068 if (number == UINT_MAX) {
2069 fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2073 IO::set_name_in_state (*node_copy.children().front(), name);
2075 Track::zero_diskstream_id_in_xml (node_copy);
2078 shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2081 error << _("Session: cannot create track/bus from template description") << endmsg;
2085 if (boost::dynamic_pointer_cast<Track>(route)) {
2086 /* force input/output change signals so that the new diskstream
2087 picks up the configuration of the route. During session
2088 loading this normally happens in a different way.
2090 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
2091 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
2094 route->set_remote_control_id (control_id);
2097 ret.push_back (route);
2100 catch (failed_constructor &err) {
2101 error << _("Session: could not create new route from template") << endmsg;
2105 catch (AudioEngine::PortRegistrationFailure& pfe) {
2106 error << pfe.what() << endmsg;
2115 add_routes (ret, true);
2122 Session::add_routes (RouteList& new_routes, bool save)
2125 RCUWriter<RouteList> writer (routes);
2126 shared_ptr<RouteList> r = writer.get_copy ();
2127 r->insert (r->end(), new_routes.begin(), new_routes.end());
2130 /* if there is no control out and we're not in the middle of loading,
2131 resort the graph here. if there is a control out, we will resort
2132 toward the end of this method. if we are in the middle of loading,
2133 we will resort when done.
2136 if (!_control_out && IO::connecting_legal) {
2137 resort_routes_using (r);
2141 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2143 boost::weak_ptr<Route> wpr (*x);
2145 (*x)->listen_changed.connect (sigc::bind (mem_fun (*this, &Session::route_listen_changed), wpr));
2146 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
2147 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
2148 (*x)->output()->changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
2149 (*x)->processors_changed.connect (mem_fun (*this, &Session::route_processors_changed));
2150 (*x)->route_group_changed.connect (hide (mem_fun (*this, &Session::route_group_changed)));
2152 if ((*x)->is_master()) {
2156 if ((*x)->is_control()) {
2157 _control_out = (*x);
2161 if (_control_out && IO::connecting_legal) {
2163 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2164 if ((*x)->is_control() || (*x)->is_master()) {
2167 (*x)->listen_via (_control_out,
2168 (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
2178 save_state (_current_snapshot_name);
2181 RouteAdded (new_routes); /* EMIT SIGNAL */
2185 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2187 boost::shared_ptr<RouteList> r = routes.reader ();
2188 boost::shared_ptr<Send> s;
2192 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2193 if (boost::dynamic_pointer_cast<Track>(*i)) {
2194 if ((s = (*i)->internal_send_for (dest)) != 0) {
2195 s->amp()->gain_control()->set_value (0.0);
2202 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2204 boost::shared_ptr<RouteList> r = routes.reader ();
2205 boost::shared_ptr<Send> s;
2209 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2210 if (boost::dynamic_pointer_cast<Track>(*i)) {
2211 if ((s = (*i)->internal_send_for (dest)) != 0) {
2212 s->amp()->gain_control()->set_value (1.0);
2219 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2221 boost::shared_ptr<RouteList> r = routes.reader ();
2222 boost::shared_ptr<Send> s;
2226 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2227 if (boost::dynamic_pointer_cast<Track>(*i)) {
2228 if ((s = (*i)->internal_send_for (dest)) != 0) {
2229 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2236 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2238 boost::shared_ptr<RouteList> r = routes.reader ();
2239 boost::shared_ptr<RouteList> t (new RouteList);
2241 /* only send tracks */
2243 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2244 if (boost::dynamic_pointer_cast<Track>(*i)) {
2249 add_internal_sends (dest, p, t);
2253 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2255 if (dest->is_control() || dest->is_master()) {
2259 if (!dest->internal_return()) {
2260 dest->add_internal_return();
2263 for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2265 if ((*i)->is_control() || (*i)->is_master() || (*i) == dest) {
2269 (*i)->listen_via (dest, p, true, true);
2276 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2278 /* need to do this in case we're rolling at the time, to prevent false underruns */
2279 dstream->do_refill_with_alloc ();
2281 dstream->set_block_size (current_block_size);
2284 RCUWriter<DiskstreamList> writer (diskstreams);
2285 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2286 ds->push_back (dstream);
2287 /* writer goes out of scope, copies ds back to main */
2290 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), boost::weak_ptr<Diskstream> (dstream)));
2291 /* this will connect to future changes, and check the current length */
2292 diskstream_playlist_changed (boost::weak_ptr<Diskstream> (dstream));
2294 dstream->RecordEnableChanged.connect (mem_fun (*this, &Session::update_have_rec_enabled_diskstream));
2296 dstream->prepare ();
2301 Session::remove_route (shared_ptr<Route> route)
2304 RCUWriter<RouteList> writer (routes);
2305 shared_ptr<RouteList> rs = writer.get_copy ();
2309 /* deleting the master out seems like a dumb
2310 idea, but its more of a UI policy issue
2314 if (route == _master_out) {
2315 _master_out = shared_ptr<Route> ();
2318 if (route == _control_out) {
2320 /* cancel control outs for all routes */
2322 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2323 (*r)->drop_listen (_control_out);
2326 _control_out.reset ();
2329 update_route_solo_state ();
2331 /* writer goes out of scope, forces route list update */
2334 boost::shared_ptr<Track> t;
2335 boost::shared_ptr<Diskstream> ds;
2337 if ((t = boost::dynamic_pointer_cast<Track>(route)) != 0) {
2338 ds = t->diskstream();
2344 RCUWriter<DiskstreamList> dsl (diskstreams);
2345 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2350 find_current_end ();
2352 // We need to disconnect the routes inputs and outputs
2354 route->input()->disconnect (0);
2355 route->output()->disconnect (0);
2357 /* if the route had internal sends sending to it, remove them */
2358 if (route->internal_return()) {
2360 boost::shared_ptr<RouteList> r = routes.reader ();
2361 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2362 boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2364 (*i)->remove_processor (s);
2369 update_latency_compensation (false, false);
2372 /* get rid of it from the dead wood collection in the route list manager */
2374 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2378 /* try to cause everyone to drop their references */
2380 route->drop_references ();
2382 sync_order_keys (N_("session"));
2384 /* save the new state of the world */
2386 if (save_state (_current_snapshot_name)) {
2387 save_history (_current_snapshot_name);
2392 Session::route_mute_changed (void* /*src*/)
2398 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2400 boost::shared_ptr<Route> route = wpr.lock();
2402 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2406 if (route->listening()) {
2408 } else if (_listen_cnt > 0) {
2414 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2416 if (solo_update_disabled) {
2421 boost::shared_ptr<Route> route = wpr.lock ();
2424 /* should not happen */
2425 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2429 shared_ptr<RouteList> r = routes.reader ();
2432 if (route->self_soloed()) {
2438 /* now mod the solo level of all other routes except master & control outs
2439 so that they will be silent if appropriate.
2442 solo_update_disabled = true;
2444 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2445 bool via_sends_only;
2448 if ((*i) == route || !(*i)->solo_isolated() || !(*i)->is_master() || !(*i)->is_control() || (*i)->is_hidden()) {
2450 } else if ((*i)->feeds (route, &via_sends_only)) {
2451 if (!via_sends_only) {
2452 (*i)->mod_solo_by_others (delta);
2457 /* make sure master is never muted by solo */
2459 if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2460 _master_out->mod_solo_by_others (1);
2463 /* ditto for control outs make sure master is never muted by solo */
2465 if (_control_out && route != _control_out && _control_out && _control_out->soloed_by_others() == 0) {
2466 _control_out->mod_solo_by_others (1);
2469 solo_update_disabled = false;
2470 update_route_solo_state (r);
2471 SoloChanged (); /* EMIT SIGNAL */
2476 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2478 /* now figure out if anything that matters is soloed */
2480 bool something_soloed = false;
2483 r = routes.reader();
2486 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2487 if (!(*i)->is_master() && !(*i)->is_control() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2488 something_soloed = true;
2493 if (something_soloed != _non_soloed_outs_muted) {
2494 _non_soloed_outs_muted = something_soloed;
2495 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2499 boost::shared_ptr<RouteList>
2500 Session::get_routes_with_internal_returns() const
2502 shared_ptr<RouteList> r = routes.reader ();
2503 boost::shared_ptr<RouteList> rl (new RouteList);
2505 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2506 if ((*i)->internal_return ()) {
2514 Session::route_by_name (string name)
2516 shared_ptr<RouteList> r = routes.reader ();
2518 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2519 if ((*i)->name() == name) {
2524 return shared_ptr<Route> ((Route*) 0);
2528 Session::route_by_id (PBD::ID id)
2530 shared_ptr<RouteList> r = routes.reader ();
2532 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2533 if ((*i)->id() == id) {
2538 return shared_ptr<Route> ((Route*) 0);
2542 Session::route_by_remote_id (uint32_t id)
2544 shared_ptr<RouteList> r = routes.reader ();
2546 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2547 if ((*i)->remote_control_id() == id) {
2552 return shared_ptr<Route> ((Route*) 0);
2556 Session::find_current_end ()
2558 if (_state_of_the_state & Loading) {
2562 nframes_t max = get_maximum_extent ();
2564 if (max > end_location->end()) {
2565 end_location->set_end (max);
2567 DurationChanged(); /* EMIT SIGNAL */
2572 Session::get_maximum_extent () const
2577 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2579 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2580 if ((*i)->destructive()) //ignore tape tracks when getting max extents
2582 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2583 if ((me = pl->get_maximum_extent()) > max) {
2591 boost::shared_ptr<Diskstream>
2592 Session::diskstream_by_name (string name)
2594 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2596 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2597 if ((*i)->name() == name) {
2602 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2605 boost::shared_ptr<Diskstream>
2606 Session::diskstream_by_id (const PBD::ID& id)
2608 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2610 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2611 if ((*i)->id() == id) {
2616 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2619 /* Region management */
2622 Session::new_region_name (string old)
2624 string::size_type last_period;
2626 string::size_type len = old.length() + 64;
2629 if ((last_period = old.find_last_of ('.')) == string::npos) {
2631 /* no period present - add one explicitly */
2634 last_period = old.length() - 1;
2639 number = atoi (old.substr (last_period+1).c_str());
2643 while (number < (UINT_MAX-1)) {
2645 RegionList::const_iterator i;
2650 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2653 for (i = regions.begin(); i != regions.end(); ++i) {
2654 if (i->second->name() == sbuf) {
2659 if (i == regions.end()) {
2664 if (number != (UINT_MAX-1)) {
2668 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2673 Session::region_name (string& result, string base, bool newlevel)
2678 if (base.find("/") != string::npos) {
2679 base = base.substr(base.find_last_of("/") + 1);
2684 Glib::Mutex::Lock lm (region_lock);
2686 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2695 string::size_type pos;
2697 pos = base.find_last_of ('.');
2699 /* pos may be npos, but then we just use entire base */
2701 subbase = base.substr (0, pos);
2706 Glib::Mutex::Lock lm (region_lock);
2708 map<string,uint32_t>::iterator x;
2712 if ((x = region_name_map.find (subbase)) == region_name_map.end()) {
2714 region_name_map[subbase] = 1;
2717 snprintf (buf, sizeof (buf), ".%d", x->second);
2728 Session::add_region (boost::shared_ptr<Region> region)
2730 vector<boost::shared_ptr<Region> > v;
2731 v.push_back (region);
2736 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2741 Glib::Mutex::Lock lm (region_lock);
2743 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2745 boost::shared_ptr<Region> region = *ii;
2749 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2753 RegionList::iterator x;
2755 for (x = regions.begin(); x != regions.end(); ++x) {
2757 if (region->region_list_equivalent (x->second)) {
2762 if (x == regions.end()) {
2764 pair<RegionList::key_type,RegionList::mapped_type> entry;
2766 entry.first = region->id();
2767 entry.second = region;
2769 pair<RegionList::iterator,bool> x = regions.insert (entry);
2781 /* mark dirty because something has changed even if we didn't
2782 add the region to the region list.
2789 vector<boost::weak_ptr<Region> > v;
2790 boost::shared_ptr<Region> first_r;
2792 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2794 boost::shared_ptr<Region> region = *ii;
2798 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2801 v.push_back (region);
2808 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2809 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2811 update_region_name_map (region);
2815 RegionsAdded (v); /* EMIT SIGNAL */
2821 Session::update_region_name_map (boost::shared_ptr<Region> region)
2823 string::size_type last_period = region->name().find_last_of ('.');
2825 if (last_period != string::npos && last_period < region->name().length() - 1) {
2827 string base = region->name().substr (0, last_period);
2828 string number = region->name().substr (last_period+1);
2829 map<string,uint32_t>::iterator x;
2831 /* note that if there is no number, we get zero from atoi,
2835 region_name_map[base] = atoi (number);
2840 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2842 boost::shared_ptr<Region> region (weak_region.lock ());
2848 if (what_changed & Region::HiddenChanged) {
2849 /* relay hidden changes */
2850 RegionHiddenChange (region);
2853 if (what_changed & NameChanged) {
2854 update_region_name_map (region);
2859 Session::remove_region (boost::weak_ptr<Region> weak_region)
2861 RegionList::iterator i;
2862 boost::shared_ptr<Region> region (weak_region.lock ());
2868 bool removed = false;
2871 Glib::Mutex::Lock lm (region_lock);
2873 if ((i = regions.find (region->id())) != regions.end()) {
2879 /* mark dirty because something has changed even if we didn't
2880 remove the region from the region list.
2886 RegionRemoved(region); /* EMIT SIGNAL */
2890 boost::shared_ptr<Region>
2891 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2893 RegionList::iterator i;
2894 boost::shared_ptr<Region> region;
2896 Glib::Mutex::Lock lm (region_lock);
2898 for (i = regions.begin(); i != regions.end(); ++i) {
2902 if (region->whole_file()) {
2904 if (child->source_equivalent (region)) {
2910 return boost::shared_ptr<Region> ();
2914 Session::destroy_region (boost::shared_ptr<Region> region)
2916 vector<boost::shared_ptr<Source> > srcs;
2919 if (region->playlist()) {
2920 region->playlist()->destroy_region (region);
2923 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2924 srcs.push_back (region->source (n));
2928 region->drop_references ();
2930 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2932 (*i)->mark_for_remove ();
2933 (*i)->drop_references ();
2935 cerr << "source was not used by any playlist\n";
2942 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2944 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2945 destroy_region (*i);
2951 Session::remove_last_capture ()
2953 list<boost::shared_ptr<Region> > r;
2955 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2957 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2958 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2961 r.insert (r.end(), l.begin(), l.end());
2966 destroy_regions (r);
2968 save_state (_current_snapshot_name);
2974 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2980 /* Source Management */
2983 Session::add_source (boost::shared_ptr<Source> source)
2985 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2986 pair<SourceMap::iterator,bool> result;
2988 entry.first = source->id();
2989 entry.second = source;
2992 Glib::Mutex::Lock lm (source_lock);
2993 result = sources.insert (entry);
2996 if (result.second) {
2997 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
3001 boost::shared_ptr<AudioFileSource> afs;
3003 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3004 if (Config->get_auto_analyse_audio()) {
3005 Analyser::queue_source_for_analysis (source, false);
3011 Session::remove_source (boost::weak_ptr<Source> src)
3013 SourceMap::iterator i;
3014 boost::shared_ptr<Source> source = src.lock();
3021 Glib::Mutex::Lock lm (source_lock);
3023 if ((i = sources.find (source->id())) != sources.end()) {
3028 if (!_state_of_the_state & InCleanup) {
3030 /* save state so we don't end up with a session file
3031 referring to non-existent sources.
3034 save_state (_current_snapshot_name);
3038 boost::shared_ptr<Source>
3039 Session::source_by_id (const PBD::ID& id)
3041 Glib::Mutex::Lock lm (source_lock);
3042 SourceMap::iterator i;
3043 boost::shared_ptr<Source> source;
3045 if ((i = sources.find (id)) != sources.end()) {
3052 boost::shared_ptr<Source>
3053 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
3055 Glib::Mutex::Lock lm (source_lock);
3057 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3058 cerr << "comparing " << path << " with " << i->second->name() << endl;
3059 boost::shared_ptr<AudioFileSource> afs
3060 = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3062 if (afs && afs->path() == path && chn == afs->channel()) {
3066 return boost::shared_ptr<Source>();
3071 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3074 string old_basename = PBD::basename_nosuffix (oldname);
3075 string new_legalized = legalize_for_path (newname);
3077 /* note: we know (or assume) the old path is already valid */
3081 /* destructive file sources have a name of the form:
3083 /path/to/Tnnnn-NAME(%[LR])?.wav
3085 the task here is to replace NAME with the new name.
3088 /* find last slash */
3092 string::size_type slash;
3093 string::size_type dash;
3095 if ((slash = path.find_last_of ('/')) == string::npos) {
3099 dir = path.substr (0, slash+1);
3101 /* '-' is not a legal character for the NAME part of the path */
3103 if ((dash = path.find_last_of ('-')) == string::npos) {
3107 prefix = path.substr (slash+1, dash-(slash+1));
3112 path += new_legalized;
3113 path += ".wav"; /* XXX gag me with a spoon */
3117 /* non-destructive file sources have a name of the form:
3119 /path/to/NAME-nnnnn(%[LR])?.ext
3121 the task here is to replace NAME with the new name.
3126 string::size_type slash;
3127 string::size_type dash;
3128 string::size_type postfix;
3130 /* find last slash */
3132 if ((slash = path.find_last_of ('/')) == string::npos) {
3136 dir = path.substr (0, slash+1);
3138 /* '-' is not a legal character for the NAME part of the path */
3140 if ((dash = path.find_last_of ('-')) == string::npos) {
3144 suffix = path.substr (dash+1);
3146 // Suffix is now everything after the dash. Now we need to eliminate
3147 // the nnnnn part, which is done by either finding a '%' or a '.'
3149 postfix = suffix.find_last_of ("%");
3150 if (postfix == string::npos) {
3151 postfix = suffix.find_last_of ('.');
3154 if (postfix != string::npos) {
3155 suffix = suffix.substr (postfix);
3157 error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3161 const uint32_t limit = 10000;
3162 char buf[PATH_MAX+1];
3164 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3166 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3168 if (access (buf, F_OK) != 0) {
3176 error << "FATAL ERROR! Could not find a " << endl;
3184 /** Return the full path (in some session directory) for a new within-session source.
3185 * \a name must be a session-unique name that does not contain slashes
3186 * (e.g. as returned by new_*_source_name)
3189 Session::new_source_path_from_name (DataType type, const string& name)
3191 assert(name.find("/") == string::npos);
3193 SessionDirectory sdir(get_best_session_directory_for_new_source());
3196 if (type == DataType::AUDIO) {
3197 p = sdir.sound_path();
3198 } else if (type == DataType::MIDI) {
3199 p = sdir.midi_path();
3201 error << "Unknown source type, unable to create file path" << endmsg;
3206 return p.to_string();
3210 Session::peak_path (Glib::ustring base) const
3212 sys::path peakfile_path(_session_dir->peak_path());
3213 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
3214 return peakfile_path.to_string();
3217 /** Return a unique name based on \a base for a new internal audio source */
3219 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3223 char buf[PATH_MAX+1];
3224 const uint32_t limit = 10000;
3228 legalized = legalize_for_path (base);
3230 // Find a "version" of the base name that doesn't exist in any of the possible directories.
3231 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3233 vector<space_and_path>::iterator i;
3234 uint32_t existing = 0;
3236 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3238 SessionDirectory sdir((*i).path);
3240 spath = sdir.sound_path().to_string();
3245 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3246 spath.c_str(), cnt, legalized.c_str());
3247 } else if (nchan == 2) {
3249 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
3250 spath.c_str(), cnt, legalized.c_str());
3252 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
3253 spath.c_str(), cnt, legalized.c_str());
3255 } else if (nchan < 26) {
3256 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
3257 spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3259 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3260 spath.c_str(), cnt, legalized.c_str());
3269 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3270 } else if (nchan == 2) {
3272 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3274 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3276 } else if (nchan < 26) {
3277 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3279 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3283 if (sys::exists(buf)) {
3289 if (existing == 0) {
3294 error << string_compose(
3295 _("There are already %1 recordings for %2, which I consider too many."),
3296 limit, base) << endmsg;
3298 throw failed_constructor();
3302 return Glib::path_get_basename(buf);
3305 /** Create a new within-session audio source */
3306 boost::shared_ptr<AudioFileSource>
3307 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3309 const size_t n_chans = ds.n_channels().n_audio();
3310 const string name = new_audio_source_name (ds.name(), n_chans, chan, destructive);
3311 const string path = new_source_path_from_name(DataType::AUDIO, name);
3313 return boost::dynamic_pointer_cast<AudioFileSource> (
3314 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3317 /** Return a unique name based on \a base for a new internal MIDI source */
3319 Session::new_midi_source_name (const string& base)
3322 char buf[PATH_MAX+1];
3323 const uint32_t limit = 10000;
3327 legalized = legalize_for_path (base);
3329 // Find a "version" of the file name that doesn't exist in any of the possible directories.
3330 for (cnt = 1; cnt <= limit; ++cnt) {
3332 vector<space_and_path>::iterator i;
3333 uint32_t existing = 0;
3335 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3337 SessionDirectory sdir((*i).path);
3339 sys::path p = sdir.midi_path();
3342 snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
3344 if (sys::exists (buf)) {
3349 if (existing == 0) {
3354 error << string_compose(
3355 _("There are already %1 recordings for %2, which I consider too many."),
3356 limit, base) << endmsg;
3358 throw failed_constructor();
3362 return Glib::path_get_basename(buf);
3366 /** Create a new within-session MIDI source */
3367 boost::shared_ptr<MidiSource>
3368 Session::create_midi_source_for_session (MidiDiskstream& ds)
3370 const string name = new_midi_source_name (ds.name());
3371 const string path = new_source_path_from_name (DataType::MIDI, name);
3373 return boost::dynamic_pointer_cast<SMFSource> (
3374 SourceFactory::createWritable (
3375 DataType::MIDI, *this, path, false, frame_rate()));
3380 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3382 if (playlist->hidden()) {
3386 bool existing = playlists.add (playlist);
3388 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3392 playlist->release();
3399 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3401 if (_state_of_the_state & Deletion) {
3405 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3411 playlists.remove (playlist);
3417 Session::set_audition (boost::shared_ptr<Region> r)
3419 pending_audition_region = r;
3420 add_post_transport_work (PostTransportAudition);
3421 _butler->schedule_transport_work ();
3425 Session::audition_playlist ()
3427 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3428 ev->region.reset ();
3433 Session::non_realtime_set_audition ()
3435 if (!pending_audition_region) {
3436 auditioner->audition_current_playlist ();
3438 auditioner->audition_region (pending_audition_region);
3439 pending_audition_region.reset ();
3441 AuditionActive (true); /* EMIT SIGNAL */
3445 Session::audition_region (boost::shared_ptr<Region> r)
3447 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3453 Session::cancel_audition ()
3455 if (auditioner->active()) {
3456 auditioner->cancel_audition ();
3457 AuditionActive (false); /* EMIT SIGNAL */
3462 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3464 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3468 Session::remove_empty_sounds ()
3470 vector<string> audio_filenames;
3472 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3474 Glib::Mutex::Lock lm (source_lock);
3476 TapeFileMatcher tape_file_matcher;
3478 remove_if (audio_filenames.begin(), audio_filenames.end(),
3479 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3481 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3483 sys::path audio_file_path (_session_dir->sound_path());
3485 audio_file_path /= *i;
3487 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3491 sys::remove (audio_file_path);
3492 const string peakfile = peak_path (audio_file_path.to_string());
3493 sys::remove (peakfile);
3495 catch (const sys::filesystem_error& err)
3497 error << err.what() << endmsg;
3504 Session::is_auditioning () const
3506 /* can be called before we have an auditioner object */
3508 return auditioner->active();
3515 Session::set_all_solo (bool yn)
3517 shared_ptr<RouteList> r = routes.reader ();
3519 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3520 if (!(*i)->is_hidden()) {
3521 (*i)->set_solo (yn, this);
3529 Session::set_all_listen (bool yn)
3531 shared_ptr<RouteList> r = routes.reader ();
3533 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3534 if (!(*i)->is_hidden()) {
3535 (*i)->set_listen (yn, this);
3543 Session::set_all_mute (bool yn)
3545 shared_ptr<RouteList> r = routes.reader ();
3547 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3548 if (!(*i)->is_hidden()) {
3549 (*i)->set_mute (yn, this);
3557 Session::n_diskstreams () const
3561 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3563 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3564 if (!(*i)->hidden()) {
3572 Session::graph_reordered ()
3574 /* don't do this stuff if we are setting up connections
3575 from a set_state() call or creating new tracks. Ditto for deletion.
3578 if (_state_of_the_state & (InitialConnecting|Deletion)) {
3582 /* every track/bus asked for this to be handled but it was deferred because
3583 we were connecting. do it now.
3586 request_input_change_handling ();
3590 /* force all diskstreams to update their capture offset values to
3591 reflect any changes in latencies within the graph.
3594 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3596 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3597 (*i)->set_capture_offset ();
3602 Session::record_disenable_all ()
3604 record_enable_change_all (false);
3608 Session::record_enable_all ()
3610 record_enable_change_all (true);
3614 Session::record_enable_change_all (bool yn)
3616 shared_ptr<RouteList> r = routes.reader ();
3618 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3619 boost::shared_ptr<Track> t;
3621 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3622 t->set_record_enable (yn, this);
3626 /* since we don't keep rec-enable state, don't mark session dirty */
3630 Session::add_processor (Processor* processor)
3632 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3637 Session::remove_processor (Processor* processor)
3641 PortInsert* port_insert;
3643 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3644 insert_bitset[port_insert->bit_slot()] = false;
3645 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3646 send_bitset[send->bit_slot()] = false;
3647 } else if ((retrn = dynamic_cast<Return *> (processor)) != 0) {
3648 return_bitset[retrn->bit_slot()] = false;
3655 Session::available_capture_duration ()
3657 float sample_bytes_on_disk = 4.0; // keep gcc happy
3659 switch (config.get_native_file_data_format()) {
3661 sample_bytes_on_disk = 4.0;
3665 sample_bytes_on_disk = 3.0;
3669 sample_bytes_on_disk = 2.0;
3673 /* impossible, but keep some gcc versions happy */
3674 fatal << string_compose (_("programming error: %1"),
3675 X_("illegal native file data format"))
3680 double scale = 4096.0 / sample_bytes_on_disk;
3682 if (_total_free_4k_blocks * scale > (double) max_frames) {
3686 return (nframes_t) floor (_total_free_4k_blocks * scale);
3690 Session::add_bundle (shared_ptr<Bundle> bundle)
3693 RCUWriter<BundleList> writer (_bundles);
3694 boost::shared_ptr<BundleList> b = writer.get_copy ();
3695 b->push_back (bundle);
3698 BundleAdded (bundle); /* EMIT SIGNAL */
3704 Session::remove_bundle (shared_ptr<Bundle> bundle)
3706 bool removed = false;
3709 RCUWriter<BundleList> writer (_bundles);
3710 boost::shared_ptr<BundleList> b = writer.get_copy ();
3711 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3713 if (i != b->end()) {
3720 BundleRemoved (bundle); /* EMIT SIGNAL */
3727 Session::bundle_by_name (string name) const
3729 boost::shared_ptr<BundleList> b = _bundles.reader ();
3731 for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3732 if ((*i)->name() == name) {
3737 return boost::shared_ptr<Bundle> ();
3741 Session::tempo_map_changed (Change)
3745 playlists.update_after_tempo_map_change ();
3750 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3751 * the given count with the current block size.
3754 Session::ensure_buffers (ChanCount howmany)
3756 if (current_block_size == 0) {
3757 return; // too early? (is this ok?)
3760 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3761 size_t count = std::max(_scratch_buffers->available().get(*t), howmany.get(*t));
3762 _scratch_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3763 _mix_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3764 _silent_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3767 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3771 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3773 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3774 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3779 Session::next_insert_id ()
3781 /* this doesn't really loop forever. just think about it */
3784 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3785 if (!insert_bitset[n]) {
3786 insert_bitset[n] = true;
3792 /* none available, so resize and try again */
3794 insert_bitset.resize (insert_bitset.size() + 16, false);
3799 Session::next_send_id ()
3801 /* this doesn't really loop forever. just think about it */
3804 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3805 if (!send_bitset[n]) {
3806 send_bitset[n] = true;
3812 /* none available, so resize and try again */
3814 send_bitset.resize (send_bitset.size() + 16, false);
3819 Session::next_return_id ()
3821 /* this doesn't really loop forever. just think about it */
3824 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3825 if (!return_bitset[n]) {
3826 return_bitset[n] = true;
3832 /* none available, so resize and try again */
3834 return_bitset.resize (return_bitset.size() + 16, false);
3839 Session::mark_send_id (uint32_t id)
3841 if (id >= send_bitset.size()) {
3842 send_bitset.resize (id+16, false);
3844 if (send_bitset[id]) {
3845 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3847 send_bitset[id] = true;
3851 Session::mark_return_id (uint32_t id)
3853 if (id >= return_bitset.size()) {
3854 return_bitset.resize (id+16, false);
3856 if (return_bitset[id]) {
3857 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3859 return_bitset[id] = true;
3863 Session::mark_insert_id (uint32_t id)
3865 if (id >= insert_bitset.size()) {
3866 insert_bitset.resize (id+16, false);
3868 if (insert_bitset[id]) {
3869 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3871 insert_bitset[id] = true;
3874 /* Named Selection management */
3877 Session::named_selection_by_name (string name)
3879 Glib::Mutex::Lock lm (named_selection_lock);
3880 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3881 if ((*i)->name == name) {
3889 Session::add_named_selection (NamedSelection* named_selection)
3892 Glib::Mutex::Lock lm (named_selection_lock);
3893 named_selections.insert (named_selections.begin(), named_selection);
3896 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3902 NamedSelectionAdded (); /* EMIT SIGNAL */
3906 Session::remove_named_selection (NamedSelection* named_selection)
3908 bool removed = false;
3911 Glib::Mutex::Lock lm (named_selection_lock);
3913 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3915 if (i != named_selections.end()) {
3917 named_selections.erase (i);
3924 NamedSelectionRemoved (); /* EMIT SIGNAL */
3929 Session::reset_native_file_format ()
3931 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3933 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3934 (*i)->reset_write_sources (false);
3939 Session::route_name_unique (string n) const
3941 shared_ptr<RouteList> r = routes.reader ();
3943 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3944 if ((*i)->name() == n) {
3953 Session::route_name_internal (string n) const
3955 if (auditioner && auditioner->name() == n) {
3959 if (_click_io && _click_io->name() == n) {
3967 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3969 if (!force && howmany <= _npan_buffers) {
3973 if (_pan_automation_buffer) {
3975 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3976 delete [] _pan_automation_buffer[i];
3979 delete [] _pan_automation_buffer;
3982 _pan_automation_buffer = new pan_t*[howmany];
3984 for (uint32_t i = 0; i < howmany; ++i) {
3985 _pan_automation_buffer[i] = new pan_t[nframes];
3988 _npan_buffers = howmany;
3992 Session::freeze (InterThreadInfo& itt)
3994 shared_ptr<RouteList> r = routes.reader ();
3996 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3998 boost::shared_ptr<Track> t;
4000 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4001 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4011 boost::shared_ptr<Region>
4012 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
4013 bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4014 InterThreadInfo& itt, bool enable_processing)
4016 boost::shared_ptr<Region> result;
4017 boost::shared_ptr<Playlist> playlist;
4018 boost::shared_ptr<AudioFileSource> fsource;
4020 char buf[PATH_MAX+1];
4021 ChanCount nchans(track.audio_diskstream()->n_channels());
4023 nframes_t this_chunk;
4026 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4027 const string sound_dir = sdir.sound_path().to_string();
4028 nframes_t len = end - start;
4031 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4032 end, start) << endmsg;
4036 // any bigger than this seems to cause stack overflows in called functions
4037 const nframes_t chunk_size = (128 * 1024)/4;
4039 // block all process callback handling
4041 block_processing ();
4043 /* call tree *MUST* hold route_lock */
4045 if ((playlist = track.diskstream()->playlist()) == 0) {
4049 /* external redirects will be a problem */
4051 if (track.has_external_redirects()) {
4055 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4057 for (x = 0; x < 99999; ++x) {
4058 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4059 if (access (buf, F_OK) != 0) {
4065 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4070 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4071 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4074 catch (failed_constructor& err) {
4075 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4079 srcs.push_back (fsource);
4082 /* XXX need to flush all redirects */
4087 /* create a set of reasonably-sized buffers */
4088 buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
4089 buffers.set_count(nchans);
4091 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4092 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4094 afs->prepare_for_peakfile_writes ();
4097 while (to_do && !itt.cancel) {
4099 this_chunk = min (to_do, chunk_size);
4101 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
4106 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4107 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4110 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4116 start += this_chunk;
4117 to_do -= this_chunk;
4119 itt.progress = (float) (1.0 - ((double) to_do / len));
4128 xnow = localtime (&now);
4130 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4131 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4134 afs->update_header (position, *xnow, now);
4135 afs->flush_header ();
4139 /* construct a region to represent the bounced material */
4141 result = RegionFactory::create (srcs, 0,
4142 srcs.front()->length(srcs.front()->timeline_position()),
4143 region_name_from_path (srcs.front()->name(), true));
4148 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4149 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4152 afs->mark_for_remove ();
4155 (*src)->drop_references ();
4159 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4160 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4163 afs->done_with_peakfile_writes ();
4167 unblock_processing ();
4173 Session::get_silent_buffers (ChanCount count)
4175 assert(_silent_buffers->available() >= count);
4176 _silent_buffers->set_count(count);
4178 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4179 for (size_t i= 0; i < count.get(*t); ++i) {
4180 _silent_buffers->get(*t, i).clear();
4184 return *_silent_buffers;
4188 Session::get_scratch_buffers (ChanCount count)
4190 if (count != ChanCount::ZERO) {
4191 assert(_scratch_buffers->available() >= count);
4192 _scratch_buffers->set_count(count);
4194 _scratch_buffers->set_count (_scratch_buffers->available());
4197 return *_scratch_buffers;
4201 Session::get_mix_buffers (ChanCount count)
4203 assert(_mix_buffers->available() >= count);
4204 _mix_buffers->set_count(count);
4205 return *_mix_buffers;
4209 Session::ntracks () const
4212 shared_ptr<RouteList> r = routes.reader ();
4214 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4215 if (boost::dynamic_pointer_cast<Track> (*i)) {
4224 Session::nbusses () const
4227 shared_ptr<RouteList> r = routes.reader ();
4229 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4230 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4239 Session::add_automation_list(AutomationList *al)
4241 automation_lists[al->id()] = al;
4245 Session::compute_initial_length ()
4247 return _engine.frame_rate() * 60 * 5;
4251 Session::sync_order_keys (std::string const & base)
4253 if (!Config->get_sync_all_route_ordering()) {
4254 /* leave order keys as they are */
4258 boost::shared_ptr<RouteList> r = routes.reader ();
4260 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4261 (*i)->sync_order_keys (base);
4264 Route::SyncOrderKeys (base); // EMIT SIGNAL
4268 /** @return true if there is at least one record-enabled diskstream, otherwise false */
4270 Session::have_rec_enabled_diskstream () const
4272 return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
4275 /** Update the state of our rec-enabled diskstreams flag */
4277 Session::update_have_rec_enabled_diskstream ()
4279 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
4280 DiskstreamList::iterator i = dsl->begin ();
4281 while (i != dsl->end () && (*i)->record_enabled () == false) {
4285 int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
4287 g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
4289 if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
4290 RecordStateChanged (); /* EMIT SIGNAL */
4295 Session::listen_position_changed ()
4299 switch (Config->get_listen_position()) {
4300 case AfterFaderListen:
4304 case PreFaderListen:
4309 boost::shared_ptr<RouteList> r = routes.reader ();
4311 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4312 (*i)->put_control_outs_at (p);
4317 Session::solo_control_mode_changed ()
4319 /* cancel all solo or all listen when solo control mode changes */
4321 if (Config->get_solo_control_is_listen_control()) {
4322 set_all_solo (false);
4324 set_all_listen (false);
4329 Session::route_group_changed ()
4331 RouteGroupChanged (); /* EMIT SIGNAL */
4335 Session::get_available_sync_options () const
4337 vector<SyncSource> ret;
4339 ret.push_back (JACK);
4342 ret.push_back (MTC);
4345 if (midi_clock_port()) {
4346 ret.push_back (MIDIClock);
4352 boost::shared_ptr<RouteList>
4353 Session::get_routes_with_regions_at (nframes64_t const p) const
4355 shared_ptr<RouteList> r = routes.reader ();
4356 shared_ptr<RouteList> rl (new RouteList);
4358 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4359 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4364 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
4369 boost::shared_ptr<Playlist> pl = ds->playlist ();
4374 if (pl->has_region_at (p)) {