2 Copyright (C) 2000-2003 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.
34 #include <pbd/error.h>
35 #include <pbd/basename.h>
36 #include <pbd/lockmonitor.h>
37 #include <pbd/xml++.h>
39 #include <ardour/ardour.h>
40 #include <ardour/audioengine.h>
41 #include <ardour/diskstream.h>
42 #include <ardour/utils.h>
43 #include <ardour/configuration.h>
44 #include <ardour/filesource.h>
45 #include <ardour/destructive_filesource.h>
46 #include <ardour/send.h>
47 #include <ardour/audioplaylist.h>
48 #include <ardour/cycle_timer.h>
49 #include <ardour/audioregion.h>
55 using namespace ARDOUR;
57 jack_nframes_t DiskStream::disk_io_chunk_frames;
59 sigc::signal<void,DiskStream*> DiskStream::DiskStreamCreated;
60 sigc::signal<void,DiskStream*> DiskStream::CannotRecordNoInput;
61 sigc::signal<void,list<Source*>*> DiskStream::DeleteSources;
62 sigc::signal<void> DiskStream::DiskOverrun;
63 sigc::signal<void> DiskStream::DiskUnderrun;
65 DiskStream::DiskStream (Session &sess, const string &name, Flag flag)
69 /* prevent any write sources from being created */
77 setup_destructive_playlist ();
80 DiskStreamCreated (this); /* EMIT SIGNAL */
83 DiskStream::DiskStream (Session& sess, const XMLNode& node)
90 if (set_state (node)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
101 DiskStreamCreated (this); /* EMIT SIGNAL */
105 DiskStream::init_channel (ChannelInfo &chan)
107 chan.playback_wrap_buffer = 0;
108 chan.capture_wrap_buffer = 0;
109 chan.speed_buffer = 0;
110 chan.peak_power = 0.0f;
111 chan.write_source = 0;
113 chan.current_capture_buffer = 0;
114 chan.current_playback_buffer = 0;
115 chan.curr_capture_cnt = 0;
117 chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
118 chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
119 chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
122 /* touch the ringbuffer buffers, which will cause
123 them to be mapped into locked physical RAM if
124 we're running with mlockall(). this doesn't do
127 memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
128 memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
129 memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
134 DiskStream::init (Flag f)
140 _alignment_style = ExistingMaterial;
141 _persistent_alignment_style = ExistingMaterial;
142 first_input_change = true;
144 i_am_the_modifier = 0;
145 atomic_set (&_record_enabled, 0);
146 was_recording = false;
147 capture_start_frame = 0;
148 capture_captured = 0;
149 _visible_speed = 1.0f;
150 _actual_speed = 1.0f;
151 _buffer_reallocation_required = false;
152 _seek_required = false;
153 first_recordable_frame = max_frames;
154 last_recordable_frame = max_frames;
159 adjust_capture_position = 0;
160 last_possibly_recording = 0;
162 wrap_buffer_size = 0;
163 speed_buffer_size = 0;
165 phi = (uint64_t) (0x1000000);
168 playback_distance = 0;
169 _read_data_count = 0;
170 _write_data_count = 0;
171 deprecated_io_node = 0;
173 /* there are no channels at this point, so these
174 two calls just get speed_buffer_size and wrap_buffer
175 size setup without duplicating their code.
178 set_block_size (_session.get_block_size());
179 allocate_temporary_buffers ();
181 pending_overwrite = false;
183 overwrite_queued = false;
184 input_change_pending = NoChange;
191 DiskStream::destroy_channel (ChannelInfo &chan)
193 if (chan.write_source) {
194 chan.write_source->release ();
195 chan.write_source = 0;
198 if (chan.speed_buffer) {
199 delete [] chan.speed_buffer;
202 if (chan.playback_wrap_buffer) {
203 delete [] chan.playback_wrap_buffer;
205 if (chan.capture_wrap_buffer) {
206 delete [] chan.capture_wrap_buffer;
209 delete chan.playback_buf;
210 delete chan.capture_buf;
211 delete chan.capture_transition_buf;
213 chan.playback_buf = 0;
214 chan.capture_buf = 0;
217 DiskStream::~DiskStream ()
219 LockMonitor lm (state_lock, __LINE__, __FILE__);
225 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
226 destroy_channel((*chan));
233 DiskStream::handle_input_change (IOChange change, void *src)
235 LockMonitor lm (state_lock, __LINE__, __FILE__);
237 if (!(input_change_pending & change)) {
238 input_change_pending = IOChange (input_change_pending|change);
239 _session.request_input_change_handling ();
244 DiskStream::non_realtime_input_change ()
247 LockMonitor lm (state_lock, __LINE__, __FILE__);
249 if (input_change_pending == NoChange) {
253 if (input_change_pending & ConfigurationChanged) {
255 if (_io->n_inputs() > _n_channels) {
257 // we need to add new channel infos
259 int diff = _io->n_inputs() - channels.size();
261 for (int i = 0; i < diff; ++i) {
265 } else if (_io->n_inputs() < _n_channels) {
267 // we need to get rid of channels
269 int diff = channels.size() - _io->n_inputs();
271 for (int i = 0; i < diff; ++i) {
277 get_input_sources ();
278 set_capture_offset ();
280 if (first_input_change) {
281 set_align_style (_persistent_alignment_style);
282 first_input_change = false;
284 set_align_style_from_io ();
287 input_change_pending = NoChange;
290 /* reset capture files */
292 reset_write_sources (false);
294 /* now refill channel buffers */
296 if (speed() != 1.0f || speed() != -1.0f) {
297 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()));
300 seek (_session.transport_frame());
305 DiskStream::get_input_sources ()
307 uint32_t ni = _io->n_inputs();
309 for (uint32_t n = 0; n < ni; ++n) {
311 const char **connections = _io->input(n)->get_connections ();
312 ChannelInfo& chan = channels[n];
314 if (connections == 0 || connections[0] == 0) {
317 // _source->disable_metering ();
323 chan.source = _session.engine().get_port_by_name (connections[0]);
333 DiskStream::find_and_use_playlist (const string& name)
336 AudioPlaylist* playlist;
338 if ((pl = _session.get_playlist (name)) == 0) {
339 error << string_compose(_("DiskStream: Session doesn't know about a Playlist called \"%1\""), name) << endmsg;
343 if ((playlist = dynamic_cast<AudioPlaylist*> (pl)) == 0) {
344 error << string_compose(_("DiskStream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
348 return use_playlist (playlist);
352 DiskStream::use_playlist (AudioPlaylist* playlist)
355 LockMonitor lm (state_lock, __LINE__, __FILE__);
357 if (playlist == _playlist) {
361 plstate_connection.disconnect();
362 plmod_connection.disconnect ();
363 plgone_connection.disconnect ();
369 _playlist = playlist;
372 if (!in_set_state && recordable()) {
373 reset_write_sources (false);
376 plstate_connection = _playlist->StateChanged.connect (mem_fun (*this, &DiskStream::playlist_changed));
377 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &DiskStream::playlist_modified));
378 plgone_connection = _playlist->GoingAway.connect (mem_fun (*this, &DiskStream::playlist_deleted));
381 if (!overwrite_queued) {
382 _session.request_overwrite_buffer (this);
383 overwrite_queued = true;
386 PlaylistChanged (); /* EMIT SIGNAL */
387 _session.set_dirty ();
393 DiskStream::playlist_deleted (Playlist* pl)
395 /* this catches an ordering issue with session destruction. playlists
396 are destroyed before diskstreams. we have to invalidate any handles
397 we have to the playlist.
404 DiskStream::use_new_playlist ()
407 AudioPlaylist* playlist;
409 if (!in_set_state && destructive()) {
414 newname = Playlist::bump_name (_playlist->name(), _session);
416 newname = Playlist::bump_name (_name, _session);
419 if ((playlist = new AudioPlaylist (_session, newname, hidden())) != 0) {
420 playlist->set_orig_diskstream_id (id());
421 return use_playlist (playlist);
428 DiskStream::use_copy_playlist ()
434 if (_playlist == 0) {
435 error << string_compose(_("DiskStream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
440 AudioPlaylist* playlist;
442 newname = Playlist::bump_name (_playlist->name(), _session);
444 if ((playlist = new AudioPlaylist (*_playlist, newname)) != 0) {
445 playlist->set_orig_diskstream_id (id());
446 return use_playlist (playlist);
453 DiskStream::setup_destructive_playlist ()
455 AudioRegion::SourceList srcs;
457 /* make sure we have sources for every channel */
459 reset_write_sources (true);
461 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
462 srcs.push_back ((*chan).write_source);
465 /* a single full-sized region */
467 AudioRegion* region = new AudioRegion (srcs, 0, max_frames, _name);
468 _playlist->add_region (*region, 0);
472 DiskStream::use_destructive_playlist ()
474 /* use the sources associated with the single full-extent region */
476 AudioRegion* region = dynamic_cast<AudioRegion*> (_playlist->regions_at (0)->front());
478 ChannelList::iterator chan;
480 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
481 (*chan).write_source = dynamic_cast<FileSource*>(®ion->source (n));
484 /* the source list will never be reset for a destructive track */
488 DiskStream::set_io (IO& io)
491 set_align_style_from_io ();
495 DiskStream::set_name (string str, void *src)
498 _playlist->set_name (str);
501 if (!in_set_state && recordable()) {
503 /* open new capture files so that they have the correct name */
505 reset_write_sources (false);
511 DiskStream::set_speed (double sp)
513 _session.request_diskstream_speed (*this, sp);
515 /* to force a rebuffering at the right place */
520 DiskStream::realtime_set_speed (double sp, bool global)
522 bool changed = false;
523 double new_speed = sp * _session.transport_speed();
525 if (_visible_speed != sp) {
530 if (new_speed != _actual_speed) {
532 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() *
533 fabs (new_speed)) + 1;
535 if (required_wrap_size > wrap_buffer_size) {
536 _buffer_reallocation_required = true;
539 _actual_speed = new_speed;
540 phi = (uint64_t) (0x1000000 * fabs(_actual_speed));
545 _seek_required = true;
547 speed_changed (); /* EMIT SIGNAL */
550 return _buffer_reallocation_required || _seek_required;
554 DiskStream::non_realtime_set_speed ()
556 if (_buffer_reallocation_required)
558 LockMonitor lm (state_lock, __LINE__, __FILE__);
559 allocate_temporary_buffers ();
561 _buffer_reallocation_required = false;
564 if (_seek_required) {
565 if (speed() != 1.0f || speed() != -1.0f) {
566 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()), true);
569 seek (_session.transport_frame(), true);
572 _seek_required = false;
577 DiskStream::prepare ()
580 playback_distance = 0;
584 DiskStream::check_record_status (jack_nframes_t transport_frame, jack_nframes_t nframes, bool can_record)
586 int possibly_recording;
589 const int transport_rolling = 0x4;
590 const int track_rec_enabled = 0x2;
591 const int global_rec_enabled = 0x1;
593 /* merge together the 3 factors that affect record status, and compute
597 rolling = _session.transport_speed() != 0.0f;
598 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
599 change = possibly_recording ^ last_possibly_recording;
601 if (possibly_recording == last_possibly_recording) {
607 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
609 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
610 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
612 /* starting to record: compute first+last frames */
614 first_recordable_frame = transport_frame + _capture_offset;
615 last_recordable_frame = max_frames;
616 capture_start_frame = transport_frame;
618 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
620 /* was stopped, now rolling (and recording) */
622 if (_alignment_style == ExistingMaterial) {
623 first_recordable_frame += _session.worst_output_latency();
625 first_recordable_frame += _roll_delay;
630 /* was rolling, but record state changed */
632 if (_alignment_style == ExistingMaterial) {
635 if (!_session.get_punch_in()) {
637 /* manual punch in happens at the correct transport frame
638 because the user hit a button. but to get alignment correct
639 we have to back up the position of the new region to the
640 appropriate spot given the roll delay.
643 capture_start_frame -= _roll_delay;
645 /* XXX paul notes (august 2005): i don't know why
649 first_recordable_frame += _capture_offset;
653 /* autopunch toggles recording at the precise
654 transport frame, and then the DS waits
655 to start recording for a time that depends
656 on the output latency.
659 first_recordable_frame += _session.worst_output_latency();
664 if (_session.get_punch_in()) {
665 first_recordable_frame += _roll_delay;
667 capture_start_frame -= _roll_delay;
673 if (_flags & Recordable) {
674 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
676 RingBufferNPT<CaptureTransition>::rw_vector transvec;
677 (*chan).capture_transition_buf->get_write_vector(&transvec);
679 if (transvec.len[0] > 0) {
680 transvec.buf[0]->type = CaptureStart;
681 transvec.buf[0]->capture_val = capture_start_frame;
682 (*chan).capture_transition_buf->increment_write_ptr(1);
686 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
692 } else if (!record_enabled() || !can_record) {
696 last_recordable_frame = transport_frame + _capture_offset;
698 if (_alignment_style == ExistingMaterial) {
699 last_recordable_frame += _session.worst_output_latency();
701 last_recordable_frame += _roll_delay;
705 last_possibly_recording = possibly_recording;
709 DiskStream::process (jack_nframes_t transport_frame, jack_nframes_t nframes, jack_nframes_t offset, bool can_record, bool rec_monitors_input)
712 ChannelList::iterator c;
714 jack_nframes_t rec_offset = 0;
715 jack_nframes_t rec_nframes = 0;
716 bool nominally_recording;
717 bool re = record_enabled ();
718 bool collect_playback = false;
720 /* if we've already processed the frames corresponding to this call,
721 just return. this allows multiple routes that are taking input
722 from this diskstream to call our ::process() method, but have
723 this stuff only happen once. more commonly, it allows both
724 the AudioTrack that is using this DiskStream *and* the Session
725 to call process() without problems.
732 check_record_status (transport_frame, nframes, can_record);
734 nominally_recording = (can_record && re);
741 /* This lock is held until the end of DiskStream::commit, so these two functions
742 must always be called as a pair. The only exception is if this function
743 returns a non-zero value, in which case, ::commit should not be called.
746 if (pthread_mutex_trylock (state_lock.mutex())) {
750 adjust_capture_position = 0;
752 for (c = channels.begin(); c != channels.end(); ++c) {
753 (*c).current_capture_buffer = 0;
754 (*c).current_playback_buffer = 0;
757 if (nominally_recording || (_session.get_record_enabled() && _session.get_punch_in())) {
760 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
767 case OverlapInternal:
768 /* ---------- recrange
771 rec_nframes = nframes;
776 /* |--------| recrange
779 rec_nframes = transport_frame + nframes - first_recordable_frame;
781 rec_offset = first_recordable_frame - transport_frame;
786 /* |--------| recrange
789 rec_nframes = last_recordable_frame - transport_frame;
793 case OverlapExternal:
794 /* |--------| recrange
795 -------------- transrange
797 rec_nframes = last_recordable_frame - last_recordable_frame;
798 rec_offset = first_recordable_frame - transport_frame;
802 if (rec_nframes && !was_recording) {
803 capture_captured = 0;
804 was_recording = true;
809 if (can_record && !_last_capture_regions.empty()) {
810 _last_capture_regions.clear ();
813 if (nominally_recording || rec_nframes) {
815 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
817 ChannelInfo& chan (*c);
819 chan.capture_buf->get_write_vector (&chan.capture_vector);
821 if (rec_nframes <= chan.capture_vector.len[0]) {
823 chan.current_capture_buffer = chan.capture_vector.buf[0];
825 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
829 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
833 jack_nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
835 if (rec_nframes > total) {
840 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
841 jack_nframes_t first = chan.capture_vector.len[0];
843 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
844 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
845 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
846 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
848 chan.current_capture_buffer = chan.capture_wrap_buffer;
855 finish_capture (rec_monitors_input);
862 /* data will be written to disk */
864 if (rec_nframes == nframes && rec_offset == 0) {
866 for (c = channels.begin(); c != channels.end(); ++c) {
867 (*c).current_playback_buffer = (*c).current_capture_buffer;
870 playback_distance = nframes;
875 /* we can't use the capture buffer as the playback buffer, because
876 we recorded only a part of the current process' cycle data
880 collect_playback = true;
883 adjust_capture_position = rec_nframes;
885 } else if (nominally_recording) {
887 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
889 for (c = channels.begin(); c != channels.end(); ++c) {
890 (*c).current_playback_buffer = (*c).current_capture_buffer;
893 playback_distance = nframes;
897 collect_playback = true;
900 if (collect_playback) {
902 /* we're doing playback */
904 jack_nframes_t necessary_samples;
906 /* no varispeed playback if we're recording, because the output .... TBD */
908 if (rec_nframes == 0 && _actual_speed != 1.0f) {
909 necessary_samples = (jack_nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
911 necessary_samples = nframes;
914 for (c = channels.begin(); c != channels.end(); ++c) {
915 (*c).playback_buf->get_read_vector (&(*c).playback_vector);
920 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
922 ChannelInfo& chan (*c);
924 if (necessary_samples <= chan.playback_vector.len[0]) {
926 chan.current_playback_buffer = chan.playback_vector.buf[0];
929 jack_nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
931 if (necessary_samples > total) {
937 memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
938 chan.playback_vector.len[0] * sizeof (Sample));
939 memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1],
940 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
942 chan.current_playback_buffer = chan.playback_wrap_buffer;
947 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
949 uint64_t phase = last_phase;
950 jack_nframes_t i = 0;
952 // Linearly interpolate into the alt buffer
953 // using 40.24 fixp maths (swh)
955 for (c = channels.begin(); c != channels.end(); ++c) {
958 ChannelInfo& chan (*c);
963 for (jack_nframes_t outsample = 0; outsample < nframes; ++outsample) {
965 fr = (phase & 0xFFFFFF) / 16777216.0f;
966 chan.speed_buffer[outsample] =
967 chan.current_playback_buffer[i] * (1.0f - fr) +
968 chan.current_playback_buffer[i+1] * fr;
972 chan.current_playback_buffer = chan.speed_buffer;
975 playback_distance = i + 1;
976 last_phase = (phase & 0xFFFFFF);
979 playback_distance = nframes;
991 /* we're exiting with failure, so ::commit will not
992 be called. unlock the state lock.
995 pthread_mutex_unlock (state_lock.mutex());
1002 DiskStream::recover ()
1004 pthread_mutex_unlock (state_lock.mutex());
1009 DiskStream::commit (jack_nframes_t nframes)
1011 bool need_butler = false;
1013 if (_actual_speed < 0.0) {
1014 playback_sample -= playback_distance;
1016 playback_sample += playback_distance;
1019 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1021 (*chan).playback_buf->increment_read_ptr (playback_distance);
1023 if (adjust_capture_position) {
1024 (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
1028 if (adjust_capture_position != 0) {
1029 capture_captured += adjust_capture_position;
1030 adjust_capture_position = 0;
1034 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
1036 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
1037 || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
1040 pthread_mutex_unlock (state_lock.mutex());
1048 DiskStream::set_pending_overwrite (bool yn)
1050 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
1052 pending_overwrite = yn;
1054 overwrite_frame = playback_sample;
1055 overwrite_offset = channels.front().playback_buf->get_read_ptr();
1059 DiskStream::overwrite_existing_buffers ()
1061 Sample* mixdown_buffer;
1065 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1067 overwrite_queued = false;
1069 /* assume all are the same size */
1070 jack_nframes_t size = channels[0].playback_buf->bufsize();
1072 mixdown_buffer = new Sample[size];
1073 gain_buffer = new float[size];
1074 workbuf = new char[size*4];
1076 /* reduce size so that we can fill the buffer correctly. */
1080 jack_nframes_t start;
1082 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1084 start = overwrite_frame;
1085 jack_nframes_t cnt = size;
1087 /* to fill the buffer without resetting the playback sample, we need to
1088 do it one or two chunks (normally two).
1090 |----------------------------------------------------------------------|
1094 |<- second chunk->||<----------------- first chunk ------------------>|
1098 jack_nframes_t to_read = size - overwrite_offset;
1100 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, workbuf,
1101 start, to_read, *chan, n, reversed)) {
1102 error << string_compose(_("DiskStream %1: when refilling, cannot read %2 from playlist at frame %3"),
1103 _id, size, playback_sample) << endmsg;
1107 if (cnt > to_read) {
1111 if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer, workbuf,
1112 start, cnt, *chan, n, reversed)) {
1113 error << string_compose(_("DiskStream %1: when refilling, cannot read %2 from playlist at frame %3"),
1114 _id, size, playback_sample) << endmsg;
1123 pending_overwrite = false;
1124 delete [] gain_buffer;
1125 delete [] mixdown_buffer;
1131 DiskStream::seek (jack_nframes_t frame, bool complete_refill)
1133 LockMonitor lm (state_lock, __LINE__, __FILE__);
1136 ChannelList::iterator chan;
1138 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1139 (*chan).playback_buf->reset ();
1140 (*chan).capture_buf->reset ();
1141 if ((*chan).write_source) {
1142 (*chan).write_source->seek (frame);
1146 playback_sample = frame;
1149 if (complete_refill) {
1150 while ((ret = do_refill (0, 0, 0)) > 0);
1152 ret = do_refill (0, 0, 0);
1159 DiskStream::can_internal_playback_seek (jack_nframes_t distance)
1161 ChannelList::iterator chan;
1163 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1164 if ((*chan).playback_buf->read_space() < distance) {
1172 DiskStream::internal_playback_seek (jack_nframes_t distance)
1174 ChannelList::iterator chan;
1176 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1177 (*chan).playback_buf->increment_read_ptr (distance);
1180 first_recordable_frame += distance;
1181 playback_sample += distance;
1187 DiskStream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, char * workbuf, jack_nframes_t& start, jack_nframes_t cnt,
1188 ChannelInfo& channel_info, int channel, bool reversed)
1190 jack_nframes_t this_read = 0;
1191 bool reloop = false;
1192 jack_nframes_t loop_end = 0;
1193 jack_nframes_t loop_start = 0;
1194 jack_nframes_t loop_length = 0;
1195 jack_nframes_t offset = 0;
1199 /* Make the use of a Location atomic for this read operation.
1201 Note: Locations don't get deleted, so all we care about
1202 when I say "atomic" is that we are always pointing to
1203 the same one and using a start/length values obtained
1207 if ((loc = loop_location) != 0) {
1208 loop_start = loc->start();
1209 loop_end = loc->end();
1210 loop_length = loop_end - loop_start;
1213 /* if we are looping, ensure that the first frame we read is at the correct
1214 position within the loop.
1217 if (loc && start >= loop_end) {
1218 //cerr << "start adjusted from " << start;
1219 start = loop_start + ((start - loop_start) % loop_length);
1220 //cerr << "to " << start << endl;
1222 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1227 /* take any loop into account. we can't read past the end of the loop. */
1229 if (loc && (loop_end - start < cnt)) {
1230 this_read = loop_end - start;
1231 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1238 if (this_read == 0) {
1242 this_read = min(cnt,this_read);
1244 if (_playlist->read (buf+offset, mixdown_buffer, gain_buffer, workbuf, start, this_read, channel) != this_read) {
1245 error << string_compose(_("DiskStream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1250 _read_data_count = _playlist->read_data_count();
1254 /* don't adjust start, since caller has already done that
1257 swap_by_ptr (buf, buf + this_read - 1);
1261 /* if we read to the end of the loop, go back to the beginning */
1271 offset += this_read;
1278 DiskStream::do_refill (Sample* mixdown_buffer, float* gain_buffer, char * workbuf)
1281 jack_nframes_t to_read;
1282 RingBufferNPT<Sample>::rw_vector vector;
1286 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1287 jack_nframes_t total_space;
1288 jack_nframes_t zero_fill;
1290 ChannelList::iterator i;
1293 channels.front().playback_buf->get_write_vector (&vector);
1295 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1299 /* if there are 2+ chunks of disk i/o possible for
1300 this track, let the caller know so that it can arrange
1301 for us to be called again, ASAP.
1304 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1308 /* if we're running close to normal speed and there isn't enough
1309 space to do disk_io_chunk_frames of I/O, then don't bother.
1311 at higher speeds, just do it because the sync between butler
1312 and audio thread may not be good enough.
1315 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1319 /* when slaved, don't try to get too close to the read pointer. this
1320 leaves space for the buffer reversal to have something useful to
1324 if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1328 total_space = min (disk_io_chunk_frames, total_space);
1332 if (file_frame == 0) {
1334 /* at start: nothing to do but fill with silence */
1336 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1338 ChannelInfo& chan (*i);
1339 chan.playback_buf->get_write_vector (&vector);
1340 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1341 if (vector.len[1]) {
1342 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1344 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1349 if (file_frame < total_space) {
1351 /* too close to the start: read what we can,
1352 and then zero fill the rest
1355 zero_fill = total_space - file_frame;
1356 total_space = file_frame;
1361 /* move read position backwards because we are going
1362 to reverse the data.
1365 file_frame -= total_space;
1371 if (file_frame == max_frames) {
1373 /* at end: nothing to do but fill with silence */
1375 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1377 ChannelInfo& chan (*i);
1378 chan.playback_buf->get_write_vector (&vector);
1379 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1380 if (vector.len[1]) {
1381 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1383 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1388 if (file_frame > max_frames - total_space) {
1390 /* to close to the end: read what we can, and zero fill the rest */
1392 zero_fill = total_space - (max_frames - file_frame);
1393 total_space = max_frames - file_frame;
1400 /* Please note: the code to allocate buffers isn't run
1401 during normal butler thread operation. Its there
1402 for other times when we need to call do_refill()
1403 from somewhere other than the butler thread.
1406 if (mixdown_buffer == 0) {
1407 mixdown_buffer = new Sample[disk_io_chunk_frames];
1408 free_mixdown = true;
1410 free_mixdown = false;
1413 if (gain_buffer == 0) {
1414 gain_buffer = new float[disk_io_chunk_frames];
1421 workbuf = new char[disk_io_chunk_frames * 4];
1422 free_workbuf = true;
1424 free_workbuf = false;
1427 jack_nframes_t file_frame_tmp = 0;
1429 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1431 ChannelInfo& chan (*i);
1434 jack_nframes_t len1, len2;
1436 chan.playback_buf->get_write_vector (&vector);
1439 file_frame_tmp = file_frame;
1442 buf1 = vector.buf[1];
1443 len1 = vector.len[1];
1444 buf2 = vector.buf[0];
1445 len2 = vector.len[0];
1447 buf1 = vector.buf[0];
1448 len1 = vector.len[0];
1449 buf2 = vector.buf[1];
1450 len2 = vector.len[1];
1454 to_read = min (ts, len1);
1455 to_read = min (to_read, disk_io_chunk_frames);
1459 if (read (buf1, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1464 chan.playback_buf->increment_write_ptr (to_read);
1468 to_read = min (ts, len2);
1473 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1474 so read some or all of vector.len[1] as well.
1477 if (read (buf2, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1482 chan.playback_buf->increment_write_ptr (to_read);
1491 file_frame = file_frame_tmp;
1495 delete [] mixdown_buffer;
1498 delete [] gain_buffer;
1508 DiskStream::do_flush (char * workbuf, bool force_flush)
1512 RingBufferNPT<Sample>::rw_vector vector;
1513 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1514 jack_nframes_t total;
1516 /* important note: this function will write *AT MOST*
1517 disk_io_chunk_frames of data to disk. it will never
1518 write more than that. if its writes that much and there
1519 is more than that waiting to be written, it will return 1,
1520 otherwise 0 on success or -1 on failure.
1522 if there is less than disk_io_chunk_frames to be written,
1523 no data will be written at all unless `force_flush' is true.
1526 _write_data_count = 0;
1528 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1530 (*chan).capture_buf->get_read_vector (&vector);
1532 total = vector.len[0] + vector.len[1];
1535 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1540 /* if there are 2+ chunks of disk i/o possible for
1541 this track, let the caller know so that it can arrange
1542 for us to be called again, ASAP.
1544 if we are forcing a flush, then if there is* any* extra
1545 work, let the caller know.
1547 if we are no longer recording and there is any extra work,
1548 let the caller know too.
1551 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1555 to_write = min (disk_io_chunk_frames, (jack_nframes_t) vector.len[0]);
1558 // check the transition buffer when recording destructive
1559 // important that we get this after the capture buf
1561 if (destructive()) {
1562 (*chan).capture_transition_buf->get_read_vector(&transvec);
1563 size_t transcount = transvec.len[0] + transvec.len[1];
1564 bool have_start = false;
1567 for (ti=0; ti < transcount; ++ti) {
1568 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1570 if (captrans.type == CaptureStart) {
1571 // by definition, the first data we got above represents the given capture pos
1573 (*chan).write_source->mark_capture_start (captrans.capture_val);
1574 (*chan).curr_capture_cnt = 0;
1578 else if (captrans.type == CaptureEnd) {
1580 // capture end, the capture_val represents total frames in capture
1582 if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1584 // shorten to make the write a perfect fit
1585 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt);
1587 if (nto_write < to_write) {
1588 ret = 1; // should we?
1590 to_write = nto_write;
1592 (*chan).write_source->mark_capture_end ();
1594 // increment past this transition, but go no further
1599 // actually ends just beyond this chunk, so force more work
1607 (*chan).capture_transition_buf->increment_read_ptr(ti);
1613 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write, workbuf) != to_write) {
1614 error << string_compose(_("DiskStream %1: cannot write to disk"), _id) << endmsg;
1618 (*chan).capture_buf->increment_read_ptr (to_write);
1619 (*chan).curr_capture_cnt += to_write;
1621 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1623 /* we wrote all of vector.len[0] but it wasn't an entire
1624 disk_io_chunk_frames of data, so arrange for some part
1625 of vector.len[1] to be flushed to disk as well.
1628 to_write = min ((jack_nframes_t)(disk_io_chunk_frames - to_write), (jack_nframes_t) vector.len[1]);
1630 if ((*chan).write_source->write (vector.buf[1], to_write, workbuf) != to_write) {
1631 error << string_compose(_("DiskStream %1: cannot write to disk"), _id) << endmsg;
1635 _write_data_count += (*chan).write_source->write_data_count();
1637 (*chan).capture_buf->increment_read_ptr (to_write);
1638 (*chan).curr_capture_cnt += to_write;
1647 DiskStream::playlist_changed (Change ignored)
1649 playlist_modified ();
1653 DiskStream::playlist_modified ()
1655 if (!i_am_the_modifier && !overwrite_queued) {
1656 _session.request_overwrite_buffer (this);
1657 overwrite_queued = true;
1662 DiskStream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1664 uint32_t buffer_position;
1665 bool more_work = true;
1667 AudioRegion* region = 0;
1668 jack_nframes_t total_capture;
1669 AudioRegion::SourceList srcs;
1670 AudioRegion::SourceList::iterator src;
1671 ChannelList::iterator chan;
1672 vector<CaptureInfo*>::iterator ci;
1674 list<Source*>* deletion_list;
1675 bool mark_write_completed = false;
1677 finish_capture (true);
1679 /* butler is already stopped, but there may be work to do
1680 to flush remaining data to disk.
1683 while (more_work && !err) {
1684 switch (do_flush ( _session.conversion_buffer(Session::TransportContext), true)) {
1691 error << string_compose(_("DiskStream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1696 /* XXX is there anything we can do if err != 0 ? */
1697 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
1699 if (capture_info.empty()) {
1703 if (abort_capture) {
1705 ChannelList::iterator chan;
1707 deletion_list = new list<Source*>;
1709 for ( chan = channels.begin(); chan != channels.end(); ++chan) {
1711 if ((*chan).write_source) {
1713 (*chan).write_source->mark_for_remove ();
1714 (*chan).write_source->release ();
1716 deletion_list->push_back ((*chan).write_source);
1718 (*chan).write_source = 0;
1721 /* new source set up in "out" below */
1724 if (!deletion_list->empty()) {
1725 DeleteSources (deletion_list);
1727 delete deletion_list;
1733 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1734 total_capture += (*ci)->frames;
1737 /* figure out the name for this take */
1739 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1741 Source* s = (*chan).write_source;
1749 if ((fsrc = dynamic_cast<FileSource *>(s)) != 0) {
1750 fsrc->update_header (capture_info.front()->start, when, twhen);
1753 s->set_captured_for (_name);
1758 /* destructive tracks have a single, never changing region */
1760 if (destructive()) {
1762 /* send a signal that any UI can pick up to do the right thing. there is
1763 a small problem here in that a UI may need the peak data to be ready
1764 for the data that was recorded and this isn't interlocked with that
1765 process. this problem is deferred to the UI.
1768 _playlist->Modified();
1772 /* Register a new region with the Session that
1773 describes the entire source. Do this first
1774 so that any sub-regions will obviously be
1775 children of this one (later!)
1779 region = new AudioRegion (srcs, channels[0].write_source->last_capture_start_frame(), total_capture,
1780 region_name_from_path (channels[0].write_source->name()),
1781 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
1783 region->special_set_position (capture_info.front()->start);
1787 catch (failed_constructor& err) {
1788 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1792 _last_capture_regions.push_back (region);
1794 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1796 _session.add_undo (_playlist->get_memento());
1797 _playlist->freeze ();
1799 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1802 _session.region_name (region_name, _name, false);
1804 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1807 region = new AudioRegion (srcs, buffer_position, (*ci)->frames, region_name);
1810 catch (failed_constructor& err) {
1811 error << _("DiskStream: could not create region for captured audio!") << endmsg;
1812 continue; /* XXX is this OK? */
1815 _last_capture_regions.push_back (region);
1817 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1819 i_am_the_modifier++;
1820 _playlist->add_region (*region, (*ci)->start);
1821 i_am_the_modifier--;
1823 buffer_position += (*ci)->frames;
1827 _session.add_redo_no_execute (_playlist->get_memento());
1830 mark_write_completed = true;
1832 reset_write_sources (mark_write_completed);
1835 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1839 capture_info.clear ();
1840 capture_start_frame = 0;
1844 DiskStream::finish_capture (bool rec_monitors_input)
1846 was_recording = false;
1848 if (capture_captured == 0) {
1852 if (recordable() && destructive()) {
1853 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1855 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1856 (*chan).capture_transition_buf->get_write_vector(&transvec);
1859 if (transvec.len[0] > 0) {
1860 transvec.buf[0]->type = CaptureEnd;
1861 transvec.buf[0]->capture_val = capture_captured;
1862 (*chan).capture_transition_buf->increment_write_ptr(1);
1866 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1872 CaptureInfo* ci = new CaptureInfo;
1874 ci->start = capture_start_frame;
1875 ci->frames = capture_captured;
1877 /* XXX theoretical race condition here. Need atomic exchange ?
1878 However, the circumstances when this is called right
1879 now (either on record-disable or transport_stopped)
1880 mean that no actual race exists. I think ...
1881 We now have a capture_info_lock, but it is only to be used
1882 to synchronize in the transport_stop and the capture info
1883 accessors, so that invalidation will not occur (both non-realtime).
1886 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1888 capture_info.push_back (ci);
1889 capture_captured = 0;
1893 DiskStream::set_record_enabled (bool yn, void* src)
1895 bool rolling = _session.transport_speed() != 0.0f;
1897 if (!recordable() || !_session.record_enabling_legal()) {
1901 /* if we're turning on rec-enable, there needs to be an
1905 if (yn && channels[0].source == 0) {
1907 /* pick up connections not initiated *from* the IO object
1908 we're associated with.
1911 get_input_sources ();
1913 if (channels[0].source == 0) {
1916 CannotRecordNoInput (this); /* emit signal */
1922 /* yes, i know that this not proof against race conditions, but its
1923 good enough. i think.
1926 if (record_enabled() != yn) {
1928 atomic_set (&_record_enabled, 1);
1929 capturing_sources.clear ();
1930 if (Config->get_use_hardware_monitoring()) {
1931 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1932 if ((*chan).source) {
1933 (*chan).source->request_monitor_input (!(_session.get_auto_input() && rolling));
1935 capturing_sources.push_back ((*chan).write_source);
1938 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1939 capturing_sources.push_back ((*chan).write_source);
1944 atomic_set (&_record_enabled, 0);
1945 if (Config->get_use_hardware_monitoring()) {
1946 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1947 if ((*chan).source) {
1948 (*chan).source->request_monitor_input (false);
1952 capturing_sources.clear ();
1955 record_enable_changed (src); /* EMIT SIGNAL */
1960 DiskStream::get_state ()
1962 XMLNode* node = new XMLNode ("DiskStream");
1964 LocaleGuard lg (X_("POSIX"));
1966 snprintf (buf, sizeof(buf), "%zd", channels.size());
1967 node->add_property ("channels", buf);
1969 node->add_property ("playlist", _playlist->name());
1971 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1972 node->add_property ("speed", buf);
1974 node->add_property("name", _name);
1975 snprintf (buf, sizeof(buf), "%" PRIu64, id());
1976 node->add_property("id", buf);
1978 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1980 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1981 XMLNode* cs_grandchild;
1983 for (vector<FileSource*>::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1984 cs_grandchild = new XMLNode (X_("file"));
1985 cs_grandchild->add_property (X_("path"), (*i)->path());
1986 cs_child->add_child_nocopy (*cs_grandchild);
1989 /* store the location where capture will start */
1993 if (_session.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1994 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1996 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1999 cs_child->add_property (X_("at"), buf);
2000 node->add_child_nocopy (*cs_child);
2004 node->add_child_copy (*_extra_xml);
2011 DiskStream::set_state (const XMLNode& node)
2013 const XMLProperty* prop;
2014 XMLNodeList nlist = node.children();
2015 XMLNodeIterator niter;
2016 uint32_t nchans = 1;
2017 XMLNode* capture_pending_node = 0;
2018 LocaleGuard lg (X_("POSIX"));
2020 in_set_state = true;
2022 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2023 if ((*niter)->name() == IO::state_node_name) {
2024 deprecated_io_node = new XMLNode (**niter);
2027 if ((*niter)->name() == X_("CapturingSources")) {
2028 capture_pending_node = *niter;
2032 /* prevent write sources from being created */
2034 in_set_state = true;
2036 if ((prop = node.property ("name")) != 0) {
2037 _name = prop->value();
2040 if (deprecated_io_node) {
2041 if ((prop = deprecated_io_node->property ("id")) != 0) {
2042 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2045 if ((prop = node.property ("id")) != 0) {
2046 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2050 if ((prop = node.property ("channels")) != 0) {
2051 nchans = atoi (prop->value().c_str());
2054 // create necessary extra channels
2055 // we are always constructed with one
2056 // and we always need one
2058 if (nchans > _n_channels) {
2060 // we need to add new channel infos
2061 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2063 int diff = nchans - channels.size();
2065 for (int i=0; i < diff; ++i) {
2069 } else if (nchans < _n_channels) {
2071 // we need to get rid of channels
2072 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2074 int diff = channels.size() - nchans;
2076 for (int i = 0; i < diff; ++i) {
2081 if ((prop = node.property ("playlist")) == 0) {
2086 bool had_playlist = (_playlist != 0);
2088 if (find_and_use_playlist (prop->value())) {
2092 if (!had_playlist) {
2093 _playlist->set_orig_diskstream_id (_id);
2096 if (capture_pending_node) {
2097 use_pending_capture_data (*capture_pending_node);
2102 if ((prop = node.property ("speed")) != 0) {
2103 double sp = atof (prop->value().c_str());
2105 if (realtime_set_speed (sp, false)) {
2106 non_realtime_set_speed ();
2110 _n_channels = channels.size();
2112 in_set_state = false;
2114 /* make sure this is clear before we do anything else */
2116 capturing_sources.clear ();
2118 /* write sources are handled elsewhere;
2119 for destructive tracks: in {setup,use}_destructive_playlist()
2120 for non-destructive: when we handle the input set up of the IO that owns this DS
2123 in_set_state = false;
2129 DiskStream::use_new_write_source (uint32_t n)
2131 if (!recordable()) {
2135 if (n >= channels.size()) {
2136 error << string_compose (_("DiskStream: channel %1 out of range"), n) << endmsg;
2140 ChannelInfo &chan = channels[n];
2142 if (chan.write_source) {
2144 if (FileSource::is_empty (chan.write_source->path())) {
2145 chan.write_source->mark_for_remove ();
2146 chan.write_source->release();
2147 delete chan.write_source;
2149 chan.write_source->release();
2150 chan.write_source = 0;
2155 if ((chan.write_source = _session.create_file_source (*this, n, destructive())) == 0) {
2156 throw failed_constructor();
2160 catch (failed_constructor &err) {
2161 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2162 chan.write_source = 0;
2166 chan.write_source->use ();
2172 DiskStream::reset_write_sources (bool mark_write_complete, bool force)
2174 ChannelList::iterator chan;
2177 if (!recordable()) {
2181 if (!force && destructive()) {
2183 /* make sure we always have enough sources for the current channel count */
2185 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2186 if ((*chan).write_source == 0) {
2191 if (chan == channels.end()) {
2195 /* some channels do not have a write source */
2198 capturing_sources.clear ();
2200 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2201 if ((*chan).write_source && mark_write_complete) {
2202 (*chan).write_source->mark_streaming_write_completed ();
2204 use_new_write_source (n);
2205 if (record_enabled()) {
2206 capturing_sources.push_back ((*chan).write_source);
2212 DiskStream::set_block_size (jack_nframes_t nframes)
2214 if (_session.get_block_size() > speed_buffer_size) {
2215 speed_buffer_size = _session.get_block_size();
2217 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2218 if ((*chan).speed_buffer) delete [] (*chan).speed_buffer;
2219 (*chan).speed_buffer = new Sample[speed_buffer_size];
2222 allocate_temporary_buffers ();
2226 DiskStream::allocate_temporary_buffers ()
2228 /* make sure the wrap buffer is at least large enough to deal
2229 with the speeds up to 1.2, to allow for micro-variation
2230 when slaving to MTC, SMPTE etc.
2233 double sp = max (fabsf (_actual_speed), 1.2f);
2234 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * sp) + 1;
2236 if (required_wrap_size > wrap_buffer_size) {
2238 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2239 if ((*chan).playback_wrap_buffer) delete [] (*chan).playback_wrap_buffer;
2240 (*chan).playback_wrap_buffer = new Sample[required_wrap_size];
2241 if ((*chan).capture_wrap_buffer) delete [] (*chan).capture_wrap_buffer;
2242 (*chan).capture_wrap_buffer = new Sample[required_wrap_size];
2245 wrap_buffer_size = required_wrap_size;
2250 DiskStream::monitor_input (bool yn)
2252 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2254 if ((*chan).source) {
2255 (*chan).source->request_monitor_input (yn);
2261 DiskStream::set_capture_offset ()
2264 /* can't capture, so forget it */
2268 _capture_offset = _io->input_latency();
2272 DiskStream::set_persistent_align_style (AlignStyle a)
2274 _persistent_alignment_style = a;
2278 DiskStream::set_align_style_from_io ()
2280 bool have_physical = false;
2286 get_input_sources ();
2288 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2289 if ((*chan).source && (*chan).source->flags() & JackPortIsPhysical) {
2290 have_physical = true;
2295 if (have_physical) {
2296 set_align_style (ExistingMaterial);
2298 set_align_style (CaptureTime);
2303 DiskStream::set_align_style (AlignStyle a)
2305 if (record_enabled() && _session.actively_recording()) {
2310 if (a != _alignment_style) {
2311 _alignment_style = a;
2312 AlignmentStyleChanged ();
2317 DiskStream::add_channel ()
2319 /* XXX need to take lock??? */
2323 init_channel (chan);
2325 chan.speed_buffer = new Sample[speed_buffer_size];
2326 chan.playback_wrap_buffer = new Sample[wrap_buffer_size];
2327 chan.capture_wrap_buffer = new Sample[wrap_buffer_size];
2329 channels.push_back (chan);
2331 _n_channels = channels.size();
2337 DiskStream::remove_channel ()
2339 if (channels.size() > 1) {
2340 /* XXX need to take lock??? */
2341 ChannelInfo & chan = channels.back();
2342 destroy_channel (chan);
2343 channels.pop_back();
2345 _n_channels = channels.size();
2353 DiskStream::playback_buffer_load () const
2355 return (float) ((double) channels.front().playback_buf->read_space()/
2356 (double) channels.front().playback_buf->bufsize());
2360 DiskStream::capture_buffer_load () const
2362 return (float) ((double) channels.front().capture_buf->write_space()/
2363 (double) channels.front().capture_buf->bufsize());
2367 DiskStream::set_loop (Location *location)
2370 if (location->start() >= location->end()) {
2371 error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
2376 loop_location = location;
2378 LoopSet (location); /* EMIT SIGNAL */
2383 DiskStream::get_capture_start_frame (uint32_t n)
2385 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
2387 if (capture_info.size() > n) {
2388 return capture_info[n]->start;
2391 return capture_start_frame;
2396 DiskStream::get_captured_frames (uint32_t n)
2398 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
2400 if (capture_info.size() > n) {
2401 return capture_info[n]->frames;
2404 return capture_captured;
2409 DiskStream::punch_in ()
2414 DiskStream::punch_out ()
2419 DiskStream::use_pending_capture_data (XMLNode& node)
2421 const XMLProperty* prop;
2422 XMLNodeList nlist = node.children();
2423 XMLNodeIterator niter;
2425 FileSource* first_fs = 0;
2426 AudioRegion::SourceList pending_sources;
2427 jack_nframes_t position;
2429 if ((prop = node.property (X_("at"))) == 0) {
2433 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2437 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2438 if ((*niter)->name() == X_("file")) {
2440 if ((prop = (*niter)->property (X_("path"))) == 0) {
2445 fs = new FileSource (prop->value(), _session.frame_rate(), true);
2448 catch (failed_constructor& err) {
2449 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2450 _name, prop->value())
2455 pending_sources.push_back (fs);
2457 if (first_fs == 0) {
2461 fs->set_captured_for (_name);
2465 if (pending_sources.size() == 0) {
2466 /* nothing can be done */
2470 if (pending_sources.size() != _n_channels) {
2471 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2476 AudioRegion* region;
2479 region = new AudioRegion (pending_sources, 0, first_fs->length(),
2480 region_name_from_path (first_fs->name()),
2481 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
2483 region->special_set_position (0);
2486 catch (failed_constructor& err) {
2487 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2495 region = new AudioRegion (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name()));
2498 catch (failed_constructor& err) {
2499 error << string_compose (_("%1: cannot create region from pending capture sources"),
2506 _playlist->add_region (*region, position);
2512 DiskStream::set_roll_delay (jack_nframes_t nframes)
2514 _roll_delay = nframes;
2518 DiskStream::set_destructive (bool yn)
2520 if (yn != destructive()) {
2521 reset_write_sources (true, true);
2523 _flags |= Destructive;
2525 _flags &= ~Destructive;