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.
33 #include <pbd/error.h>
34 #include <pbd/basename.h>
35 #include <glibmm/thread.h>
36 #include <pbd/xml++.h>
37 #include <pbd/memento_command.h>
38 #include <pbd/enumwriter.h>
39 #include <pbd/stacktrace.h>
41 #include <ardour/ardour.h>
42 #include <ardour/audioengine.h>
43 #include <ardour/audio_diskstream.h>
44 #include <ardour/utils.h>
45 #include <ardour/configuration.h>
46 #include <ardour/audiofilesource.h>
47 #include <ardour/send.h>
48 #include <ardour/region_factory.h>
49 #include <ardour/audioplaylist.h>
50 #include <ardour/playlist_factory.h>
51 #include <ardour/cycle_timer.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/source_factory.h>
59 using namespace ARDOUR;
62 size_t AudioDiskstream::_working_buffers_size = 0;
63 Sample* AudioDiskstream::_mixdown_buffer = 0;
64 gain_t* AudioDiskstream::_gain_buffer = 0;
66 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
67 : Diskstream(sess, name, flag)
68 , deprecated_io_node(NULL)
69 , channels (new ChannelList)
71 /* prevent any write sources from being created */
81 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
82 : Diskstream(sess, node)
83 , deprecated_io_node(NULL)
84 , channels (new ChannelList)
89 if (set_state (node)) {
91 throw failed_constructor();
97 use_destructive_playlist ();
102 AudioDiskstream::init (Diskstream::Flag f)
106 /* there are no channels at this point, so these
107 two calls just get speed_buffer_size and wrap_buffer
108 size setup without duplicating their code.
111 set_block_size (_session.get_block_size());
112 allocate_temporary_buffers ();
115 assert(_n_channels == 1);
118 AudioDiskstream::~AudioDiskstream ()
123 RCUWriter<ChannelList> writer (channels);
124 boost::shared_ptr<ChannelList> c = writer.get_copy();
126 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
137 AudioDiskstream::allocate_working_buffers()
139 assert(disk_io_frames() > 0);
141 _working_buffers_size = disk_io_frames();
142 _mixdown_buffer = new Sample[_working_buffers_size];
143 _gain_buffer = new gain_t[_working_buffers_size];
147 AudioDiskstream::free_working_buffers()
149 delete [] _mixdown_buffer;
150 delete [] _gain_buffer;
151 _working_buffers_size = 0;
157 AudioDiskstream::non_realtime_input_change ()
160 Glib::Mutex::Lock lm (state_lock);
162 if (input_change_pending == NoChange) {
167 RCUWriter<ChannelList> writer (channels);
168 boost::shared_ptr<ChannelList> c = writer.get_copy();
170 _n_channels = c->size();
172 if (_io->n_inputs() > _n_channels) {
173 add_channel_to (c, _io->n_inputs() - _n_channels);
174 } else if (_io->n_inputs() < _n_channels) {
175 remove_channel_from (c, _n_channels - _io->n_inputs());
179 get_input_sources ();
180 set_capture_offset ();
182 if (first_input_change) {
183 set_align_style (_persistent_alignment_style);
184 first_input_change = false;
186 set_align_style_from_io ();
189 input_change_pending = NoChange;
191 /* implicit unlock */
194 /* reset capture files */
196 reset_write_sources (false);
198 /* now refill channel buffers */
200 if (speed() != 1.0f || speed() != -1.0f) {
201 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
203 seek (_session.transport_frame());
208 AudioDiskstream::get_input_sources ()
210 boost::shared_ptr<ChannelList> c = channels.reader();
213 ChannelList::iterator chan;
214 uint32_t ni = _io->n_inputs();
216 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
218 const char **connections = _io->input(n)->get_connections ();
220 if (connections == 0 || connections[0] == 0) {
222 if ((*chan)->source) {
223 // _source->disable_metering ();
229 (*chan)->source = _session.engine().get_port_by_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.playlist_by_name (name))) == 0) {
244 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, name));
248 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
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);
266 AudioDiskstream::use_new_playlist ()
269 boost::shared_ptr<AudioPlaylist> playlist;
271 if (!in_set_state && destructive()) {
276 newname = Playlist::bump_name (_playlist->name(), _session);
278 newname = Playlist::bump_name (_name, _session);
281 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, newname, hidden()))) != 0) {
283 playlist->set_orig_diskstream_id (id());
284 return use_playlist (playlist);
292 AudioDiskstream::use_copy_playlist ()
294 assert(audio_playlist());
300 if (_playlist == 0) {
301 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
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);
319 AudioDiskstream::setup_destructive_playlist ()
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 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
331 _playlist->add_region (region, srcs.front()->natural_position());
335 AudioDiskstream::use_destructive_playlist ()
337 /* this is called from the XML-based constructor or ::set_destructive. when called,
338 we already have a playlist and a region, but we need to
339 set up our sources for write. we use the sources associated
340 with the (presumed single, full-extent) region.
343 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
346 reset_write_sources (false, true);
350 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
353 throw failed_constructor();
356 /* be sure to stretch the region out to the maximum length */
358 region->set_length (max_frames - region->position(), this);
361 ChannelList::iterator chan;
362 boost::shared_ptr<ChannelList> c = channels.reader();
364 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
365 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
366 assert((*chan)->write_source);
367 (*chan)->write_source->set_allow_remove_if_empty (false);
369 /* this might be false if we switched modes, so force it */
371 (*chan)->write_source->set_destructive (true);
374 /* the source list will never be reset for a destructive track */
378 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
380 int possibly_recording;
383 const int transport_rolling = 0x4;
384 const int track_rec_enabled = 0x2;
385 const int global_rec_enabled = 0x1;
387 /* merge together the 3 factors that affect record status, and compute
391 rolling = _session.transport_speed() != 0.0f;
392 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
393 change = possibly_recording ^ last_possibly_recording;
395 if (possibly_recording == last_possibly_recording) {
401 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
403 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
404 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
406 /* starting to record: compute first+last frames */
408 first_recordable_frame = transport_frame + _capture_offset;
409 last_recordable_frame = max_frames;
410 capture_start_frame = transport_frame;
412 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
414 /* was stopped, now rolling (and recording) */
416 if (_alignment_style == ExistingMaterial) {
417 first_recordable_frame += _session.worst_output_latency();
419 first_recordable_frame += _roll_delay;
424 /* was rolling, but record state changed */
426 if (_alignment_style == ExistingMaterial) {
428 if (!Config->get_punch_in()) {
430 /* manual punch in happens at the correct transport frame
431 because the user hit a button. but to get alignment correct
432 we have to back up the position of the new region to the
433 appropriate spot given the roll delay.
436 capture_start_frame -= _roll_delay;
438 /* XXX paul notes (august 2005): i don't know why
442 first_recordable_frame += _capture_offset;
446 /* autopunch toggles recording at the precise
447 transport frame, and then the DS waits
448 to start recording for a time that depends
449 on the output latency.
452 first_recordable_frame += _session.worst_output_latency();
457 if (Config->get_punch_in()) {
458 first_recordable_frame += _roll_delay;
460 capture_start_frame -= _roll_delay;
466 if (recordable() && destructive()) {
467 boost::shared_ptr<ChannelList> c = channels.reader();
468 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
470 RingBufferNPT<CaptureTransition>::rw_vector transvec;
471 (*chan)->capture_transition_buf->get_write_vector(&transvec);
473 if (transvec.len[0] > 0) {
474 transvec.buf[0]->type = CaptureStart;
475 transvec.buf[0]->capture_val = capture_start_frame;
476 (*chan)->capture_transition_buf->increment_write_ptr(1);
480 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
486 } else if (!record_enabled() || !can_record) {
490 last_recordable_frame = transport_frame + _capture_offset;
492 if (_alignment_style == ExistingMaterial) {
493 last_recordable_frame += _session.worst_output_latency();
495 last_recordable_frame += _roll_delay;
499 last_possibly_recording = possibly_recording;
503 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
506 boost::shared_ptr<ChannelList> c = channels.reader();
507 ChannelList::iterator chan;
509 nframes_t rec_offset = 0;
510 nframes_t rec_nframes = 0;
511 bool nominally_recording;
512 bool re = record_enabled ();
513 bool collect_playback = false;
515 /* if we've already processed the frames corresponding to this call,
516 just return. this allows multiple routes that are taking input
517 from this diskstream to call our ::process() method, but have
518 this stuff only happen once. more commonly, it allows both
519 the AudioTrack that is using this AudioDiskstream *and* the Session
520 to call process() without problems.
527 commit_should_unlock = false;
529 check_record_status (transport_frame, nframes, can_record);
531 nominally_recording = (can_record && re);
538 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
539 must always be called as a pair. The only exception is if this function
540 returns a non-zero value, in which case, ::commit should not be called.
543 // If we can't take the state lock return.
544 if (!state_lock.trylock()) {
547 commit_should_unlock = true;
548 adjust_capture_position = 0;
550 for (chan = c->begin(); chan != c->end(); ++chan) {
551 (*chan)->current_capture_buffer = 0;
552 (*chan)->current_playback_buffer = 0;
555 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
558 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
559 if (last_recordable_frame < first_recordable_frame) {
560 last_recordable_frame = max_frames;
564 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
571 case OverlapInternal:
572 /* ---------- recrange
575 rec_nframes = nframes;
580 /* |--------| recrange
583 rec_nframes = transport_frame + nframes - first_recordable_frame;
585 rec_offset = first_recordable_frame - transport_frame;
590 /* |--------| recrange
593 rec_nframes = last_recordable_frame - transport_frame;
597 case OverlapExternal:
598 /* |--------| recrange
599 -------------- transrange
601 rec_nframes = last_recordable_frame - first_recordable_frame;
602 rec_offset = first_recordable_frame - transport_frame;
606 if (rec_nframes && !was_recording) {
607 capture_captured = 0;
608 was_recording = true;
613 if (can_record && !_last_capture_regions.empty()) {
614 _last_capture_regions.clear ();
617 if (nominally_recording || rec_nframes) {
619 uint32_t limit = _io->n_inputs ();
621 /* one or more ports could already have been removed from _io, but our
622 channel setup hasn't yet been updated. prevent us from trying to
623 use channels that correspond to missing ports. note that the
624 process callback (from which this is called) is always atomic
625 with respect to port removal/addition.
628 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
630 ChannelInfo* chaninfo (*chan);
632 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
634 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
636 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
638 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
642 memcpy (chaninfo->current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
646 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
648 if (rec_nframes > total) {
653 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
654 nframes_t first = chaninfo->capture_vector.len[0];
656 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
657 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
658 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
659 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
661 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
668 finish_capture (rec_monitors_input, c);
675 /* data will be written to disk */
677 if (rec_nframes == nframes && rec_offset == 0) {
679 for (chan = c->begin(); chan != c->end(); ++chan) {
680 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
683 playback_distance = nframes;
688 /* we can't use the capture buffer as the playback buffer, because
689 we recorded only a part of the current process' cycle data
693 collect_playback = true;
696 adjust_capture_position = rec_nframes;
698 } else if (nominally_recording) {
700 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
702 for (chan = c->begin(); chan != c->end(); ++chan) {
703 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
706 playback_distance = nframes;
710 collect_playback = true;
713 if (collect_playback) {
715 /* we're doing playback */
717 nframes_t necessary_samples;
719 /* no varispeed playback if we're recording, because the output .... TBD */
721 if (rec_nframes == 0 && _actual_speed != 1.0f) {
722 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
724 necessary_samples = nframes;
727 for (chan = c->begin(); chan != c->end(); ++chan) {
728 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
733 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
735 ChannelInfo* chaninfo (*chan);
737 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
739 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
742 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
744 if (necessary_samples > total) {
750 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
751 chaninfo->playback_vector.len[0] * sizeof (Sample));
752 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
753 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
755 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
760 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
762 uint64_t phase = last_phase;
766 // Linearly interpolate into the alt buffer
767 // using 40.24 fixp maths (swh)
769 if (phi != target_phi) {
770 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
775 for (chan = c->begin(); chan != c->end(); ++chan) {
778 ChannelInfo* chaninfo (*chan);
783 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
785 fr = (phase & 0xFFFFFF) / 16777216.0f;
786 chaninfo->speed_buffer[outsample] =
787 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
788 chaninfo->current_playback_buffer[i+1] * fr;
789 phase += phi + phi_delta;
792 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
795 playback_distance = i; // + 1;
796 last_phase = (phase & 0xFFFFFF);
799 playback_distance = nframes;
812 /* we're exiting with failure, so ::commit will not
813 be called. unlock the state lock.
816 commit_should_unlock = false;
824 AudioDiskstream::commit (nframes_t nframes)
826 bool need_butler = false;
828 if (_actual_speed < 0.0) {
829 playback_sample -= playback_distance;
831 playback_sample += playback_distance;
834 boost::shared_ptr<ChannelList> c = channels.reader();
835 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
837 (*chan)->playback_buf->increment_read_ptr (playback_distance);
839 if (adjust_capture_position) {
840 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
844 if (adjust_capture_position != 0) {
845 capture_captured += adjust_capture_position;
846 adjust_capture_position = 0;
850 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
852 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
853 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
856 if (commit_should_unlock) {
866 AudioDiskstream::set_pending_overwrite (bool yn)
868 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
870 pending_overwrite = yn;
872 overwrite_frame = playback_sample;
873 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
877 AudioDiskstream::overwrite_existing_buffers ()
879 boost::shared_ptr<ChannelList> c = channels.reader();
880 Sample* mixdown_buffer;
883 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
885 overwrite_queued = false;
887 /* assume all are the same size */
888 nframes_t size = c->front()->playback_buf->bufsize();
890 mixdown_buffer = new Sample[size];
891 gain_buffer = new float[size];
893 /* reduce size so that we can fill the buffer correctly. */
899 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
901 start = overwrite_frame;
902 nframes_t cnt = size;
904 /* to fill the buffer without resetting the playback sample, we need to
905 do it one or two chunks (normally two).
907 |----------------------------------------------------------------------|
911 |<- second chunk->||<----------------- first chunk ------------------>|
915 nframes_t to_read = size - overwrite_offset;
917 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
918 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
919 _id, size, playback_sample) << endmsg;
927 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
928 start, cnt, *chan, n, reversed)) {
929 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
930 _id, size, playback_sample) << endmsg;
939 pending_overwrite = false;
940 delete [] gain_buffer;
941 delete [] mixdown_buffer;
946 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
950 ChannelList::iterator chan;
951 boost::shared_ptr<ChannelList> c = channels.reader();
953 Glib::Mutex::Lock lm (state_lock);
955 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
956 (*chan)->playback_buf->reset ();
957 (*chan)->capture_buf->reset ();
960 /* can't rec-enable in destructive mode if transport is before start */
962 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
963 disengage_record_enable ();
966 playback_sample = frame;
969 if (complete_refill) {
970 while ((ret = do_refill_with_alloc ()) > 0) ;
972 ret = do_refill_with_alloc ();
979 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
981 ChannelList::iterator chan;
982 boost::shared_ptr<ChannelList> c = channels.reader();
984 for (chan = c->begin(); chan != c->end(); ++chan) {
985 if ((*chan)->playback_buf->read_space() < distance) {
993 AudioDiskstream::internal_playback_seek (nframes_t distance)
995 ChannelList::iterator chan;
996 boost::shared_ptr<ChannelList> c = channels.reader();
998 for (chan = c->begin(); chan != c->end(); ++chan) {
999 (*chan)->playback_buf->increment_read_ptr (distance);
1002 first_recordable_frame += distance;
1003 playback_sample += distance;
1009 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1010 ChannelInfo* channel_info, int channel, bool reversed)
1012 nframes_t this_read = 0;
1013 bool reloop = false;
1014 nframes_t loop_end = 0;
1015 nframes_t loop_start = 0;
1016 nframes_t loop_length = 0;
1017 nframes_t offset = 0;
1018 nframes_t xfade_samples = 0;
1019 Sample xfade_buf[128];
1022 /* XXX we don't currently play loops in reverse. not sure why */
1026 /* Make the use of a Location atomic for this read operation.
1028 Note: Locations don't get deleted, so all we care about
1029 when I say "atomic" is that we are always pointing to
1030 the same one and using a start/length values obtained
1034 if ((loc = loop_location) != 0) {
1035 loop_start = loc->start();
1036 loop_end = loc->end();
1037 loop_length = loop_end - loop_start;
1040 /* if we are looping, ensure that the first frame we read is at the correct
1041 position within the loop.
1044 if (loc && start >= loop_end) {
1045 //cerr << "start adjusted from " << start;
1046 start = loop_start + ((start - loop_start) % loop_length);
1047 //cerr << "to " << start << endl;
1050 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1059 /* take any loop into account. we can't read past the end of the loop. */
1061 if (loc && (loop_end - start < cnt)) {
1062 this_read = loop_end - start;
1063 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1070 if (this_read == 0) {
1074 this_read = min(cnt,this_read);
1076 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1077 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1082 // xfade loop boundary if appropriate
1084 if (xfade_samples > 0) {
1085 // just do a linear xfade for this short bit
1087 xfade_samples = min(xfade_samples, this_read);
1089 float delta = 1.0f / xfade_samples;
1091 Sample * tmpbuf = buf+offset;
1093 for (size_t i=0; i < xfade_samples; ++i) {
1094 *tmpbuf = (*tmpbuf * scale) + xfade_buf[i]*(1.0f - scale);
1102 _read_data_count = _playlist->read_data_count();
1106 swap_by_ptr (buf, buf + this_read - 1);
1111 /* if we read to the end of the loop, go back to the beginning */
1114 // read crossfade samples to apply to the next read
1116 xfade_samples = min((nframes_t) 128, cnt-this_read);
1118 if (audio_playlist()->read (xfade_buf, mixdown_buffer, gain_buffer, start, xfade_samples, channel) != xfade_samples) {
1119 error << string_compose(_("AudioDiskstream %1: cannot read xfade samples %2 from playlist at frame %3"),
1120 _id, xfade_samples,start) << endmsg;
1121 memset(xfade_buf, 0, xfade_samples * sizeof(Sample)); // just in case
1129 offset += this_read;
1136 AudioDiskstream::do_refill_with_alloc ()
1138 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1139 float* gain_buf = new float[disk_io_chunk_frames];
1141 int ret = _do_refill(mix_buf, gain_buf);
1150 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1154 RingBufferNPT<Sample>::rw_vector vector;
1155 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1156 nframes_t total_space;
1157 nframes_t zero_fill;
1159 ChannelList::iterator i;
1160 boost::shared_ptr<ChannelList> c = channels.reader();
1167 assert(mixdown_buffer);
1168 assert(gain_buffer);
1175 c->front()->playback_buf->get_write_vector (&vector);
1177 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1181 /* if there are 2+ chunks of disk i/o possible for
1182 this track, let the caller know so that it can arrange
1183 for us to be called again, ASAP.
1186 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1190 /* if we're running close to normal speed and there isn't enough
1191 space to do disk_io_chunk_frames of I/O, then don't bother.
1193 at higher speeds, just do it because the sync between butler
1194 and audio thread may not be good enough.
1197 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1201 /* when slaved, don't try to get too close to the read pointer. this
1202 leaves space for the buffer reversal to have something useful to
1206 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1210 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1212 total_space = min (disk_io_chunk_frames, total_space);
1216 if (file_frame == 0) {
1218 /* at start: nothing to do but fill with silence */
1220 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1222 ChannelInfo* chan (*i);
1223 chan->playback_buf->get_write_vector (&vector);
1224 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1225 if (vector.len[1]) {
1226 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1228 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1233 if (file_frame < total_space) {
1235 /* too close to the start: read what we can,
1236 and then zero fill the rest
1239 zero_fill = total_space - file_frame;
1240 total_space = file_frame;
1250 if (file_frame == max_frames) {
1252 /* at end: nothing to do but fill with silence */
1254 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1256 ChannelInfo* chan (*i);
1257 chan->playback_buf->get_write_vector (&vector);
1258 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1259 if (vector.len[1]) {
1260 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1262 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1267 if (file_frame > max_frames - total_space) {
1269 /* to close to the end: read what we can, and zero fill the rest */
1271 zero_fill = total_space - (max_frames - file_frame);
1272 total_space = max_frames - file_frame;
1279 nframes_t file_frame_tmp = 0;
1281 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1283 ChannelInfo* chan (*i);
1286 nframes_t len1, len2;
1288 chan->playback_buf->get_write_vector (&vector);
1290 if (vector.len[0] > disk_io_chunk_frames) {
1292 /* we're not going to fill the first chunk, so certainly do not bother with the
1293 other part. it won't be connected with the part we do fill, as in:
1295 .... => writable space
1296 ++++ => readable space
1297 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1299 |......|+++++++++++++|...............................|
1304 So, just pretend that the buf1 part isn't there.
1314 file_frame_tmp = file_frame;
1316 buf1 = vector.buf[0];
1317 len1 = vector.len[0];
1318 buf2 = vector.buf[1];
1319 len2 = vector.len[1];
1321 to_read = min (ts, len1);
1322 to_read = min (to_read, disk_io_chunk_frames);
1326 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1331 chan->playback_buf->increment_write_ptr (to_read);
1335 to_read = min (ts, len2);
1339 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1340 so read some or all of vector.len[1] as well.
1343 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1348 chan->playback_buf->increment_write_ptr (to_read);
1357 file_frame = file_frame_tmp;
1364 /** Flush pending data to disk.
1366 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1367 * of data to disk. it will never write more than that. If it writes that
1368 * much and there is more than that waiting to be written, it will return 1,
1369 * otherwise 0 on success or -1 on failure.
1371 * If there is less than disk_io_chunk_frames to be written, no data will be
1372 * written at all unless @a force_flush is true.
1375 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1379 RingBufferNPT<Sample>::rw_vector vector;
1380 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1383 _write_data_count = 0;
1385 transvec.buf[0] = 0;
1386 transvec.buf[1] = 0;
1390 boost::shared_ptr<ChannelList> c = channels.reader();
1391 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1393 (*chan)->capture_buf->get_read_vector (&vector);
1395 total = vector.len[0] + vector.len[1];
1397 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1401 /* if there are 2+ chunks of disk i/o possible for
1402 this track, let the caller know so that it can arrange
1403 for us to be called again, ASAP.
1405 if we are forcing a flush, then if there is* any* extra
1406 work, let the caller know.
1408 if we are no longer recording and there is any extra work,
1409 let the caller know too.
1412 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1416 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1418 // check the transition buffer when recording destructive
1419 // important that we get this after the capture buf
1421 if (destructive()) {
1422 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1423 size_t transcount = transvec.len[0] + transvec.len[1];
1424 bool have_start = false;
1427 for (ti=0; ti < transcount; ++ti) {
1428 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1430 if (captrans.type == CaptureStart) {
1431 // by definition, the first data we got above represents the given capture pos
1433 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1434 (*chan)->curr_capture_cnt = 0;
1438 else if (captrans.type == CaptureEnd) {
1440 // capture end, the capture_val represents total frames in capture
1442 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1444 // shorten to make the write a perfect fit
1445 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1447 if (nto_write < to_write) {
1448 ret = 1; // should we?
1450 to_write = nto_write;
1452 (*chan)->write_source->mark_capture_end ();
1454 // increment past this transition, but go no further
1459 // actually ends just beyond this chunk, so force more work
1467 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1471 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1472 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1476 (*chan)->capture_buf->increment_read_ptr (to_write);
1477 (*chan)->curr_capture_cnt += to_write;
1479 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1481 /* we wrote all of vector.len[0] but it wasn't an entire
1482 disk_io_chunk_frames of data, so arrange for some part
1483 of vector.len[1] to be flushed to disk as well.
1486 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1488 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1489 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1493 _write_data_count += (*chan)->write_source->write_data_count();
1495 (*chan)->capture_buf->increment_read_ptr (to_write);
1496 (*chan)->curr_capture_cnt += to_write;
1505 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1507 uint32_t buffer_position;
1508 bool more_work = true;
1510 boost::shared_ptr<AudioRegion> region;
1511 nframes_t total_capture;
1513 SourceList::iterator src;
1514 ChannelList::iterator chan;
1515 vector<CaptureInfo*>::iterator ci;
1516 boost::shared_ptr<ChannelList> c = channels.reader();
1518 bool mark_write_completed = false;
1520 finish_capture (true, c);
1522 /* butler is already stopped, but there may be work to do
1523 to flush remaining data to disk.
1526 while (more_work && !err) {
1527 switch (do_flush (Session::TransportContext, true)) {
1534 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1539 /* XXX is there anything we can do if err != 0 ? */
1540 Glib::Mutex::Lock lm (capture_info_lock);
1542 if (capture_info.empty()) {
1546 if (abort_capture) {
1548 if (destructive()) {
1552 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1554 if ((*chan)->write_source) {
1556 (*chan)->write_source->mark_for_remove ();
1557 (*chan)->write_source->drop_references ();
1558 (*chan)->write_source.reset ();
1561 /* new source set up in "out" below */
1567 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1568 total_capture += (*ci)->frames;
1571 /* figure out the name for this take */
1573 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1575 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1579 s->update_header (capture_info.front()->start, when, twhen);
1580 s->set_captured_for (_name);
1581 s->mark_immutable ();
1585 /* destructive tracks have a single, never changing region */
1587 if (destructive()) {
1589 /* send a signal that any UI can pick up to do the right thing. there is
1590 a small problem here in that a UI may need the peak data to be ready
1591 for the data that was recorded and this isn't interlocked with that
1592 process. this problem is deferred to the UI.
1595 _playlist->Modified();
1599 string whole_file_region_name;
1600 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1602 /* Register a new region with the Session that
1603 describes the entire source. Do this first
1604 so that any sub-regions will obviously be
1605 children of this one (later!)
1609 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1610 whole_file_region_name,
1611 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1613 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1614 region->special_set_position (capture_info.front()->start);
1618 catch (failed_constructor& err) {
1619 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1623 _last_capture_regions.push_back (region);
1625 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1627 XMLNode &before = _playlist->get_state();
1628 _playlist->freeze ();
1630 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1634 _session.region_name (region_name, whole_file_region_name, false);
1636 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1639 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1640 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1643 catch (failed_constructor& err) {
1644 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1645 continue; /* XXX is this OK? */
1648 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1650 _last_capture_regions.push_back (region);
1652 i_am_the_modifier++;
1653 _playlist->add_region (region, (*ci)->start);
1654 i_am_the_modifier--;
1656 buffer_position += (*ci)->frames;
1660 XMLNode &after = _playlist->get_state();
1661 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1664 mark_write_completed = true;
1667 reset_write_sources (mark_write_completed);
1671 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1675 capture_info.clear ();
1676 capture_start_frame = 0;
1680 AudioDiskstream::transport_looped (nframes_t transport_frame)
1682 if (was_recording) {
1683 // all we need to do is finish this capture, with modified capture length
1684 boost::shared_ptr<ChannelList> c = channels.reader();
1686 // adjust the capture length knowing that the data will be recorded to disk
1687 // only necessary after the first loop where we're recording
1688 if (capture_info.size() == 0) {
1689 capture_captured += _capture_offset;
1691 if (_alignment_style == ExistingMaterial) {
1692 capture_captured += _session.worst_output_latency();
1694 capture_captured += _roll_delay;
1698 finish_capture (true, c);
1700 // the next region will start recording via the normal mechanism
1701 // we'll set the start position to the current transport pos
1702 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1703 capture_start_frame = transport_frame;
1704 first_recordable_frame = transport_frame; // mild lie
1705 last_recordable_frame = max_frames;
1706 was_recording = true;
1708 if (recordable() && destructive()) {
1709 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1711 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1712 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1714 if (transvec.len[0] > 0) {
1715 transvec.buf[0]->type = CaptureStart;
1716 transvec.buf[0]->capture_val = capture_start_frame;
1717 (*chan)->capture_transition_buf->increment_write_ptr(1);
1721 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1731 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1733 was_recording = false;
1735 if (capture_captured == 0) {
1739 if (recordable() && destructive()) {
1740 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1742 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1743 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1745 if (transvec.len[0] > 0) {
1746 transvec.buf[0]->type = CaptureEnd;
1747 transvec.buf[0]->capture_val = capture_captured;
1748 (*chan)->capture_transition_buf->increment_write_ptr(1);
1752 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1758 CaptureInfo* ci = new CaptureInfo;
1760 ci->start = capture_start_frame;
1761 ci->frames = capture_captured;
1763 /* XXX theoretical race condition here. Need atomic exchange ?
1764 However, the circumstances when this is called right
1765 now (either on record-disable or transport_stopped)
1766 mean that no actual race exists. I think ...
1767 We now have a capture_info_lock, but it is only to be used
1768 to synchronize in the transport_stop and the capture info
1769 accessors, so that invalidation will not occur (both non-realtime).
1772 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1774 capture_info.push_back (ci);
1775 capture_captured = 0;
1779 AudioDiskstream::set_record_enabled (bool yn)
1781 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs() == 0) {
1785 /* can't rec-enable in destructive mode if transport is before start */
1787 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1791 if (yn && channels.reader()->front()->source == 0) {
1793 /* pick up connections not initiated *from* the IO object
1794 we're associated with.
1797 get_input_sources ();
1800 /* yes, i know that this not proof against race conditions, but its
1801 good enough. i think.
1804 if (record_enabled() != yn) {
1806 engage_record_enable ();
1808 disengage_record_enable ();
1814 AudioDiskstream::engage_record_enable ()
1816 bool rolling = _session.transport_speed() != 0.0f;
1817 boost::shared_ptr<ChannelList> c = channels.reader();
1819 g_atomic_int_set (&_record_enabled, 1);
1820 capturing_sources.clear ();
1822 if (Config->get_monitoring_model() == HardwareMonitoring) {
1824 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1825 if ((*chan)->source) {
1826 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1828 capturing_sources.push_back ((*chan)->write_source);
1832 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1833 capturing_sources.push_back ((*chan)->write_source);
1837 RecordEnableChanged (); /* EMIT SIGNAL */
1841 AudioDiskstream::disengage_record_enable ()
1843 g_atomic_int_set (&_record_enabled, 0);
1844 boost::shared_ptr<ChannelList> c = channels.reader();
1845 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1846 if (Config->get_monitoring_model() == HardwareMonitoring) {
1847 if ((*chan)->source) {
1848 (*chan)->source->ensure_monitor_input (false);
1852 capturing_sources.clear ();
1853 RecordEnableChanged (); /* EMIT SIGNAL */
1857 AudioDiskstream::get_state ()
1859 XMLNode* node = new XMLNode ("AudioDiskstream");
1861 LocaleGuard lg (X_("POSIX"));
1862 boost::shared_ptr<ChannelList> c = channels.reader();
1864 node->add_property ("flags", enum_2_string (_flags));
1866 snprintf (buf, sizeof(buf), "%zd", c->size());
1867 node->add_property ("channels", buf);
1869 node->add_property ("playlist", _playlist->name());
1871 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1872 node->add_property ("speed", buf);
1874 node->add_property("name", _name);
1875 id().print (buf, sizeof (buf));
1876 node->add_property("id", buf);
1878 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1880 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1881 XMLNode* cs_grandchild;
1883 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1884 cs_grandchild = new XMLNode (X_("file"));
1885 cs_grandchild->add_property (X_("path"), (*i)->path());
1886 cs_child->add_child_nocopy (*cs_grandchild);
1889 /* store the location where capture will start */
1893 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1894 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1896 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1899 cs_child->add_property (X_("at"), buf);
1900 node->add_child_nocopy (*cs_child);
1904 node->add_child_copy (*_extra_xml);
1911 AudioDiskstream::set_state (const XMLNode& node)
1913 const XMLProperty* prop;
1914 XMLNodeList nlist = node.children();
1915 XMLNodeIterator niter;
1916 uint32_t nchans = 1;
1917 XMLNode* capture_pending_node = 0;
1918 LocaleGuard lg (X_("POSIX"));
1920 in_set_state = true;
1922 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1923 if ((*niter)->name() == IO::state_node_name) {
1924 deprecated_io_node = new XMLNode (**niter);
1927 if ((*niter)->name() == X_("CapturingSources")) {
1928 capture_pending_node = *niter;
1932 /* prevent write sources from being created */
1934 in_set_state = true;
1936 if ((prop = node.property ("name")) != 0) {
1937 _name = prop->value();
1940 if (deprecated_io_node) {
1941 if ((prop = deprecated_io_node->property ("id")) != 0) {
1942 _id = prop->value ();
1945 if ((prop = node.property ("id")) != 0) {
1946 _id = prop->value ();
1950 if ((prop = node.property ("flags")) != 0) {
1951 _flags = Flag (string_2_enum (prop->value(), _flags));
1954 if ((prop = node.property ("channels")) != 0) {
1955 nchans = atoi (prop->value().c_str());
1958 // create necessary extra channels
1959 // we are always constructed with one and we always need one
1961 _n_channels = channels.reader()->size();
1963 if (nchans > _n_channels) {
1965 add_channel (nchans - _n_channels);
1967 } else if (nchans < _n_channels) {
1969 remove_channel (_n_channels - nchans);
1972 if ((prop = node.property ("playlist")) == 0) {
1977 bool had_playlist = (_playlist != 0);
1979 if (find_and_use_playlist (prop->value())) {
1983 if (!had_playlist) {
1984 _playlist->set_orig_diskstream_id (_id);
1987 if (!destructive() && capture_pending_node) {
1988 /* destructive streams have one and only one source per channel,
1989 and so they never end up in pending capture in any useful
1992 use_pending_capture_data (*capture_pending_node);
1997 if ((prop = node.property ("speed")) != 0) {
1998 double sp = atof (prop->value().c_str());
2000 if (realtime_set_speed (sp, false)) {
2001 non_realtime_set_speed ();
2005 in_set_state = false;
2007 /* make sure this is clear before we do anything else */
2009 capturing_sources.clear ();
2011 /* write sources are handled when we handle the input set
2012 up of the IO that owns this DS (::non_realtime_input_change())
2015 in_set_state = false;
2021 AudioDiskstream::use_new_write_source (uint32_t n)
2023 boost::shared_ptr<ChannelList> c = channels.reader();
2025 if (!recordable()) {
2029 if (n >= c->size()) {
2030 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2034 ChannelInfo* chan = (*c)[n];
2036 if (chan->write_source) {
2037 chan->write_source->done_with_peakfile_writes ();
2038 chan->write_source->set_allow_remove_if_empty (true);
2039 chan->write_source.reset ();
2043 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2044 throw failed_constructor();
2048 catch (failed_constructor &err) {
2049 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2050 chan->write_source.reset ();
2054 /* do not remove destructive files even if they are empty */
2056 chan->write_source->set_allow_remove_if_empty (!destructive());
2062 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2064 ChannelList::iterator chan;
2065 boost::shared_ptr<ChannelList> c = channels.reader();
2068 if (!recordable()) {
2072 capturing_sources.clear ();
2074 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2075 if (!destructive()) {
2077 if ((*chan)->write_source && mark_write_complete) {
2078 (*chan)->write_source->mark_streaming_write_completed ();
2080 use_new_write_source (n);
2082 if (record_enabled()) {
2083 capturing_sources.push_back ((*chan)->write_source);
2087 if ((*chan)->write_source == 0) {
2088 use_new_write_source (n);
2093 if (destructive()) {
2095 /* we now have all our write sources set up, so create the
2096 playlist's single region.
2099 if (_playlist->empty()) {
2100 setup_destructive_playlist ();
2106 AudioDiskstream::rename_write_sources ()
2108 ChannelList::iterator chan;
2109 boost::shared_ptr<ChannelList> c = channels.reader();
2112 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2113 if ((*chan)->write_source != 0) {
2114 (*chan)->write_source->set_name (_name, destructive());
2115 /* XXX what to do if one of them fails ? */
2123 AudioDiskstream::set_block_size (nframes_t nframes)
2125 if (_session.get_block_size() > speed_buffer_size) {
2126 speed_buffer_size = _session.get_block_size();
2127 boost::shared_ptr<ChannelList> c = channels.reader();
2129 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2130 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2131 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2134 allocate_temporary_buffers ();
2138 AudioDiskstream::allocate_temporary_buffers ()
2140 /* make sure the wrap buffer is at least large enough to deal
2141 with the speeds up to 1.2, to allow for micro-variation
2142 when slaving to MTC, SMPTE etc.
2145 double sp = max (fabsf (_actual_speed), 1.2f);
2146 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2148 if (required_wrap_size > wrap_buffer_size) {
2150 boost::shared_ptr<ChannelList> c = channels.reader();
2152 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2153 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2154 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2155 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2156 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2159 wrap_buffer_size = required_wrap_size;
2164 AudioDiskstream::monitor_input (bool yn)
2166 boost::shared_ptr<ChannelList> c = channels.reader();
2168 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2170 if ((*chan)->source) {
2171 (*chan)->source->ensure_monitor_input (yn);
2177 AudioDiskstream::set_align_style_from_io ()
2179 bool have_physical = false;
2185 get_input_sources ();
2187 boost::shared_ptr<ChannelList> c = channels.reader();
2189 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2190 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2191 have_physical = true;
2196 if (have_physical) {
2197 set_align_style (ExistingMaterial);
2199 set_align_style (CaptureTime);
2204 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2206 while (how_many--) {
2207 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2210 _n_channels = c->size();
2216 AudioDiskstream::add_channel (uint32_t how_many)
2218 RCUWriter<ChannelList> writer (channels);
2219 boost::shared_ptr<ChannelList> c = writer.get_copy();
2221 return add_channel_to (c, how_many);
2225 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2227 while (--how_many && !c->empty()) {
2232 _n_channels = c->size();
2238 AudioDiskstream::remove_channel (uint32_t how_many)
2240 RCUWriter<ChannelList> writer (channels);
2241 boost::shared_ptr<ChannelList> c = writer.get_copy();
2243 return remove_channel_from (c, how_many);
2247 AudioDiskstream::playback_buffer_load () const
2249 boost::shared_ptr<ChannelList> c = channels.reader();
2251 return (float) ((double) c->front()->playback_buf->read_space()/
2252 (double) c->front()->playback_buf->bufsize());
2256 AudioDiskstream::capture_buffer_load () const
2258 boost::shared_ptr<ChannelList> c = channels.reader();
2260 return (float) ((double) c->front()->capture_buf->write_space()/
2261 (double) c->front()->capture_buf->bufsize());
2265 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2267 const XMLProperty* prop;
2268 XMLNodeList nlist = node.children();
2269 XMLNodeIterator niter;
2270 boost::shared_ptr<AudioFileSource> fs;
2271 boost::shared_ptr<AudioFileSource> first_fs;
2272 SourceList pending_sources;
2275 if ((prop = node.property (X_("at"))) == 0) {
2279 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2283 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2284 if ((*niter)->name() == X_("file")) {
2286 if ((prop = (*niter)->property (X_("path"))) == 0) {
2290 // This protects sessions from errant CapturingSources in stored sessions
2292 if (stat (prop->value().c_str(), &sbuf)) {
2297 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (_session, prop->value(), false, _session.frame_rate()));
2300 catch (failed_constructor& err) {
2301 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2302 _name, prop->value())
2307 pending_sources.push_back (fs);
2309 if (first_fs == 0) {
2313 fs->set_captured_for (_name);
2317 if (pending_sources.size() == 0) {
2318 /* nothing can be done */
2322 if (pending_sources.size() != _n_channels) {
2323 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2328 boost::shared_ptr<AudioRegion> region;
2331 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2332 region_name_from_path (first_fs->name(), true),
2333 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2334 region->special_set_position (0);
2337 catch (failed_constructor& err) {
2338 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2346 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2349 catch (failed_constructor& err) {
2350 error << string_compose (_("%1: cannot create region from pending capture sources"),
2357 _playlist->add_region (region, position);
2363 AudioDiskstream::set_destructive (bool yn)
2365 bool bounce_ignored;
2367 if (yn != destructive()) {
2370 /* requestor should already have checked this and
2371 bounced if necessary and desired
2373 if (!can_become_destructive (bounce_ignored)) {
2376 _flags = Flag (_flags | Destructive);
2377 use_destructive_playlist ();
2379 _flags = Flag (_flags & ~Destructive);
2380 reset_write_sources (true, true);
2388 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2391 requires_bounce = false;
2395 /* is there only one region ? */
2397 if (_playlist->n_regions() != 1) {
2398 requires_bounce = true;
2402 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2405 /* do the source(s) for the region cover the session start position ? */
2407 if (first->position() != _session.current_start_frame()) {
2408 if (first->start() > _session.current_start_frame()) {
2409 requires_bounce = true;
2414 /* is the source used by only 1 playlist ? */
2416 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2420 if (afirst->source()->used() > 1) {
2421 requires_bounce = true;
2425 requires_bounce = false;
2429 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2433 current_capture_buffer = 0;
2434 current_playback_buffer = 0;
2435 curr_capture_cnt = 0;
2437 speed_buffer = new Sample[speed_size];
2438 playback_wrap_buffer = new Sample[wrap_size];
2439 capture_wrap_buffer = new Sample[wrap_size];
2441 playback_buf = new RingBufferNPT<Sample> (bufsize);
2442 capture_buf = new RingBufferNPT<Sample> (bufsize);
2443 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2445 /* touch the ringbuffer buffers, which will cause
2446 them to be mapped into locked physical RAM if
2447 we're running with mlockall(). this doesn't do
2451 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2452 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2453 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2456 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2459 write_source.reset ();
2463 delete [] speed_buffer;
2467 if (playback_wrap_buffer) {
2468 delete [] playback_wrap_buffer;
2469 playback_wrap_buffer = 0;
2472 if (capture_wrap_buffer) {
2473 delete [] capture_wrap_buffer;
2474 capture_wrap_buffer = 0;
2478 delete playback_buf;
2487 if (capture_transition_buf) {
2488 delete capture_transition_buf;
2489 capture_transition_buf = 0;