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 */
80 setup_destructive_playlist ();
83 DiskStreamCreated (this); /* EMIT SIGNAL */
86 DiskStream::DiskStream (Session& sess, const XMLNode& node)
93 if (set_state (node)) {
95 throw failed_constructor();
101 use_destructive_playlist ();
104 DiskStreamCreated (this); /* EMIT SIGNAL */
108 DiskStream::init_channel (ChannelInfo &chan)
110 chan.playback_wrap_buffer = 0;
111 chan.capture_wrap_buffer = 0;
112 chan.speed_buffer = 0;
113 chan.peak_power = 0.0f;
114 chan.write_source = 0;
116 chan.current_capture_buffer = 0;
117 chan.current_playback_buffer = 0;
118 chan.curr_capture_cnt = 0;
120 chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
121 chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
122 chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
125 /* touch the ringbuffer buffers, which will cause
126 them to be mapped into locked physical RAM if
127 we're running with mlockall(). this doesn't do
130 memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
131 memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
132 memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
137 DiskStream::init (Flag f)
143 _alignment_style = ExistingMaterial;
144 _persistent_alignment_style = ExistingMaterial;
145 first_input_change = true;
147 i_am_the_modifier = 0;
148 atomic_set (&_record_enabled, 0);
149 was_recording = false;
150 capture_start_frame = 0;
151 capture_captured = 0;
152 _visible_speed = 1.0f;
153 _actual_speed = 1.0f;
154 _buffer_reallocation_required = false;
155 _seek_required = false;
156 first_recordable_frame = max_frames;
157 last_recordable_frame = max_frames;
162 adjust_capture_position = 0;
163 last_possibly_recording = 0;
165 wrap_buffer_size = 0;
166 speed_buffer_size = 0;
168 phi = (uint64_t) (0x1000000);
171 playback_distance = 0;
172 _read_data_count = 0;
173 _write_data_count = 0;
174 deprecated_io_node = 0;
176 /* there are no channels at this point, so these
177 two calls just get speed_buffer_size and wrap_buffer
178 size setup without duplicating their code.
181 set_block_size (_session.get_block_size());
182 allocate_temporary_buffers ();
184 pending_overwrite = false;
186 overwrite_queued = false;
187 input_change_pending = NoChange;
194 DiskStream::destroy_channel (ChannelInfo &chan)
196 if (chan.write_source) {
197 chan.write_source->release ();
198 chan.write_source = 0;
201 if (chan.speed_buffer) {
202 delete [] chan.speed_buffer;
205 if (chan.playback_wrap_buffer) {
206 delete [] chan.playback_wrap_buffer;
208 if (chan.capture_wrap_buffer) {
209 delete [] chan.capture_wrap_buffer;
212 delete chan.playback_buf;
213 delete chan.capture_buf;
214 delete chan.capture_transition_buf;
216 chan.playback_buf = 0;
217 chan.capture_buf = 0;
220 DiskStream::~DiskStream ()
222 LockMonitor lm (state_lock, __LINE__, __FILE__);
228 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
229 destroy_channel((*chan));
236 DiskStream::handle_input_change (IOChange change, void *src)
238 LockMonitor lm (state_lock, __LINE__, __FILE__);
240 if (!(input_change_pending & change)) {
241 input_change_pending = IOChange (input_change_pending|change);
242 _session.request_input_change_handling ();
247 DiskStream::non_realtime_input_change ()
250 LockMonitor lm (state_lock, __LINE__, __FILE__);
252 if (input_change_pending == NoChange) {
256 if (input_change_pending & ConfigurationChanged) {
258 if (_io->n_inputs() > _n_channels) {
260 // we need to add new channel infos
262 int diff = _io->n_inputs() - channels.size();
264 for (int i = 0; i < diff; ++i) {
268 } else if (_io->n_inputs() < _n_channels) {
270 // we need to get rid of channels
272 int diff = channels.size() - _io->n_inputs();
274 for (int i = 0; i < diff; ++i) {
280 get_input_sources ();
281 set_capture_offset ();
283 if (first_input_change) {
284 set_align_style (_persistent_alignment_style);
285 first_input_change = false;
287 set_align_style_from_io ();
290 input_change_pending = NoChange;
293 /* reset capture files */
295 reset_write_sources (false);
297 /* now refill channel buffers */
299 if (speed() != 1.0f || speed() != -1.0f) {
300 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()));
303 seek (_session.transport_frame());
308 DiskStream::get_input_sources ()
310 uint32_t ni = _io->n_inputs();
312 for (uint32_t n = 0; n < ni; ++n) {
314 const char **connections = _io->input(n)->get_connections ();
315 ChannelInfo& chan = channels[n];
317 if (connections == 0 || connections[0] == 0) {
320 // _source->disable_metering ();
326 chan.source = _session.engine().get_port_by_name (connections[0]);
336 DiskStream::find_and_use_playlist (const string& name)
339 AudioPlaylist* playlist;
341 if ((pl = _session.get_playlist (name)) == 0) {
342 error << string_compose(_("DiskStream: Session doesn't know about a Playlist called \"%1\""), name) << endmsg;
346 if ((playlist = dynamic_cast<AudioPlaylist*> (pl)) == 0) {
347 error << string_compose(_("DiskStream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
351 return use_playlist (playlist);
355 DiskStream::use_playlist (AudioPlaylist* playlist)
358 LockMonitor lm (state_lock, __LINE__, __FILE__);
360 if (playlist == _playlist) {
364 plstate_connection.disconnect();
365 plmod_connection.disconnect ();
366 plgone_connection.disconnect ();
372 _playlist = playlist;
375 if (!in_set_state && recordable()) {
376 reset_write_sources (false);
379 plstate_connection = _playlist->StateChanged.connect (mem_fun (*this, &DiskStream::playlist_changed));
380 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &DiskStream::playlist_modified));
381 plgone_connection = _playlist->GoingAway.connect (mem_fun (*this, &DiskStream::playlist_deleted));
384 if (!overwrite_queued) {
385 _session.request_overwrite_buffer (this);
386 overwrite_queued = true;
389 PlaylistChanged (); /* EMIT SIGNAL */
390 _session.set_dirty ();
396 DiskStream::playlist_deleted (Playlist* pl)
398 /* this catches an ordering issue with session destruction. playlists
399 are destroyed before diskstreams. we have to invalidate any handles
400 we have to the playlist.
407 DiskStream::use_new_playlist ()
410 AudioPlaylist* playlist;
412 if (!in_set_state && destructive()) {
417 newname = Playlist::bump_name (_playlist->name(), _session);
419 newname = Playlist::bump_name (_name, _session);
422 if ((playlist = new AudioPlaylist (_session, newname, hidden())) != 0) {
423 playlist->set_orig_diskstream_id (id());
424 return use_playlist (playlist);
431 DiskStream::use_copy_playlist ()
437 if (_playlist == 0) {
438 error << string_compose(_("DiskStream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
443 AudioPlaylist* playlist;
445 newname = Playlist::bump_name (_playlist->name(), _session);
447 if ((playlist = new AudioPlaylist (*_playlist, newname)) != 0) {
448 playlist->set_orig_diskstream_id (id());
449 return use_playlist (playlist);
456 DiskStream::setup_destructive_playlist ()
458 AudioRegion::SourceList srcs;
460 /* make sure we have sources for every channel */
462 reset_write_sources (true);
464 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
465 srcs.push_back ((*chan).write_source);
468 /* a single full-sized region */
470 AudioRegion* region = new AudioRegion (srcs, 0, max_frames, _name);
471 _playlist->add_region (*region, 0);
475 DiskStream::use_destructive_playlist ()
477 /* use the sources associated with the single full-extent region */
479 Playlist::RegionList* rl = _playlist->regions_at (0);
482 throw failed_constructor();
485 AudioRegion* region = dynamic_cast<AudioRegion*> (rl->front());
488 throw failed_constructor();
494 ChannelList::iterator chan;
496 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
497 (*chan).write_source = dynamic_cast<FileSource*>(®ion->source (n));
498 (*chan).write_source->set_allow_remove_if_empty (false);
501 /* the source list will never be reset for a destructive track */
505 DiskStream::set_io (IO& io)
508 set_align_style_from_io ();
512 DiskStream::set_name (string str, void *src)
515 _playlist->set_name (str);
518 if (!in_set_state && recordable()) {
519 /* rename existing capture files so that they have the correct name */
520 return rename_write_sources ();
530 DiskStream::set_speed (double sp)
532 _session.request_diskstream_speed (*this, sp);
534 /* to force a rebuffering at the right place */
539 DiskStream::realtime_set_speed (double sp, bool global)
541 bool changed = false;
542 double new_speed = sp * _session.transport_speed();
544 if (_visible_speed != sp) {
549 if (new_speed != _actual_speed) {
551 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() *
552 fabs (new_speed)) + 1;
554 if (required_wrap_size > wrap_buffer_size) {
555 _buffer_reallocation_required = true;
558 _actual_speed = new_speed;
559 phi = (uint64_t) (0x1000000 * fabs(_actual_speed));
564 _seek_required = true;
566 speed_changed (); /* EMIT SIGNAL */
569 return _buffer_reallocation_required || _seek_required;
573 DiskStream::non_realtime_set_speed ()
575 if (_buffer_reallocation_required)
577 LockMonitor lm (state_lock, __LINE__, __FILE__);
578 allocate_temporary_buffers ();
580 _buffer_reallocation_required = false;
583 if (_seek_required) {
584 if (speed() != 1.0f || speed() != -1.0f) {
585 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()), true);
588 seek (_session.transport_frame(), true);
591 _seek_required = false;
596 DiskStream::prepare ()
599 playback_distance = 0;
603 DiskStream::check_record_status (jack_nframes_t transport_frame, jack_nframes_t nframes, bool can_record)
605 int possibly_recording;
608 const int transport_rolling = 0x4;
609 const int track_rec_enabled = 0x2;
610 const int global_rec_enabled = 0x1;
612 /* merge together the 3 factors that affect record status, and compute
616 rolling = _session.transport_speed() != 0.0f;
617 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
618 change = possibly_recording ^ last_possibly_recording;
620 if (possibly_recording == last_possibly_recording) {
626 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
628 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
629 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
631 /* starting to record: compute first+last frames */
633 first_recordable_frame = transport_frame + _capture_offset;
634 last_recordable_frame = max_frames;
635 capture_start_frame = transport_frame;
637 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
639 /* was stopped, now rolling (and recording) */
641 if (_alignment_style == ExistingMaterial) {
642 first_recordable_frame += _session.worst_output_latency();
644 first_recordable_frame += _roll_delay;
649 /* was rolling, but record state changed */
651 if (_alignment_style == ExistingMaterial) {
654 if (!_session.get_punch_in()) {
656 /* manual punch in happens at the correct transport frame
657 because the user hit a button. but to get alignment correct
658 we have to back up the position of the new region to the
659 appropriate spot given the roll delay.
662 capture_start_frame -= _roll_delay;
664 /* XXX paul notes (august 2005): i don't know why
668 first_recordable_frame += _capture_offset;
672 /* autopunch toggles recording at the precise
673 transport frame, and then the DS waits
674 to start recording for a time that depends
675 on the output latency.
678 first_recordable_frame += _session.worst_output_latency();
683 if (_session.get_punch_in()) {
684 first_recordable_frame += _roll_delay;
686 capture_start_frame -= _roll_delay;
692 if (_flags & Recordable) {
693 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
695 RingBufferNPT<CaptureTransition>::rw_vector transvec;
696 (*chan).capture_transition_buf->get_write_vector(&transvec);
698 if (transvec.len[0] > 0) {
699 transvec.buf[0]->type = CaptureStart;
700 transvec.buf[0]->capture_val = capture_start_frame;
701 (*chan).capture_transition_buf->increment_write_ptr(1);
705 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
711 } else if (!record_enabled() || !can_record) {
715 last_recordable_frame = transport_frame + _capture_offset;
717 if (_alignment_style == ExistingMaterial) {
718 last_recordable_frame += _session.worst_output_latency();
720 last_recordable_frame += _roll_delay;
724 last_possibly_recording = possibly_recording;
728 DiskStream::process (jack_nframes_t transport_frame, jack_nframes_t nframes, jack_nframes_t offset, bool can_record, bool rec_monitors_input)
731 ChannelList::iterator c;
733 jack_nframes_t rec_offset = 0;
734 jack_nframes_t rec_nframes = 0;
735 bool nominally_recording;
736 bool re = record_enabled ();
737 bool collect_playback = false;
739 /* if we've already processed the frames corresponding to this call,
740 just return. this allows multiple routes that are taking input
741 from this diskstream to call our ::process() method, but have
742 this stuff only happen once. more commonly, it allows both
743 the AudioTrack that is using this DiskStream *and* the Session
744 to call process() without problems.
751 check_record_status (transport_frame, nframes, can_record);
753 nominally_recording = (can_record && re);
760 /* This lock is held until the end of DiskStream::commit, so these two functions
761 must always be called as a pair. The only exception is if this function
762 returns a non-zero value, in which case, ::commit should not be called.
765 if (pthread_mutex_trylock (state_lock.mutex())) {
769 adjust_capture_position = 0;
771 for (c = channels.begin(); c != channels.end(); ++c) {
772 (*c).current_capture_buffer = 0;
773 (*c).current_playback_buffer = 0;
776 if (nominally_recording || (_session.get_record_enabled() && _session.get_punch_in())) {
779 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
786 case OverlapInternal:
787 /* ---------- recrange
790 rec_nframes = nframes;
795 /* |--------| recrange
798 rec_nframes = transport_frame + nframes - first_recordable_frame;
800 rec_offset = first_recordable_frame - transport_frame;
805 /* |--------| recrange
808 rec_nframes = last_recordable_frame - transport_frame;
812 case OverlapExternal:
813 /* |--------| recrange
814 -------------- transrange
816 rec_nframes = last_recordable_frame - last_recordable_frame;
817 rec_offset = first_recordable_frame - transport_frame;
821 if (rec_nframes && !was_recording) {
822 capture_captured = 0;
823 was_recording = true;
828 if (can_record && !_last_capture_regions.empty()) {
829 _last_capture_regions.clear ();
832 if (nominally_recording || rec_nframes) {
834 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
836 ChannelInfo& chan (*c);
838 chan.capture_buf->get_write_vector (&chan.capture_vector);
840 if (rec_nframes <= chan.capture_vector.len[0]) {
842 chan.current_capture_buffer = chan.capture_vector.buf[0];
844 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
848 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
852 jack_nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
854 if (rec_nframes > total) {
859 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
860 jack_nframes_t first = chan.capture_vector.len[0];
862 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
863 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
864 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
865 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
867 chan.current_capture_buffer = chan.capture_wrap_buffer;
874 finish_capture (rec_monitors_input);
881 /* data will be written to disk */
883 if (rec_nframes == nframes && rec_offset == 0) {
885 for (c = channels.begin(); c != channels.end(); ++c) {
886 (*c).current_playback_buffer = (*c).current_capture_buffer;
889 playback_distance = nframes;
894 /* we can't use the capture buffer as the playback buffer, because
895 we recorded only a part of the current process' cycle data
899 collect_playback = true;
902 adjust_capture_position = rec_nframes;
904 } else if (nominally_recording) {
906 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
908 for (c = channels.begin(); c != channels.end(); ++c) {
909 (*c).current_playback_buffer = (*c).current_capture_buffer;
912 playback_distance = nframes;
916 collect_playback = true;
919 if (collect_playback) {
921 /* we're doing playback */
923 jack_nframes_t necessary_samples;
925 /* no varispeed playback if we're recording, because the output .... TBD */
927 if (rec_nframes == 0 && _actual_speed != 1.0f) {
928 necessary_samples = (jack_nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
930 necessary_samples = nframes;
933 for (c = channels.begin(); c != channels.end(); ++c) {
934 (*c).playback_buf->get_read_vector (&(*c).playback_vector);
939 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
941 ChannelInfo& chan (*c);
943 if (necessary_samples <= chan.playback_vector.len[0]) {
945 chan.current_playback_buffer = chan.playback_vector.buf[0];
948 jack_nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
950 if (necessary_samples > total) {
956 memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
957 chan.playback_vector.len[0] * sizeof (Sample));
958 memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1],
959 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
961 chan.current_playback_buffer = chan.playback_wrap_buffer;
966 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
968 uint64_t phase = last_phase;
969 jack_nframes_t i = 0;
971 // Linearly interpolate into the alt buffer
972 // using 40.24 fixp maths (swh)
974 for (c = channels.begin(); c != channels.end(); ++c) {
977 ChannelInfo& chan (*c);
982 for (jack_nframes_t outsample = 0; outsample < nframes; ++outsample) {
984 fr = (phase & 0xFFFFFF) / 16777216.0f;
985 chan.speed_buffer[outsample] =
986 chan.current_playback_buffer[i] * (1.0f - fr) +
987 chan.current_playback_buffer[i+1] * fr;
991 chan.current_playback_buffer = chan.speed_buffer;
994 playback_distance = i + 1;
995 last_phase = (phase & 0xFFFFFF);
998 playback_distance = nframes;
1010 /* we're exiting with failure, so ::commit will not
1011 be called. unlock the state lock.
1014 pthread_mutex_unlock (state_lock.mutex());
1021 DiskStream::recover ()
1023 pthread_mutex_unlock (state_lock.mutex());
1028 DiskStream::commit (jack_nframes_t nframes)
1030 bool need_butler = false;
1032 if (_actual_speed < 0.0) {
1033 playback_sample -= playback_distance;
1035 playback_sample += playback_distance;
1038 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1040 (*chan).playback_buf->increment_read_ptr (playback_distance);
1042 if (adjust_capture_position) {
1043 (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
1047 if (adjust_capture_position != 0) {
1048 capture_captured += adjust_capture_position;
1049 adjust_capture_position = 0;
1053 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
1055 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
1056 || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
1059 pthread_mutex_unlock (state_lock.mutex());
1067 DiskStream::set_pending_overwrite (bool yn)
1069 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
1071 pending_overwrite = yn;
1073 overwrite_frame = playback_sample;
1074 overwrite_offset = channels.front().playback_buf->get_read_ptr();
1078 DiskStream::overwrite_existing_buffers ()
1080 Sample* mixdown_buffer;
1084 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1086 overwrite_queued = false;
1088 /* assume all are the same size */
1089 jack_nframes_t size = channels[0].playback_buf->bufsize();
1091 mixdown_buffer = new Sample[size];
1092 gain_buffer = new float[size];
1093 workbuf = new char[size*4];
1095 /* reduce size so that we can fill the buffer correctly. */
1099 jack_nframes_t start;
1101 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1103 start = overwrite_frame;
1104 jack_nframes_t cnt = size;
1106 /* to fill the buffer without resetting the playback sample, we need to
1107 do it one or two chunks (normally two).
1109 |----------------------------------------------------------------------|
1113 |<- second chunk->||<----------------- first chunk ------------------>|
1117 jack_nframes_t to_read = size - overwrite_offset;
1119 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, workbuf,
1120 start, to_read, *chan, n, reversed)) {
1121 error << string_compose(_("DiskStream %1: when refilling, cannot read %2 from playlist at frame %3"),
1122 _id, size, playback_sample) << endmsg;
1126 if (cnt > to_read) {
1130 if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer, workbuf,
1131 start, cnt, *chan, n, reversed)) {
1132 error << string_compose(_("DiskStream %1: when refilling, cannot read %2 from playlist at frame %3"),
1133 _id, size, playback_sample) << endmsg;
1142 pending_overwrite = false;
1143 delete [] gain_buffer;
1144 delete [] mixdown_buffer;
1150 DiskStream::seek (jack_nframes_t frame, bool complete_refill)
1152 LockMonitor lm (state_lock, __LINE__, __FILE__);
1155 ChannelList::iterator chan;
1157 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1158 (*chan).playback_buf->reset ();
1159 (*chan).capture_buf->reset ();
1160 if ((*chan).write_source) {
1161 (*chan).write_source->seek (frame);
1165 playback_sample = frame;
1168 if (complete_refill) {
1169 while ((ret = do_refill (0, 0, 0)) > 0);
1171 ret = do_refill (0, 0, 0);
1178 DiskStream::can_internal_playback_seek (jack_nframes_t distance)
1180 ChannelList::iterator chan;
1182 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1183 if ((*chan).playback_buf->read_space() < distance) {
1191 DiskStream::internal_playback_seek (jack_nframes_t distance)
1193 ChannelList::iterator chan;
1195 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1196 (*chan).playback_buf->increment_read_ptr (distance);
1199 first_recordable_frame += distance;
1200 playback_sample += distance;
1206 DiskStream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, char * workbuf, jack_nframes_t& start, jack_nframes_t cnt,
1207 ChannelInfo& channel_info, int channel, bool reversed)
1209 jack_nframes_t this_read = 0;
1210 bool reloop = false;
1211 jack_nframes_t loop_end = 0;
1212 jack_nframes_t loop_start = 0;
1213 jack_nframes_t loop_length = 0;
1214 jack_nframes_t offset = 0;
1218 /* Make the use of a Location atomic for this read operation.
1220 Note: Locations don't get deleted, so all we care about
1221 when I say "atomic" is that we are always pointing to
1222 the same one and using a start/length values obtained
1226 if ((loc = loop_location) != 0) {
1227 loop_start = loc->start();
1228 loop_end = loc->end();
1229 loop_length = loop_end - loop_start;
1232 /* if we are looping, ensure that the first frame we read is at the correct
1233 position within the loop.
1236 if (loc && start >= loop_end) {
1237 //cerr << "start adjusted from " << start;
1238 start = loop_start + ((start - loop_start) % loop_length);
1239 //cerr << "to " << start << endl;
1241 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1246 /* take any loop into account. we can't read past the end of the loop. */
1248 if (loc && (loop_end - start < cnt)) {
1249 this_read = loop_end - start;
1250 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1257 if (this_read == 0) {
1261 this_read = min(cnt,this_read);
1263 if (_playlist->read (buf+offset, mixdown_buffer, gain_buffer, workbuf, start, this_read, channel) != this_read) {
1264 error << string_compose(_("DiskStream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1269 _read_data_count = _playlist->read_data_count();
1273 /* don't adjust start, since caller has already done that
1276 swap_by_ptr (buf, buf + this_read - 1);
1280 /* if we read to the end of the loop, go back to the beginning */
1290 offset += this_read;
1297 DiskStream::do_refill (Sample* mixdown_buffer, float* gain_buffer, char * workbuf)
1300 jack_nframes_t to_read;
1301 RingBufferNPT<Sample>::rw_vector vector;
1305 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1306 jack_nframes_t total_space;
1307 jack_nframes_t zero_fill;
1309 ChannelList::iterator i;
1312 channels.front().playback_buf->get_write_vector (&vector);
1314 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1318 /* if there are 2+ chunks of disk i/o possible for
1319 this track, let the caller know so that it can arrange
1320 for us to be called again, ASAP.
1323 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1327 /* if we're running close to normal speed and there isn't enough
1328 space to do disk_io_chunk_frames of I/O, then don't bother.
1330 at higher speeds, just do it because the sync between butler
1331 and audio thread may not be good enough.
1334 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1338 /* when slaved, don't try to get too close to the read pointer. this
1339 leaves space for the buffer reversal to have something useful to
1343 if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1347 total_space = min (disk_io_chunk_frames, total_space);
1351 if (file_frame == 0) {
1353 /* at start: nothing to do but fill with silence */
1355 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1357 ChannelInfo& chan (*i);
1358 chan.playback_buf->get_write_vector (&vector);
1359 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1360 if (vector.len[1]) {
1361 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1363 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1368 if (file_frame < total_space) {
1370 /* too close to the start: read what we can,
1371 and then zero fill the rest
1374 zero_fill = total_space - file_frame;
1375 total_space = file_frame;
1380 /* move read position backwards because we are going
1381 to reverse the data.
1384 file_frame -= total_space;
1390 if (file_frame == max_frames) {
1392 /* at end: nothing to do but fill with silence */
1394 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1396 ChannelInfo& chan (*i);
1397 chan.playback_buf->get_write_vector (&vector);
1398 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1399 if (vector.len[1]) {
1400 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1402 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1407 if (file_frame > max_frames - total_space) {
1409 /* to close to the end: read what we can, and zero fill the rest */
1411 zero_fill = total_space - (max_frames - file_frame);
1412 total_space = max_frames - file_frame;
1419 /* Please note: the code to allocate buffers isn't run
1420 during normal butler thread operation. Its there
1421 for other times when we need to call do_refill()
1422 from somewhere other than the butler thread.
1425 if (mixdown_buffer == 0) {
1426 mixdown_buffer = new Sample[disk_io_chunk_frames];
1427 free_mixdown = true;
1429 free_mixdown = false;
1432 if (gain_buffer == 0) {
1433 gain_buffer = new float[disk_io_chunk_frames];
1440 workbuf = new char[disk_io_chunk_frames * 4];
1441 free_workbuf = true;
1443 free_workbuf = false;
1446 jack_nframes_t file_frame_tmp = 0;
1448 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1450 ChannelInfo& chan (*i);
1453 jack_nframes_t len1, len2;
1455 chan.playback_buf->get_write_vector (&vector);
1458 file_frame_tmp = file_frame;
1461 buf1 = vector.buf[1];
1462 len1 = vector.len[1];
1463 buf2 = vector.buf[0];
1464 len2 = vector.len[0];
1466 buf1 = vector.buf[0];
1467 len1 = vector.len[0];
1468 buf2 = vector.buf[1];
1469 len2 = vector.len[1];
1473 to_read = min (ts, len1);
1474 to_read = min (to_read, disk_io_chunk_frames);
1478 if (read (buf1, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1483 chan.playback_buf->increment_write_ptr (to_read);
1487 to_read = min (ts, len2);
1492 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1493 so read some or all of vector.len[1] as well.
1496 if (read (buf2, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1501 chan.playback_buf->increment_write_ptr (to_read);
1510 file_frame = file_frame_tmp;
1514 delete [] mixdown_buffer;
1517 delete [] gain_buffer;
1527 DiskStream::do_flush (char * workbuf, bool force_flush)
1531 RingBufferNPT<Sample>::rw_vector vector;
1532 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1533 jack_nframes_t total;
1535 /* important note: this function will write *AT MOST*
1536 disk_io_chunk_frames of data to disk. it will never
1537 write more than that. if its writes that much and there
1538 is more than that waiting to be written, it will return 1,
1539 otherwise 0 on success or -1 on failure.
1541 if there is less than disk_io_chunk_frames to be written,
1542 no data will be written at all unless `force_flush' is true.
1545 _write_data_count = 0;
1547 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1549 (*chan).capture_buf->get_read_vector (&vector);
1551 total = vector.len[0] + vector.len[1];
1554 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1559 /* if there are 2+ chunks of disk i/o possible for
1560 this track, let the caller know so that it can arrange
1561 for us to be called again, ASAP.
1563 if we are forcing a flush, then if there is* any* extra
1564 work, let the caller know.
1566 if we are no longer recording and there is any extra work,
1567 let the caller know too.
1570 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1574 to_write = min (disk_io_chunk_frames, (jack_nframes_t) vector.len[0]);
1577 // check the transition buffer when recording destructive
1578 // important that we get this after the capture buf
1580 if (destructive()) {
1581 (*chan).capture_transition_buf->get_read_vector(&transvec);
1582 size_t transcount = transvec.len[0] + transvec.len[1];
1583 bool have_start = false;
1586 for (ti=0; ti < transcount; ++ti) {
1587 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1589 if (captrans.type == CaptureStart) {
1590 // by definition, the first data we got above represents the given capture pos
1592 (*chan).write_source->mark_capture_start (captrans.capture_val);
1593 (*chan).curr_capture_cnt = 0;
1597 else if (captrans.type == CaptureEnd) {
1599 // capture end, the capture_val represents total frames in capture
1601 if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1603 // shorten to make the write a perfect fit
1604 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt);
1606 if (nto_write < to_write) {
1607 ret = 1; // should we?
1609 to_write = nto_write;
1611 (*chan).write_source->mark_capture_end ();
1613 // increment past this transition, but go no further
1618 // actually ends just beyond this chunk, so force more work
1626 (*chan).capture_transition_buf->increment_read_ptr(ti);
1630 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write, workbuf) != to_write) {
1631 error << string_compose(_("DiskStream %1: cannot write to disk"), _id) << endmsg;
1635 (*chan).capture_buf->increment_read_ptr (to_write);
1636 (*chan).curr_capture_cnt += to_write;
1638 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1640 /* we wrote all of vector.len[0] but it wasn't an entire
1641 disk_io_chunk_frames of data, so arrange for some part
1642 of vector.len[1] to be flushed to disk as well.
1645 to_write = min ((jack_nframes_t)(disk_io_chunk_frames - to_write), (jack_nframes_t) vector.len[1]);
1647 if ((*chan).write_source->write (vector.buf[1], to_write, workbuf) != to_write) {
1648 error << string_compose(_("DiskStream %1: cannot write to disk"), _id) << endmsg;
1652 _write_data_count += (*chan).write_source->write_data_count();
1654 (*chan).capture_buf->increment_read_ptr (to_write);
1655 (*chan).curr_capture_cnt += to_write;
1664 DiskStream::playlist_changed (Change ignored)
1666 playlist_modified ();
1670 DiskStream::playlist_modified ()
1672 if (!i_am_the_modifier && !overwrite_queued) {
1673 _session.request_overwrite_buffer (this);
1674 overwrite_queued = true;
1679 DiskStream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1681 uint32_t buffer_position;
1682 bool more_work = true;
1684 AudioRegion* region = 0;
1685 jack_nframes_t total_capture;
1686 AudioRegion::SourceList srcs;
1687 AudioRegion::SourceList::iterator src;
1688 ChannelList::iterator chan;
1689 vector<CaptureInfo*>::iterator ci;
1691 list<Source*>* deletion_list;
1692 bool mark_write_completed = false;
1694 finish_capture (true);
1696 /* butler is already stopped, but there may be work to do
1697 to flush remaining data to disk.
1700 while (more_work && !err) {
1701 switch (do_flush ( _session.conversion_buffer(Session::TransportContext), true)) {
1708 error << string_compose(_("DiskStream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1713 /* XXX is there anything we can do if err != 0 ? */
1714 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
1716 if (capture_info.empty()) {
1720 if (abort_capture) {
1722 ChannelList::iterator chan;
1724 deletion_list = new list<Source*>;
1726 for ( chan = channels.begin(); chan != channels.end(); ++chan) {
1728 if ((*chan).write_source) {
1730 (*chan).write_source->mark_for_remove ();
1731 (*chan).write_source->release ();
1733 deletion_list->push_back ((*chan).write_source);
1735 (*chan).write_source = 0;
1738 /* new source set up in "out" below */
1741 if (!deletion_list->empty()) {
1742 DeleteSources (deletion_list);
1744 delete deletion_list;
1750 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1751 total_capture += (*ci)->frames;
1754 /* figure out the name for this take */
1756 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1758 Source* s = (*chan).write_source;
1766 if ((fsrc = dynamic_cast<FileSource *>(s)) != 0) {
1767 fsrc->update_header (capture_info.front()->start, when, twhen);
1770 s->set_captured_for (_name);
1775 /* destructive tracks have a single, never changing region */
1777 if (destructive()) {
1779 /* send a signal that any UI can pick up to do the right thing. there is
1780 a small problem here in that a UI may need the peak data to be ready
1781 for the data that was recorded and this isn't interlocked with that
1782 process. this problem is deferred to the UI.
1785 _playlist->Modified();
1789 /* Register a new region with the Session that
1790 describes the entire source. Do this first
1791 so that any sub-regions will obviously be
1792 children of this one (later!)
1796 region = new AudioRegion (srcs, channels[0].write_source->last_capture_start_frame(), total_capture,
1797 region_name_from_path (channels[0].write_source->name()),
1798 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
1800 region->special_set_position (capture_info.front()->start);
1804 catch (failed_constructor& err) {
1805 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1809 _last_capture_regions.push_back (region);
1811 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1813 _session.add_undo (_playlist->get_memento());
1814 _playlist->freeze ();
1816 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1819 _session.region_name (region_name, _name, false);
1821 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1824 region = new AudioRegion (srcs, buffer_position, (*ci)->frames, region_name);
1827 catch (failed_constructor& err) {
1828 error << _("DiskStream: could not create region for captured audio!") << endmsg;
1829 continue; /* XXX is this OK? */
1832 _last_capture_regions.push_back (region);
1834 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1836 i_am_the_modifier++;
1837 _playlist->add_region (*region, (*ci)->start);
1838 i_am_the_modifier--;
1840 buffer_position += (*ci)->frames;
1844 _session.add_redo_no_execute (_playlist->get_memento());
1847 mark_write_completed = true;
1849 reset_write_sources (mark_write_completed);
1852 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1856 capture_info.clear ();
1857 capture_start_frame = 0;
1861 DiskStream::finish_capture (bool rec_monitors_input)
1863 was_recording = false;
1865 if (capture_captured == 0) {
1869 if (recordable() && destructive()) {
1870 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1872 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1873 (*chan).capture_transition_buf->get_write_vector(&transvec);
1876 if (transvec.len[0] > 0) {
1877 transvec.buf[0]->type = CaptureEnd;
1878 transvec.buf[0]->capture_val = capture_captured;
1879 (*chan).capture_transition_buf->increment_write_ptr(1);
1883 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1889 CaptureInfo* ci = new CaptureInfo;
1891 ci->start = capture_start_frame;
1892 ci->frames = capture_captured;
1894 /* XXX theoretical race condition here. Need atomic exchange ?
1895 However, the circumstances when this is called right
1896 now (either on record-disable or transport_stopped)
1897 mean that no actual race exists. I think ...
1898 We now have a capture_info_lock, but it is only to be used
1899 to synchronize in the transport_stop and the capture info
1900 accessors, so that invalidation will not occur (both non-realtime).
1903 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1905 capture_info.push_back (ci);
1906 capture_captured = 0;
1910 DiskStream::set_record_enabled (bool yn, void* src)
1912 bool rolling = _session.transport_speed() != 0.0f;
1914 if (!recordable() || !_session.record_enabling_legal()) {
1918 /* if we're turning on rec-enable, there needs to be an
1922 if (yn && channels[0].source == 0) {
1924 /* pick up connections not initiated *from* the IO object
1925 we're associated with.
1928 get_input_sources ();
1930 if (channels[0].source == 0) {
1933 CannotRecordNoInput (this); /* emit signal */
1939 /* yes, i know that this not proof against race conditions, but its
1940 good enough. i think.
1943 if (record_enabled() != yn) {
1945 atomic_set (&_record_enabled, 1);
1946 capturing_sources.clear ();
1947 if (Config->get_use_hardware_monitoring()) {
1948 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1949 if ((*chan).source) {
1950 (*chan).source->request_monitor_input (!(_session.get_auto_input() && rolling));
1952 capturing_sources.push_back ((*chan).write_source);
1955 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1956 capturing_sources.push_back ((*chan).write_source);
1961 atomic_set (&_record_enabled, 0);
1962 if (Config->get_use_hardware_monitoring()) {
1963 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1964 if ((*chan).source) {
1965 (*chan).source->request_monitor_input (false);
1969 capturing_sources.clear ();
1972 record_enable_changed (src); /* EMIT SIGNAL */
1977 DiskStream::get_state ()
1979 XMLNode* node = new XMLNode ("DiskStream");
1981 LocaleGuard lg (X_("POSIX"));
1983 snprintf (buf, sizeof(buf), "0x%x", _flags);
1984 node->add_property ("flags", buf);
1986 snprintf (buf, sizeof(buf), "%zd", channels.size());
1987 node->add_property ("channels", buf);
1989 node->add_property ("playlist", _playlist->name());
1991 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1992 node->add_property ("speed", buf);
1994 node->add_property("name", _name);
1995 snprintf (buf, sizeof(buf), "%" PRIu64, id());
1996 node->add_property("id", buf);
1998 if (!capturing_sources.empty() && _session.get_record_enabled()) {
2000 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
2001 XMLNode* cs_grandchild;
2003 for (vector<FileSource*>::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
2004 cs_grandchild = new XMLNode (X_("file"));
2005 cs_grandchild->add_property (X_("path"), (*i)->path());
2006 cs_child->add_child_nocopy (*cs_grandchild);
2009 /* store the location where capture will start */
2013 if (_session.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
2014 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
2016 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
2019 cs_child->add_property (X_("at"), buf);
2020 node->add_child_nocopy (*cs_child);
2024 node->add_child_copy (*_extra_xml);
2031 DiskStream::set_state (const XMLNode& node)
2033 const XMLProperty* prop;
2034 XMLNodeList nlist = node.children();
2035 XMLNodeIterator niter;
2036 uint32_t nchans = 1;
2037 XMLNode* capture_pending_node = 0;
2038 LocaleGuard lg (X_("POSIX"));
2040 in_set_state = true;
2042 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2043 if ((*niter)->name() == IO::state_node_name) {
2044 deprecated_io_node = new XMLNode (**niter);
2047 if ((*niter)->name() == X_("CapturingSources")) {
2048 capture_pending_node = *niter;
2052 /* prevent write sources from being created */
2054 in_set_state = true;
2056 if ((prop = node.property ("name")) != 0) {
2057 _name = prop->value();
2060 if (deprecated_io_node) {
2061 if ((prop = deprecated_io_node->property ("id")) != 0) {
2062 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2065 if ((prop = node.property ("id")) != 0) {
2066 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2070 if ((prop = node.property ("flags")) != 0) {
2071 _flags = strtol (prop->value().c_str(), 0, 0);
2074 if ((prop = node.property ("channels")) != 0) {
2075 nchans = atoi (prop->value().c_str());
2078 // create necessary extra channels
2079 // we are always constructed with one
2080 // and we always need one
2082 if (nchans > _n_channels) {
2084 // we need to add new channel infos
2085 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2087 int diff = nchans - channels.size();
2089 for (int i=0; i < diff; ++i) {
2093 } else if (nchans < _n_channels) {
2095 // we need to get rid of channels
2096 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2098 int diff = channels.size() - nchans;
2100 for (int i = 0; i < diff; ++i) {
2105 if ((prop = node.property ("playlist")) == 0) {
2110 bool had_playlist = (_playlist != 0);
2112 if (find_and_use_playlist (prop->value())) {
2116 if (!had_playlist) {
2117 _playlist->set_orig_diskstream_id (_id);
2120 if (!destructive() && capture_pending_node) {
2121 /* destructive streams have one and only one source per channel,
2122 and so they never end up in pending capture in any useful
2125 use_pending_capture_data (*capture_pending_node);
2130 if ((prop = node.property ("speed")) != 0) {
2131 double sp = atof (prop->value().c_str());
2133 if (realtime_set_speed (sp, false)) {
2134 non_realtime_set_speed ();
2138 _n_channels = channels.size();
2140 in_set_state = false;
2142 /* make sure this is clear before we do anything else */
2144 capturing_sources.clear ();
2146 /* write sources are handled elsewhere;
2147 for destructive tracks: in {setup,use}_destructive_playlist()
2148 for non-destructive: when we handle the input set up of the IO that owns this DS
2151 in_set_state = false;
2157 DiskStream::use_new_write_source (uint32_t n)
2159 if (!recordable()) {
2163 if (n >= channels.size()) {
2164 error << string_compose (_("DiskStream: channel %1 out of range"), n) << endmsg;
2168 ChannelInfo &chan = channels[n];
2170 if (chan.write_source) {
2172 if (FileSource::is_empty (chan.write_source->path())) {
2173 chan.write_source->mark_for_remove ();
2174 chan.write_source->release();
2175 delete chan.write_source;
2177 chan.write_source->release();
2178 chan.write_source = 0;
2183 if ((chan.write_source = _session.create_file_source (*this, n, destructive())) == 0) {
2184 throw failed_constructor();
2188 catch (failed_constructor &err) {
2189 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2190 chan.write_source = 0;
2194 chan.write_source->use ();
2196 /* do not remove destructive files even if they are empty */
2198 chan.write_source->set_allow_remove_if_empty (!destructive());
2204 DiskStream::reset_write_sources (bool mark_write_complete, bool force)
2206 ChannelList::iterator chan;
2209 if (!recordable()) {
2213 if (!force && destructive()) {
2215 /* make sure we always have enough sources for the current channel count */
2217 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2218 if ((*chan).write_source == 0) {
2223 if (chan == channels.end()) {
2227 /* some channels do not have a write source */
2230 capturing_sources.clear ();
2232 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2233 if ((*chan).write_source && mark_write_complete) {
2234 (*chan).write_source->mark_streaming_write_completed ();
2236 use_new_write_source (n);
2237 if (record_enabled()) {
2238 capturing_sources.push_back ((*chan).write_source);
2244 DiskStream::rename_write_sources ()
2246 ChannelList::iterator chan;
2249 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2250 if ((*chan).write_source != 0) {
2251 (*chan).write_source->set_name (_name, destructive());
2252 /* XXX what to do if one of them fails ? */
2260 DiskStream::set_block_size (jack_nframes_t nframes)
2262 if (_session.get_block_size() > speed_buffer_size) {
2263 speed_buffer_size = _session.get_block_size();
2265 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2266 if ((*chan).speed_buffer) delete [] (*chan).speed_buffer;
2267 (*chan).speed_buffer = new Sample[speed_buffer_size];
2270 allocate_temporary_buffers ();
2274 DiskStream::allocate_temporary_buffers ()
2276 /* make sure the wrap buffer is at least large enough to deal
2277 with the speeds up to 1.2, to allow for micro-variation
2278 when slaving to MTC, SMPTE etc.
2281 double sp = max (fabsf (_actual_speed), 1.2f);
2282 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * sp) + 1;
2284 if (required_wrap_size > wrap_buffer_size) {
2286 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2287 if ((*chan).playback_wrap_buffer) delete [] (*chan).playback_wrap_buffer;
2288 (*chan).playback_wrap_buffer = new Sample[required_wrap_size];
2289 if ((*chan).capture_wrap_buffer) delete [] (*chan).capture_wrap_buffer;
2290 (*chan).capture_wrap_buffer = new Sample[required_wrap_size];
2293 wrap_buffer_size = required_wrap_size;
2298 DiskStream::monitor_input (bool yn)
2300 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2302 if ((*chan).source) {
2303 (*chan).source->request_monitor_input (yn);
2309 DiskStream::set_capture_offset ()
2312 /* can't capture, so forget it */
2316 _capture_offset = _io->input_latency();
2320 DiskStream::set_persistent_align_style (AlignStyle a)
2322 _persistent_alignment_style = a;
2326 DiskStream::set_align_style_from_io ()
2328 bool have_physical = false;
2334 get_input_sources ();
2336 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2337 if ((*chan).source && (*chan).source->flags() & JackPortIsPhysical) {
2338 have_physical = true;
2343 if (have_physical) {
2344 set_align_style (ExistingMaterial);
2346 set_align_style (CaptureTime);
2351 DiskStream::set_align_style (AlignStyle a)
2353 if (record_enabled() && _session.actively_recording()) {
2358 if (a != _alignment_style) {
2359 _alignment_style = a;
2360 AlignmentStyleChanged ();
2365 DiskStream::add_channel ()
2367 /* XXX need to take lock??? */
2371 init_channel (chan);
2373 chan.speed_buffer = new Sample[speed_buffer_size];
2374 chan.playback_wrap_buffer = new Sample[wrap_buffer_size];
2375 chan.capture_wrap_buffer = new Sample[wrap_buffer_size];
2377 channels.push_back (chan);
2379 _n_channels = channels.size();
2385 DiskStream::remove_channel ()
2387 if (channels.size() > 1) {
2388 /* XXX need to take lock??? */
2389 ChannelInfo & chan = channels.back();
2390 destroy_channel (chan);
2391 channels.pop_back();
2393 _n_channels = channels.size();
2401 DiskStream::playback_buffer_load () const
2403 return (float) ((double) channels.front().playback_buf->read_space()/
2404 (double) channels.front().playback_buf->bufsize());
2408 DiskStream::capture_buffer_load () const
2410 return (float) ((double) channels.front().capture_buf->write_space()/
2411 (double) channels.front().capture_buf->bufsize());
2415 DiskStream::set_loop (Location *location)
2418 if (location->start() >= location->end()) {
2419 error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
2424 loop_location = location;
2426 LoopSet (location); /* EMIT SIGNAL */
2431 DiskStream::get_capture_start_frame (uint32_t n)
2433 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
2435 if (capture_info.size() > n) {
2436 return capture_info[n]->start;
2439 return capture_start_frame;
2444 DiskStream::get_captured_frames (uint32_t n)
2446 LockMonitor lm (capture_info_lock, __LINE__, __FILE__);
2448 if (capture_info.size() > n) {
2449 return capture_info[n]->frames;
2452 return capture_captured;
2457 DiskStream::punch_in ()
2462 DiskStream::punch_out ()
2467 DiskStream::use_pending_capture_data (XMLNode& node)
2469 const XMLProperty* prop;
2470 XMLNodeList nlist = node.children();
2471 XMLNodeIterator niter;
2473 FileSource* first_fs = 0;
2474 AudioRegion::SourceList pending_sources;
2475 jack_nframes_t position;
2477 if ((prop = node.property (X_("at"))) == 0) {
2481 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2485 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2486 if ((*niter)->name() == X_("file")) {
2488 if ((prop = (*niter)->property (X_("path"))) == 0) {
2493 fs = new FileSource (prop->value(), _session.frame_rate(), true);
2496 catch (failed_constructor& err) {
2497 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2498 _name, prop->value())
2503 pending_sources.push_back (fs);
2505 if (first_fs == 0) {
2509 fs->set_captured_for (_name);
2513 if (pending_sources.size() == 0) {
2514 /* nothing can be done */
2518 if (pending_sources.size() != _n_channels) {
2519 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2524 AudioRegion* region;
2527 region = new AudioRegion (pending_sources, 0, first_fs->length(),
2528 region_name_from_path (first_fs->name()),
2529 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
2531 region->special_set_position (0);
2534 catch (failed_constructor& err) {
2535 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2543 region = new AudioRegion (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name()));
2546 catch (failed_constructor& err) {
2547 error << string_compose (_("%1: cannot create region from pending capture sources"),
2554 _playlist->add_region (*region, position);
2560 DiskStream::set_roll_delay (jack_nframes_t nframes)
2562 _roll_delay = nframes;
2566 DiskStream::set_destructive (bool yn)
2568 if (yn != destructive()) {
2569 reset_write_sources (true, true);
2571 _flags |= Destructive;
2573 _flags &= ~Destructive;