Move panner bypass state up to the PannerShell so that it is preserved even when...
[ardour2.git] / libs / ardour / audio_diskstream.cc
blob1132b2a05037010188866874dd8b634428f33e53
1 /*
2 Copyright (C) 2000-2006 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.
19 #include <fstream>
20 #include <cstdio>
21 #include <unistd.h>
22 #include <cmath>
23 #include <cerrno>
24 #include <cassert>
25 #include <string>
26 #include <climits>
27 #include <fcntl.h>
28 #include <cstdlib>
29 #include <ctime>
30 #include <sys/stat.h>
31 #include <sys/mman.h>
33 #include "pbd/error.h"
34 #include "pbd/xml++.h"
35 #include "pbd/memento_command.h"
36 #include "pbd/enumwriter.h"
37 #include "pbd/stateful_diff_command.h"
39 #include "ardour/analyser.h"
40 #include "ardour/ardour.h"
41 #include "ardour/audio_buffer.h"
42 #include "ardour/audio_diskstream.h"
43 #include "ardour/audio_port.h"
44 #include "ardour/audioengine.h"
45 #include "ardour/audiofilesource.h"
47 #include "ardour/audioplaylist.h"
48 #include "ardour/audioregion.h"
49 #include "ardour/butler.h"
50 #include "ardour/configuration.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/debug.h"
53 #include "ardour/io.h"
54 #include "ardour/playlist_factory.h"
55 #include "ardour/region_factory.h"
56 #include "ardour/send.h"
57 #include "ardour/session.h"
58 #include "ardour/source_factory.h"
59 #include "ardour/utils.h"
60 #include "ardour/session_playlists.h"
61 #include "ardour/route.h"
63 #include "i18n.h"
64 #include <locale.h>
66 using namespace std;
67 using namespace ARDOUR;
68 using namespace PBD;
70 size_t AudioDiskstream::_working_buffers_size = 0;
71 Sample* AudioDiskstream::_mixdown_buffer = 0;
72 gain_t* AudioDiskstream::_gain_buffer = 0;
74 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
75 : Diskstream(sess, name, flag)
76 , channels (new ChannelList)
78 /* prevent any write sources from being created */
80 in_set_state = true;
81 use_new_playlist ();
82 in_set_state = false;
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , channels (new ChannelList)
89 in_set_state = true;
90 init ();
92 if (set_state (node, Stateful::loading_state_version)) {
93 in_set_state = false;
94 throw failed_constructor();
97 in_set_state = false;
99 if (destructive()) {
100 use_destructive_playlist ();
104 void
105 AudioDiskstream::init ()
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 AudioDiskstream::~AudioDiskstream ()
118 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
121 RCUWriter<ChannelList> writer (channels);
122 boost::shared_ptr<ChannelList> c = writer.get_copy();
124 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
125 delete *chan;
128 c->clear();
131 channels.flush ();
134 void
135 AudioDiskstream::allocate_working_buffers()
137 assert(disk_io_frames() > 0);
139 _working_buffers_size = disk_io_frames();
140 _mixdown_buffer = new Sample[_working_buffers_size];
141 _gain_buffer = new gain_t[_working_buffers_size];
144 void
145 AudioDiskstream::free_working_buffers()
147 delete [] _mixdown_buffer;
148 delete [] _gain_buffer;
149 _working_buffers_size = 0;
150 _mixdown_buffer = 0;
151 _gain_buffer = 0;
154 void
155 AudioDiskstream::non_realtime_input_change ()
158 Glib::Mutex::Lock lm (state_lock);
160 if (input_change_pending.type == IOChange::NoChange) {
161 return;
164 if (input_change_pending.type == IOChange::ConfigurationChanged) {
165 RCUWriter<ChannelList> writer (channels);
166 boost::shared_ptr<ChannelList> c = writer.get_copy();
168 _n_channels.set(DataType::AUDIO, c->size());
170 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
171 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
172 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
173 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
177 if (input_change_pending.type & IOChange::ConnectionsChanged) {
178 get_input_sources ();
179 set_capture_offset ();
180 set_align_style_from_io ();
183 input_change_pending = IOChange::NoChange;
185 /* implicit unlock */
188 /* reset capture files */
190 reset_write_sources (false);
192 /* now refill channel buffers */
194 if (speed() != 1.0f || speed() != -1.0f) {
195 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
196 } else {
197 seek (_session.transport_frame());
201 void
202 AudioDiskstream::non_realtime_locate (framepos_t location)
204 /* now refill channel buffers */
206 if (speed() != 1.0f || speed() != -1.0f) {
207 seek ((framepos_t) (location * (double) speed()));
208 } else {
209 seek (location);
213 void
214 AudioDiskstream::get_input_sources ()
216 boost::shared_ptr<ChannelList> c = channels.reader();
218 uint32_t n;
219 ChannelList::iterator chan;
220 uint32_t ni = _io->n_ports().n_audio();
221 vector<string> connections;
223 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
225 connections.clear ();
227 if (_io->nth (n)->get_connections (connections) == 0) {
228 if (!(*chan)->source.name.empty()) {
229 // _source->disable_metering ();
231 (*chan)->source.name = string();
232 } else {
233 (*chan)->source.name = connections[0];
239 AudioDiskstream::find_and_use_playlist (const string& name)
241 boost::shared_ptr<AudioPlaylist> playlist;
243 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
244 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
247 if (!playlist) {
248 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
249 return -1;
252 return use_playlist (playlist);
256 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
258 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
260 Diskstream::use_playlist(playlist);
262 return 0;
266 AudioDiskstream::use_new_playlist ()
268 string newname;
269 boost::shared_ptr<AudioPlaylist> playlist;
271 if (!in_set_state && destructive()) {
272 return 0;
275 if (_playlist) {
276 newname = Playlist::bump_name (_playlist->name(), _session);
277 } else {
278 newname = Playlist::bump_name (_name, _session);
281 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
283 playlist->set_orig_diskstream_id (id());
284 return use_playlist (playlist);
286 } else {
287 return -1;
292 AudioDiskstream::use_copy_playlist ()
294 assert(audio_playlist());
296 if (destructive()) {
297 return 0;
300 if (_playlist == 0) {
301 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
302 return -1;
305 string newname;
306 boost::shared_ptr<AudioPlaylist> playlist;
308 newname = Playlist::bump_name (_playlist->name(), _session);
310 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
311 playlist->set_orig_diskstream_id (id());
312 return use_playlist (playlist);
313 } else {
314 return -1;
318 void
319 AudioDiskstream::setup_destructive_playlist ()
321 SourceList srcs;
322 boost::shared_ptr<ChannelList> c = channels.reader();
324 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
325 srcs.push_back ((*chan)->write_source);
328 /* a single full-sized region */
330 assert (!srcs.empty ());
332 PropertyList plist;
333 plist.add (Properties::name, _name.val());
334 plist.add (Properties::start, 0);
335 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
337 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
338 _playlist->add_region (region, srcs.front()->natural_position());
341 void
342 AudioDiskstream::use_destructive_playlist ()
344 /* this is called from the XML-based constructor or ::set_destructive. when called,
345 we already have a playlist and a region, but we need to
346 set up our sources for write. we use the sources associated
347 with the (presumed single, full-extent) region.
350 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
352 if (!rp) {
353 reset_write_sources (false, true);
354 return;
357 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
359 if (region == 0) {
360 throw failed_constructor();
363 /* be sure to stretch the region out to the maximum length */
365 region->set_length (max_framepos - region->position());
367 uint32_t n;
368 ChannelList::iterator chan;
369 boost::shared_ptr<ChannelList> c = channels.reader();
371 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
372 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
373 assert((*chan)->write_source);
374 (*chan)->write_source->set_allow_remove_if_empty (false);
376 /* this might be false if we switched modes, so force it */
378 (*chan)->write_source->set_destructive (true);
381 /* the source list will never be reset for a destructive track */
384 void
385 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
387 if (recordable() && destructive()) {
388 boost::shared_ptr<ChannelList> c = channels.reader();
389 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
391 RingBufferNPT<CaptureTransition>::rw_vector transitions;
392 (*chan)->capture_transition_buf->get_write_vector (&transitions);
394 if (transitions.len[0] > 0) {
395 transitions.buf[0]->type = CaptureStart;
396 transitions.buf[0]->capture_val = capture_start_frame;
397 (*chan)->capture_transition_buf->increment_write_ptr(1);
398 } else {
399 // bad!
400 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
401 << endmsg;
408 AudioDiskstream::process (framepos_t transport_frame, pframes_t nframes, bool can_record, bool rec_monitors_input, bool& need_butler)
410 uint32_t n;
411 boost::shared_ptr<ChannelList> c = channels.reader();
412 ChannelList::iterator chan;
413 int ret = -1;
414 framecnt_t rec_offset = 0;
415 framecnt_t rec_nframes = 0;
416 bool collect_playback = false;
418 playback_distance = 0;
420 if (!_io || !_io->active()) {
421 return 0;
424 check_record_status (transport_frame, can_record);
426 if (nframes == 0) {
427 return 0;
430 Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
432 if (!sm.locked()) {
433 return 1;
436 adjust_capture_position = 0;
438 for (chan = c->begin(); chan != c->end(); ++chan) {
439 (*chan)->current_capture_buffer = 0;
440 (*chan)->current_playback_buffer = 0;
443 // Safeguard against situations where process() goes haywire when autopunching
444 // and last_recordable_frame < first_recordable_frame
446 if (last_recordable_frame < first_recordable_frame) {
447 last_recordable_frame = max_framepos;
450 if (record_enabled()) {
452 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
453 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
455 if (rec_nframes && !was_recording) {
456 capture_captured = 0;
457 was_recording = true;
461 if (can_record && !_last_capture_sources.empty()) {
462 _last_capture_sources.clear ();
465 if (rec_nframes) {
467 uint32_t limit = _io->n_ports ().n_audio();
469 /* one or more ports could already have been removed from _io, but our
470 channel setup hasn't yet been updated. prevent us from trying to
471 use channels that correspond to missing ports. note that the
472 process callback (from which this is called) is always atomic
473 with respect to port removal/addition.
476 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
478 ChannelInfo* chaninfo (*chan);
480 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
482 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
484 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
486 /* note: grab the entire port buffer, but only copy what we were supposed to
487 for recording, and use rec_offset
490 AudioPort* const ap = _io->audio (n);
491 assert(ap);
492 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
493 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
496 } else {
498 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
500 if (rec_nframes > total) {
501 DiskOverrun ();
502 goto out;
505 AudioPort* const ap = _io->audio (n);
506 assert(ap);
508 Sample* buf = ap->get_audio_buffer(nframes).data();
509 framecnt_t first = chaninfo->capture_vector.len[0];
511 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
512 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
513 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
514 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
516 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
520 } else {
522 if (was_recording) {
523 finish_capture (rec_monitors_input, c);
528 if (rec_nframes) {
530 /* data will be written to disk */
532 if (rec_nframes == nframes && rec_offset == 0) {
534 for (chan = c->begin(); chan != c->end(); ++chan) {
535 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
538 playback_distance = nframes;
540 } else {
543 /* we can't use the capture buffer as the playback buffer, because
544 we recorded only a part of the current process' cycle data
545 for capture.
548 collect_playback = true;
551 adjust_capture_position = rec_nframes;
553 } else if (can_record && record_enabled()) {
555 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
557 for (chan = c->begin(); chan != c->end(); ++chan) {
558 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
561 playback_distance = nframes;
563 } else {
565 collect_playback = true;
568 if (collect_playback) {
570 /* we're doing playback */
572 framecnt_t necessary_samples;
574 /* no varispeed playback if we're recording, because the output .... TBD */
576 if (rec_nframes == 0 && _actual_speed != 1.0f) {
577 necessary_samples = (framecnt_t) floor ((nframes * fabs (_actual_speed))) + 1;
578 } else {
579 necessary_samples = nframes;
582 for (chan = c->begin(); chan != c->end(); ++chan) {
583 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
586 n = 0;
588 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
590 ChannelInfo* chaninfo (*chan);
592 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
594 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
596 } else {
597 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
599 if (necessary_samples > total) {
600 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
601 cerr << "underrun for " << _name << endl;
602 DiskUnderrun ();
603 goto out;
605 } else {
607 memcpy ((char *) chaninfo->playback_wrap_buffer,
608 chaninfo->playback_vector.buf[0],
609 chaninfo->playback_vector.len[0] * sizeof (Sample));
610 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
611 chaninfo->playback_vector.buf[1],
612 (necessary_samples - chaninfo->playback_vector.len[0])
613 * sizeof (Sample));
615 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
620 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
621 process_varispeed_playback(nframes, c);
622 } else {
623 playback_distance = nframes;
626 _speed = _target_speed;
630 ret = 0;
632 if (commit (nframes)) {
633 need_butler = true;
636 out:
637 return ret;
640 void
641 AudioDiskstream::process_varispeed_playback (pframes_t nframes, boost::shared_ptr<ChannelList> c)
643 ChannelList::iterator chan;
645 interpolation.set_speed (_target_speed);
647 int channel = 0;
648 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
649 ChannelInfo* chaninfo (*chan);
651 playback_distance = interpolation.interpolate (
652 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
654 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
658 bool
659 AudioDiskstream::commit (framecnt_t /* nframes */)
661 bool need_butler = false;
663 if (!_io || !_io->active()) {
664 return false;
667 if (_actual_speed < 0.0) {
668 playback_sample -= playback_distance;
669 } else {
670 playback_sample += playback_distance;
673 boost::shared_ptr<ChannelList> c = channels.reader();
674 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
676 (*chan)->playback_buf->increment_read_ptr (playback_distance);
678 if (adjust_capture_position) {
679 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
683 if (adjust_capture_position != 0) {
684 capture_captured += adjust_capture_position;
685 adjust_capture_position = 0;
688 if (c->empty()) {
689 return false;
692 if (_slaved) {
693 if (_io && _io->active()) {
694 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
695 } else {
696 need_butler = false;
698 } else {
699 if (_io && _io->active()) {
700 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
701 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
702 } else {
703 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
707 return need_butler;
710 void
711 AudioDiskstream::set_pending_overwrite (bool yn)
713 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
715 _pending_overwrite = yn;
717 overwrite_frame = playback_sample;
719 boost::shared_ptr<ChannelList> c = channels.reader ();
720 if (!c->empty ()) {
721 overwrite_offset = c->front()->playback_buf->get_read_ptr();
726 AudioDiskstream::overwrite_existing_buffers ()
728 boost::shared_ptr<ChannelList> c = channels.reader();
729 if (c->empty ()) {
730 _pending_overwrite = false;
731 return 0;
734 Sample* mixdown_buffer;
735 float* gain_buffer;
736 int ret = -1;
737 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
739 overwrite_queued = false;
741 /* assume all are the same size */
742 framecnt_t size = c->front()->playback_buf->bufsize();
744 mixdown_buffer = new Sample[size];
745 gain_buffer = new float[size];
747 /* reduce size so that we can fill the buffer correctly (ringbuffers
748 can only handle size-1, otherwise they appear to be empty)
750 size--;
752 uint32_t n=0;
753 framepos_t start;
755 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
757 start = overwrite_frame;
758 framecnt_t cnt = size;
760 /* to fill the buffer without resetting the playback sample, we need to
761 do it one or two chunks (normally two).
763 |----------------------------------------------------------------------|
766 overwrite_offset
767 |<- second chunk->||<----------------- first chunk ------------------>|
771 framecnt_t to_read = size - overwrite_offset;
773 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
774 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
775 _id, size, playback_sample) << endmsg;
776 goto out;
779 if (cnt > to_read) {
781 cnt -= to_read;
783 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
784 start, cnt, *chan, n, reversed)) {
785 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
786 _id, size, playback_sample) << endmsg;
787 goto out;
792 ret = 0;
794 out:
795 _pending_overwrite = false;
796 delete [] gain_buffer;
797 delete [] mixdown_buffer;
798 return ret;
802 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
804 uint32_t n;
805 int ret = -1;
806 ChannelList::iterator chan;
807 boost::shared_ptr<ChannelList> c = channels.reader();
809 Glib::Mutex::Lock lm (state_lock);
811 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
812 (*chan)->playback_buf->reset ();
813 (*chan)->capture_buf->reset ();
816 /* can't rec-enable in destructive mode if transport is before start */
818 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
819 disengage_record_enable ();
822 playback_sample = frame;
823 file_frame = frame;
825 if (complete_refill) {
826 while ((ret = do_refill_with_alloc ()) > 0) ;
827 } else {
828 ret = do_refill_with_alloc ();
831 return ret;
835 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
837 ChannelList::iterator chan;
838 boost::shared_ptr<ChannelList> c = channels.reader();
840 for (chan = c->begin(); chan != c->end(); ++chan) {
841 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
842 return false;
845 return true;
849 AudioDiskstream::internal_playback_seek (framecnt_t distance)
851 ChannelList::iterator chan;
852 boost::shared_ptr<ChannelList> c = channels.reader();
854 for (chan = c->begin(); chan != c->end(); ++chan) {
855 (*chan)->playback_buf->increment_read_ptr (distance);
858 if (first_recordable_frame < max_framepos) {
859 first_recordable_frame += distance;
861 playback_sample += distance;
863 return 0;
867 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
868 framepos_t& start, framecnt_t cnt,
869 ChannelInfo* /*channel_info*/, int channel, bool reversed)
871 framecnt_t this_read = 0;
872 bool reloop = false;
873 framepos_t loop_end = 0;
874 framepos_t loop_start = 0;
875 framecnt_t offset = 0;
876 Location *loc = 0;
878 /* XXX we don't currently play loops in reverse. not sure why */
880 if (!reversed) {
882 framecnt_t loop_length = 0;
884 /* Make the use of a Location atomic for this read operation.
886 Note: Locations don't get deleted, so all we care about
887 when I say "atomic" is that we are always pointing to
888 the same one and using a start/length values obtained
889 just once.
892 if ((loc = loop_location) != 0) {
893 loop_start = loc->start();
894 loop_end = loc->end();
895 loop_length = loop_end - loop_start;
898 /* if we are looping, ensure that the first frame we read is at the correct
899 position within the loop.
902 if (loc && start >= loop_end) {
903 //cerr << "start adjusted from " << start;
904 start = loop_start + ((start - loop_start) % loop_length);
905 //cerr << "to " << start << endl;
908 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
911 if (reversed) {
912 start -= cnt;
915 while (cnt) {
917 /* take any loop into account. we can't read past the end of the loop. */
919 if (loc && (loop_end - start < cnt)) {
920 this_read = loop_end - start;
921 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
922 reloop = true;
923 } else {
924 reloop = false;
925 this_read = cnt;
928 if (this_read == 0) {
929 break;
932 this_read = min(cnt,this_read);
934 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
935 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
936 start) << endmsg;
937 return -1;
940 _read_data_count = _playlist->read_data_count();
942 if (reversed) {
944 swap_by_ptr (buf, buf + this_read - 1);
946 } else {
948 /* if we read to the end of the loop, go back to the beginning */
950 if (reloop) {
951 start = loop_start;
952 } else {
953 start += this_read;
957 cnt -= this_read;
958 offset += this_read;
961 return 0;
965 AudioDiskstream::do_refill_with_alloc ()
967 Sample* mix_buf = new Sample[disk_io_chunk_frames];
968 float* gain_buf = new float[disk_io_chunk_frames];
970 int ret = _do_refill(mix_buf, gain_buf);
972 delete [] mix_buf;
973 delete [] gain_buf;
975 return ret;
979 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
981 int32_t ret = 0;
982 framecnt_t to_read;
983 RingBufferNPT<Sample>::rw_vector vector;
984 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
985 framecnt_t total_space;
986 framecnt_t zero_fill;
987 uint32_t chan_n;
988 ChannelList::iterator i;
989 boost::shared_ptr<ChannelList> c = channels.reader();
990 framecnt_t ts;
992 if (c->empty()) {
993 return 0;
996 assert(mixdown_buffer);
997 assert(gain_buffer);
999 vector.buf[0] = 0;
1000 vector.len[0] = 0;
1001 vector.buf[1] = 0;
1002 vector.len[1] = 0;
1004 c->front()->playback_buf->get_write_vector (&vector);
1006 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1007 return 0;
1010 /* if there are 2+ chunks of disk i/o possible for
1011 this track, let the caller know so that it can arrange
1012 for us to be called again, ASAP.
1015 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1016 ret = 1;
1019 /* if we're running close to normal speed and there isn't enough
1020 space to do disk_io_chunk_frames of I/O, then don't bother.
1022 at higher speeds, just do it because the sync between butler
1023 and audio thread may not be good enough.
1026 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1027 return 0;
1030 /* when slaved, don't try to get too close to the read pointer. this
1031 leaves space for the buffer reversal to have something useful to
1032 work with.
1035 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1036 return 0;
1039 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1041 total_space = min (disk_io_chunk_frames, total_space);
1043 if (reversed) {
1045 if (file_frame == 0) {
1047 /* at start: nothing to do but fill with silence */
1049 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1051 ChannelInfo* chan (*i);
1052 chan->playback_buf->get_write_vector (&vector);
1053 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1054 if (vector.len[1]) {
1055 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1057 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1059 return 0;
1062 if (file_frame < total_space) {
1064 /* too close to the start: read what we can,
1065 and then zero fill the rest
1068 zero_fill = total_space - file_frame;
1069 total_space = file_frame;
1071 } else {
1073 zero_fill = 0;
1076 } else {
1078 if (file_frame == max_framepos) {
1080 /* at end: nothing to do but fill with silence */
1082 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1084 ChannelInfo* chan (*i);
1085 chan->playback_buf->get_write_vector (&vector);
1086 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1087 if (vector.len[1]) {
1088 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1090 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1092 return 0;
1095 if (file_frame > max_framepos - total_space) {
1097 /* to close to the end: read what we can, and zero fill the rest */
1099 zero_fill = total_space - (max_framepos - file_frame);
1100 total_space = max_framepos - file_frame;
1102 } else {
1103 zero_fill = 0;
1107 framepos_t file_frame_tmp = 0;
1109 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1111 ChannelInfo* chan (*i);
1112 Sample* buf1;
1113 Sample* buf2;
1114 framecnt_t len1, len2;
1116 chan->playback_buf->get_write_vector (&vector);
1118 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1120 /* we're not going to fill the first chunk, so certainly do not bother with the
1121 other part. it won't be connected with the part we do fill, as in:
1123 .... => writable space
1124 ++++ => readable space
1125 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1127 |......|+++++++++++++|...............................|
1128 buf1 buf0
1129 ^^^^^^^^^^^^^^^
1132 So, just pretend that the buf1 part isn't there.
1136 vector.buf[1] = 0;
1137 vector.len[1] = 0;
1141 ts = total_space;
1142 file_frame_tmp = file_frame;
1144 buf1 = vector.buf[0];
1145 len1 = vector.len[0];
1146 buf2 = vector.buf[1];
1147 len2 = vector.len[1];
1149 to_read = min (ts, len1);
1150 to_read = min (to_read, disk_io_chunk_frames);
1152 assert (to_read >= 0);
1154 if (to_read) {
1156 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1157 ret = -1;
1158 goto out;
1161 chan->playback_buf->increment_write_ptr (to_read);
1162 ts -= to_read;
1165 to_read = min (ts, len2);
1167 if (to_read) {
1169 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1170 so read some or all of vector.len[1] as well.
1173 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1174 ret = -1;
1175 goto out;
1178 chan->playback_buf->increment_write_ptr (to_read);
1181 if (zero_fill) {
1182 /* do something */
1187 file_frame = file_frame_tmp;
1188 assert (file_frame >= 0);
1190 out:
1192 return ret;
1195 /** Flush pending data to disk.
1197 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1198 * of data to disk. it will never write more than that. If it writes that
1199 * much and there is more than that waiting to be written, it will return 1,
1200 * otherwise 0 on success or -1 on failure.
1202 * If there is less than disk_io_chunk_frames to be written, no data will be
1203 * written at all unless @a force_flush is true.
1206 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1208 uint32_t to_write;
1209 int32_t ret = 0;
1210 RingBufferNPT<Sample>::rw_vector vector;
1211 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1212 framecnt_t total;
1214 _write_data_count = 0;
1216 transvec.buf[0] = 0;
1217 transvec.buf[1] = 0;
1218 vector.buf[0] = 0;
1219 vector.buf[1] = 0;
1221 boost::shared_ptr<ChannelList> c = channels.reader();
1222 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1224 (*chan)->capture_buf->get_read_vector (&vector);
1226 total = vector.len[0] + vector.len[1];
1228 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1229 goto out;
1232 /* if there are 2+ chunks of disk i/o possible for
1233 this track, let the caller know so that it can arrange
1234 for us to be called again, ASAP.
1236 if we are forcing a flush, then if there is* any* extra
1237 work, let the caller know.
1239 if we are no longer recording and there is any extra work,
1240 let the caller know too.
1243 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1244 ret = 1;
1247 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1249 // check the transition buffer when recording destructive
1250 // important that we get this after the capture buf
1252 if (destructive()) {
1253 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1254 size_t transcount = transvec.len[0] + transvec.len[1];
1255 size_t ti;
1257 for (ti=0; ti < transcount; ++ti) {
1258 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1260 if (captrans.type == CaptureStart) {
1261 // by definition, the first data we got above represents the given capture pos
1263 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1264 (*chan)->curr_capture_cnt = 0;
1266 } else if (captrans.type == CaptureEnd) {
1268 // capture end, the capture_val represents total frames in capture
1270 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1272 // shorten to make the write a perfect fit
1273 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1275 if (nto_write < to_write) {
1276 ret = 1; // should we?
1278 to_write = nto_write;
1280 (*chan)->write_source->mark_capture_end ();
1282 // increment past this transition, but go no further
1283 ++ti;
1284 break;
1286 else {
1287 // actually ends just beyond this chunk, so force more work
1288 ret = 1;
1289 break;
1294 if (ti > 0) {
1295 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1299 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1300 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1301 return -1;
1304 (*chan)->capture_buf->increment_read_ptr (to_write);
1305 (*chan)->curr_capture_cnt += to_write;
1307 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1309 /* we wrote all of vector.len[0] but it wasn't an entire
1310 disk_io_chunk_frames of data, so arrange for some part
1311 of vector.len[1] to be flushed to disk as well.
1314 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1316 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1317 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1318 return -1;
1321 _write_data_count += (*chan)->write_source->write_data_count();
1323 (*chan)->capture_buf->increment_read_ptr (to_write);
1324 (*chan)->curr_capture_cnt += to_write;
1328 out:
1329 return ret;
1332 void
1333 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1335 uint32_t buffer_position;
1336 bool more_work = true;
1337 int err = 0;
1338 boost::shared_ptr<AudioRegion> region;
1339 framecnt_t total_capture;
1340 SourceList srcs;
1341 SourceList::iterator src;
1342 ChannelList::iterator chan;
1343 vector<CaptureInfo*>::iterator ci;
1344 boost::shared_ptr<ChannelList> c = channels.reader();
1345 uint32_t n = 0;
1346 bool mark_write_completed = false;
1348 finish_capture (true, c);
1350 /* butler is already stopped, but there may be work to do
1351 to flush remaining data to disk.
1354 while (more_work && !err) {
1355 switch (do_flush (TransportContext, true)) {
1356 case 0:
1357 more_work = false;
1358 break;
1359 case 1:
1360 break;
1361 case -1:
1362 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1363 err++;
1367 /* XXX is there anything we can do if err != 0 ? */
1368 Glib::Mutex::Lock lm (capture_info_lock);
1370 if (capture_info.empty()) {
1371 return;
1374 if (abort_capture) {
1376 if (destructive()) {
1377 goto outout;
1380 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1382 if ((*chan)->write_source) {
1384 (*chan)->write_source->mark_for_remove ();
1385 (*chan)->write_source->drop_references ();
1386 (*chan)->write_source.reset ();
1389 /* new source set up in "out" below */
1392 goto out;
1395 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1396 total_capture += (*ci)->frames;
1399 /* figure out the name for this take */
1401 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1403 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1405 if (s) {
1406 srcs.push_back (s);
1407 s->update_header (capture_info.front()->start, when, twhen);
1408 s->set_captured_for (_name.val());
1409 s->mark_immutable ();
1411 if (Config->get_auto_analyse_audio()) {
1412 Analyser::queue_source_for_analysis (s, true);
1417 /* destructive tracks have a single, never changing region */
1419 if (destructive()) {
1421 /* send a signal that any UI can pick up to do the right thing. there is
1422 a small problem here in that a UI may need the peak data to be ready
1423 for the data that was recorded and this isn't interlocked with that
1424 process. this problem is deferred to the UI.
1427 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1429 } else {
1431 string whole_file_region_name;
1432 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1434 /* Register a new region with the Session that
1435 describes the entire source. Do this first
1436 so that any sub-regions will obviously be
1437 children of this one (later!)
1440 try {
1441 PropertyList plist;
1443 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1444 plist.add (Properties::length, total_capture);
1445 plist.add (Properties::name, whole_file_region_name);
1446 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1447 rx->set_automatic (true);
1448 rx->set_whole_file (true);
1450 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1451 region->special_set_position (capture_info.front()->start);
1455 catch (failed_constructor& err) {
1456 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1457 /* XXX what now? */
1460 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1462 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1464 _playlist->clear_changes ();
1465 _playlist->freeze ();
1467 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1469 string region_name;
1471 RegionFactory::region_name (region_name, whole_file_region_name, false);
1473 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1474 _name, (*ci)->start, (*ci)->frames, region_name));
1476 try {
1478 PropertyList plist;
1480 plist.add (Properties::start, buffer_position);
1481 plist.add (Properties::length, (*ci)->frames);
1482 plist.add (Properties::name, region_name);
1484 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1485 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1488 catch (failed_constructor& err) {
1489 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1490 continue; /* XXX is this OK? */
1493 i_am_the_modifier++;
1495 if (_playlist->explicit_relayering()) {
1496 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1497 should end up on. Put it at the top.
1499 region->set_layer (_playlist->top_layer() + 1);
1500 region->set_pending_explicit_relayer (true);
1503 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1504 i_am_the_modifier--;
1506 buffer_position += (*ci)->frames;
1509 _playlist->thaw ();
1510 _session.add_command (new StatefulDiffCommand (_playlist));
1513 mark_write_completed = true;
1515 out:
1516 reset_write_sources (mark_write_completed);
1518 outout:
1520 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1521 delete *ci;
1524 capture_info.clear ();
1525 capture_start_frame = 0;
1528 void
1529 AudioDiskstream::transport_looped (framepos_t transport_frame)
1531 if (was_recording) {
1532 // all we need to do is finish this capture, with modified capture length
1533 boost::shared_ptr<ChannelList> c = channels.reader();
1535 // adjust the capture length knowing that the data will be recorded to disk
1536 // only necessary after the first loop where we're recording
1537 if (capture_info.size() == 0) {
1538 capture_captured += _capture_offset;
1540 if (_alignment_style == ExistingMaterial) {
1541 capture_captured += _session.worst_output_latency();
1542 } else {
1543 capture_captured += _roll_delay;
1547 finish_capture (true, c);
1549 // the next region will start recording via the normal mechanism
1550 // we'll set the start position to the current transport pos
1551 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1552 capture_start_frame = transport_frame;
1553 first_recordable_frame = transport_frame; // mild lie
1554 last_recordable_frame = max_framepos;
1555 was_recording = true;
1557 if (recordable() && destructive()) {
1558 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1560 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1561 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1563 if (transvec.len[0] > 0) {
1564 transvec.buf[0]->type = CaptureStart;
1565 transvec.buf[0]->capture_val = capture_start_frame;
1566 (*chan)->capture_transition_buf->increment_write_ptr(1);
1568 else {
1569 // bad!
1570 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1571 << endmsg;
1579 void
1580 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1582 was_recording = false;
1583 first_recordable_frame = max_framepos;
1584 last_recordable_frame = max_framepos;
1586 if (capture_captured == 0) {
1587 return;
1590 if (recordable() && destructive()) {
1591 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1593 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1594 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1596 if (transvec.len[0] > 0) {
1597 transvec.buf[0]->type = CaptureEnd;
1598 transvec.buf[0]->capture_val = capture_captured;
1599 (*chan)->capture_transition_buf->increment_write_ptr(1);
1601 else {
1602 // bad!
1603 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1609 CaptureInfo* ci = new CaptureInfo;
1611 ci->start = capture_start_frame;
1612 ci->frames = capture_captured;
1614 /* XXX theoretical race condition here. Need atomic exchange ?
1615 However, the circumstances when this is called right
1616 now (either on record-disable or transport_stopped)
1617 mean that no actual race exists. I think ...
1618 We now have a capture_info_lock, but it is only to be used
1619 to synchronize in the transport_stop and the capture info
1620 accessors, so that invalidation will not occur (both non-realtime).
1623 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1625 capture_info.push_back (ci);
1626 capture_captured = 0;
1628 /* now we've finished a capture, reset first_recordable_frame for next time */
1629 first_recordable_frame = max_framepos;
1632 void
1633 AudioDiskstream::set_record_enabled (bool yn)
1635 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1636 return;
1639 /* can't rec-enable in destructive mode if transport is before start */
1641 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1642 return;
1645 /* yes, i know that this not proof against race conditions, but its
1646 good enough. i think.
1649 if (record_enabled() != yn) {
1650 if (yn) {
1651 engage_record_enable ();
1652 } else {
1653 disengage_record_enable ();
1658 void
1659 AudioDiskstream::engage_record_enable ()
1661 bool rolling = _session.transport_speed() != 0.0f;
1662 boost::shared_ptr<ChannelList> c = channels.reader();
1664 g_atomic_int_set (&_record_enabled, 1);
1665 capturing_sources.clear ();
1667 if (Config->get_monitoring_model() == HardwareMonitoring) {
1669 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1670 (*chan)->source.ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1671 capturing_sources.push_back ((*chan)->write_source);
1672 (*chan)->write_source->mark_streaming_write_started ();
1675 } else {
1676 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1677 capturing_sources.push_back ((*chan)->write_source);
1678 (*chan)->write_source->mark_streaming_write_started ();
1682 RecordEnableChanged (); /* EMIT SIGNAL */
1685 void
1686 AudioDiskstream::disengage_record_enable ()
1688 g_atomic_int_set (&_record_enabled, 0);
1689 boost::shared_ptr<ChannelList> c = channels.reader();
1690 if (Config->get_monitoring_model() == HardwareMonitoring) {
1691 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1692 (*chan)->source.ensure_monitor_input (false);
1695 capturing_sources.clear ();
1696 RecordEnableChanged (); /* EMIT SIGNAL */
1699 XMLNode&
1700 AudioDiskstream::get_state ()
1702 XMLNode& node (Diskstream::get_state());
1703 char buf[64] = "";
1704 LocaleGuard lg (X_("POSIX"));
1706 boost::shared_ptr<ChannelList> c = channels.reader();
1707 snprintf (buf, sizeof(buf), "%zd", c->size());
1708 node.add_property ("channels", buf);
1710 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1712 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1713 XMLNode* cs_grandchild;
1715 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1716 cs_grandchild = new XMLNode (X_("file"));
1717 cs_grandchild->add_property (X_("path"), (*i)->path());
1718 cs_child->add_child_nocopy (*cs_grandchild);
1721 /* store the location where capture will start */
1723 Location* pi;
1725 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1726 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1727 } else {
1728 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1731 cs_child->add_property (X_("at"), buf);
1732 node.add_child_nocopy (*cs_child);
1735 return node;
1739 AudioDiskstream::set_state (const XMLNode& node, int version)
1741 const XMLProperty* prop;
1742 XMLNodeList nlist = node.children();
1743 XMLNodeIterator niter;
1744 uint32_t nchans = 1;
1745 XMLNode* capture_pending_node = 0;
1746 LocaleGuard lg (X_("POSIX"));
1748 /* prevent write sources from being created */
1750 in_set_state = true;
1752 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1753 if ((*niter)->name() == IO::state_node_name) {
1754 deprecated_io_node = new XMLNode (**niter);
1757 if ((*niter)->name() == X_("CapturingSources")) {
1758 capture_pending_node = *niter;
1762 if (Diskstream::set_state (node, version)) {
1763 return -1;
1766 if ((prop = node.property ("channels")) != 0) {
1767 nchans = atoi (prop->value().c_str());
1770 // create necessary extra channels
1771 // we are always constructed with one and we always need one
1773 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1775 if (nchans > _n_channels.n_audio()) {
1777 add_channel (nchans - _n_channels.n_audio());
1778 IO::PortCountChanged(_n_channels);
1780 } else if (nchans < _n_channels.n_audio()) {
1782 remove_channel (_n_channels.n_audio() - nchans);
1787 if (!destructive() && capture_pending_node) {
1788 /* destructive streams have one and only one source per channel,
1789 and so they never end up in pending capture in any useful
1790 sense.
1792 use_pending_capture_data (*capture_pending_node);
1795 in_set_state = false;
1797 /* make sure this is clear before we do anything else */
1799 capturing_sources.clear ();
1801 /* write sources are handled when we handle the input set
1802 up of the IO that owns this DS (::non_realtime_input_change())
1805 return 0;
1809 AudioDiskstream::use_new_write_source (uint32_t n)
1811 boost::shared_ptr<ChannelList> c = channels.reader();
1813 if (!recordable()) {
1814 return 1;
1817 if (n >= c->size()) {
1818 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1819 return -1;
1822 ChannelInfo* chan = (*c)[n];
1824 try {
1825 if ((chan->write_source = _session.create_audio_source_for_session (
1826 n_channels().n_audio(), name(), n, destructive())) == 0) {
1827 throw failed_constructor();
1831 catch (failed_constructor &err) {
1832 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1833 chan->write_source.reset ();
1834 return -1;
1837 /* do not remove destructive files even if they are empty */
1839 chan->write_source->set_allow_remove_if_empty (!destructive());
1841 return 0;
1844 list<boost::shared_ptr<Source> >
1845 AudioDiskstream::steal_write_sources()
1847 /* not possible to steal audio write sources */
1848 list<boost::shared_ptr<Source> > ret;
1849 return ret;
1852 void
1853 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1855 ChannelList::iterator chan;
1856 boost::shared_ptr<ChannelList> c = channels.reader();
1857 uint32_t n;
1859 if (!_session.writable() || !recordable()) {
1860 return;
1863 capturing_sources.clear ();
1865 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1867 if (!destructive()) {
1869 if ((*chan)->write_source) {
1871 if (mark_write_complete) {
1872 (*chan)->write_source->mark_streaming_write_completed ();
1873 (*chan)->write_source->done_with_peakfile_writes ();
1876 if ((*chan)->write_source->removable()) {
1877 (*chan)->write_source->mark_for_remove ();
1878 (*chan)->write_source->drop_references ();
1881 (*chan)->write_source.reset ();
1884 use_new_write_source (n);
1886 if (record_enabled()) {
1887 capturing_sources.push_back ((*chan)->write_source);
1890 } else {
1892 if ((*chan)->write_source == 0) {
1893 use_new_write_source (n);
1898 if (destructive() && !c->empty ()) {
1900 /* we now have all our write sources set up, so create the
1901 playlist's single region.
1904 if (_playlist->empty()) {
1905 setup_destructive_playlist ();
1910 void
1911 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1913 if (_session.get_block_size() > speed_buffer_size) {
1914 speed_buffer_size = _session.get_block_size();
1915 boost::shared_ptr<ChannelList> c = channels.reader();
1917 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1918 if ((*chan)->speed_buffer)
1919 delete [] (*chan)->speed_buffer;
1920 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1923 allocate_temporary_buffers ();
1926 void
1927 AudioDiskstream::allocate_temporary_buffers ()
1929 /* make sure the wrap buffer is at least large enough to deal
1930 with the speeds up to 1.2, to allow for micro-variation
1931 when slaving to MTC, Timecode etc.
1934 double const sp = max (fabsf (_actual_speed), 1.2f);
1935 framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() * sp) + 1;
1937 if (required_wrap_size > wrap_buffer_size) {
1939 boost::shared_ptr<ChannelList> c = channels.reader();
1941 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1942 if ((*chan)->playback_wrap_buffer)
1943 delete [] (*chan)->playback_wrap_buffer;
1944 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
1945 if ((*chan)->capture_wrap_buffer)
1946 delete [] (*chan)->capture_wrap_buffer;
1947 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
1950 wrap_buffer_size = required_wrap_size;
1954 void
1955 AudioDiskstream::monitor_input (bool yn)
1957 boost::shared_ptr<ChannelList> c = channels.reader();
1959 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1960 (*chan)->source.ensure_monitor_input (yn);
1964 void
1965 AudioDiskstream::set_align_style_from_io ()
1967 bool have_physical = false;
1969 if (_alignment_choice != Automatic) {
1970 return;
1973 if (_io == 0) {
1974 return;
1977 get_input_sources ();
1979 boost::shared_ptr<ChannelList> c = channels.reader();
1981 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1982 if ((*chan)->source.is_physical ()) {
1983 have_physical = true;
1984 break;
1988 if (have_physical) {
1989 set_align_style (ExistingMaterial);
1990 } else {
1991 set_align_style (CaptureTime);
1996 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
1998 while (how_many--) {
1999 c->push_back (new ChannelInfo(
2000 _session.butler()->audio_diskstream_playback_buffer_size(),
2001 _session.butler()->audio_diskstream_capture_buffer_size(),
2002 speed_buffer_size, wrap_buffer_size));
2003 interpolation.add_channel_to (
2004 _session.butler()->audio_diskstream_playback_buffer_size(),
2005 speed_buffer_size);
2008 _n_channels.set(DataType::AUDIO, c->size());
2010 return 0;
2014 AudioDiskstream::add_channel (uint32_t how_many)
2016 RCUWriter<ChannelList> writer (channels);
2017 boost::shared_ptr<ChannelList> c = writer.get_copy();
2019 return add_channel_to (c, how_many);
2023 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2025 while (how_many-- && !c->empty()) {
2026 delete c->back();
2027 c->pop_back();
2028 interpolation.remove_channel_from ();
2031 _n_channels.set(DataType::AUDIO, c->size());
2033 return 0;
2037 AudioDiskstream::remove_channel (uint32_t how_many)
2039 RCUWriter<ChannelList> writer (channels);
2040 boost::shared_ptr<ChannelList> c = writer.get_copy();
2042 return remove_channel_from (c, how_many);
2045 float
2046 AudioDiskstream::playback_buffer_load () const
2048 boost::shared_ptr<ChannelList> c = channels.reader();
2050 if (c->empty ()) {
2051 return 0;
2054 return (float) ((double) c->front()->playback_buf->read_space()/
2055 (double) c->front()->playback_buf->bufsize());
2058 float
2059 AudioDiskstream::capture_buffer_load () const
2061 boost::shared_ptr<ChannelList> c = channels.reader();
2063 if (c->empty ()) {
2064 return 0;
2067 return (float) ((double) c->front()->capture_buf->write_space()/
2068 (double) c->front()->capture_buf->bufsize());
2072 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2074 const XMLProperty* prop;
2075 XMLNodeList nlist = node.children();
2076 XMLNodeIterator niter;
2077 boost::shared_ptr<AudioFileSource> fs;
2078 boost::shared_ptr<AudioFileSource> first_fs;
2079 SourceList pending_sources;
2080 framepos_t position;
2082 if ((prop = node.property (X_("at"))) == 0) {
2083 return -1;
2086 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2087 return -1;
2090 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2091 if ((*niter)->name() == X_("file")) {
2093 if ((prop = (*niter)->property (X_("path"))) == 0) {
2094 continue;
2097 // This protects sessions from errant CapturingSources in stored sessions
2098 struct stat sbuf;
2099 if (stat (prop->value().c_str(), &sbuf)) {
2100 continue;
2103 try {
2104 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2105 SourceFactory::createWritable (
2106 DataType::AUDIO, _session,
2107 prop->value(), string(), false, _session.frame_rate()));
2110 catch (failed_constructor& err) {
2111 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2112 _name, prop->value())
2113 << endmsg;
2114 return -1;
2117 pending_sources.push_back (fs);
2119 if (first_fs == 0) {
2120 first_fs = fs;
2123 fs->set_captured_for (_name.val());
2127 if (pending_sources.size() == 0) {
2128 /* nothing can be done */
2129 return 1;
2132 if (pending_sources.size() != _n_channels.n_audio()) {
2133 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2134 << endmsg;
2135 return -1;
2138 boost::shared_ptr<AudioRegion> region;
2140 try {
2142 PropertyList plist;
2144 plist.add (Properties::start, 0);
2145 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2146 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2148 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2150 region->set_automatic (true);
2151 region->set_whole_file (true);
2152 region->special_set_position (0);
2155 catch (failed_constructor& err) {
2156 error << string_compose (
2157 _("%1: cannot create whole-file region from pending capture sources"),
2158 _name) << endmsg;
2160 return -1;
2163 _playlist->add_region (region, position);
2165 return 0;
2169 AudioDiskstream::set_non_layered (bool yn)
2171 if (yn != non_layered()) {
2173 if (yn) {
2174 _flags = Flag (_flags | NonLayered);
2175 } else {
2176 _flags = Flag (_flags & ~NonLayered);
2180 return 0;
2184 AudioDiskstream::set_destructive (bool yn)
2186 if (yn != destructive()) {
2188 if (yn) {
2189 bool bounce_ignored;
2190 /* requestor should already have checked this and
2191 bounced if necessary and desired
2193 if (!can_become_destructive (bounce_ignored)) {
2194 return -1;
2196 _flags = Flag (_flags | Destructive);
2197 use_destructive_playlist ();
2198 } else {
2199 _flags = Flag (_flags & ~Destructive);
2200 reset_write_sources (true, true);
2204 return 0;
2207 bool
2208 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2210 if (!_playlist) {
2211 requires_bounce = false;
2212 return false;
2215 /* is there only one region ? */
2217 if (_playlist->n_regions() != 1) {
2218 requires_bounce = true;
2219 return false;
2222 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2223 if (!first) {
2224 requires_bounce = false;
2225 return true;
2228 /* do the source(s) for the region cover the session start position ? */
2230 if (first->position() != _session.current_start_frame()) {
2231 if (first->start() > _session.current_start_frame()) {
2232 requires_bounce = true;
2233 return false;
2237 /* is the source used by only 1 playlist ? */
2239 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2241 assert (afirst);
2243 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2244 requires_bounce = true;
2245 return false;
2248 requires_bounce = false;
2249 return true;
2252 void
2253 AudioDiskstream::adjust_playback_buffering ()
2255 boost::shared_ptr<ChannelList> c = channels.reader();
2257 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2258 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2262 void
2263 AudioDiskstream::adjust_capture_buffering ()
2265 boost::shared_ptr<ChannelList> c = channels.reader();
2267 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2268 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2272 bool
2273 AudioDiskstream::ChannelSource::is_physical () const
2275 if (name.empty()) {
2276 return false;
2279 return AudioEngine::instance()->port_is_physical (name);
2282 void
2283 AudioDiskstream::ChannelSource::ensure_monitor_input (bool yn) const
2285 if (name.empty()) {
2286 return;
2289 return AudioEngine::instance()->ensure_monitor_input (name, yn);
2292 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2294 peak_power = 0.0f;
2295 current_capture_buffer = 0;
2296 current_playback_buffer = 0;
2297 curr_capture_cnt = 0;
2299 speed_buffer = new Sample[speed_size];
2300 playback_wrap_buffer = new Sample[wrap_size];
2301 capture_wrap_buffer = new Sample[wrap_size];
2303 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2304 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2305 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2307 /* touch the ringbuffer buffers, which will cause
2308 them to be mapped into locked physical RAM if
2309 we're running with mlockall(). this doesn't do
2310 much if we're not.
2313 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2314 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2315 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2318 void
2319 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2321 delete playback_buf;
2322 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2323 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2326 void
2327 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2329 delete capture_buf;
2331 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2332 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2335 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2337 write_source.reset ();
2339 delete [] speed_buffer;
2340 speed_buffer = 0;
2342 delete [] playback_wrap_buffer;
2343 playback_wrap_buffer = 0;
2345 delete [] capture_wrap_buffer;
2346 capture_wrap_buffer = 0;
2348 delete playback_buf;
2349 playback_buf = 0;
2351 delete capture_buf;
2352 capture_buf = 0;
2354 delete capture_transition_buf;
2355 capture_transition_buf = 0;
2359 bool
2360 AudioDiskstream::set_name (string const & name)
2362 Diskstream::set_name (name);
2364 /* get a new write source so that its name reflects the new diskstream name */
2366 boost::shared_ptr<ChannelList> c = channels.reader();
2367 ChannelList::iterator i;
2368 int n = 0;
2370 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2371 use_new_write_source (n);
2374 return true;