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.
18 $Id: diskstream.cc 567 2006-06-07 14:54:12Z trutkin $
34 #include <pbd/error.h>
35 #include <pbd/basename.h>
36 #include <glibmm/thread.h>
37 #include <pbd/xml++.h>
39 #include <ardour/ardour.h>
40 #include <ardour/audioengine.h>
41 #include <ardour/audio_diskstream.h>
42 #include <ardour/utils.h>
43 #include <ardour/configuration.h>
44 #include <ardour/audiofilesource.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;
58 //sigc::signal<void,AudioDiskstream*> AudioDiskstream::AudioDiskstreamCreated;
59 sigc::signal<void,list<AudioFileSource*>*> AudioDiskstream::DeleteSources;
60 //sigc::signal<void> AudioDiskstream::DiskOverrun;
61 //sigc::signal<void> AudioDiskstream::DiskUnderrun;
63 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
64 : Diskstream(sess, name, flag)
67 /* prevent any write sources from being created */
76 DiskstreamCreated (this); /* EMIT SIGNAL */
79 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
80 : Diskstream(sess, node)
86 if (set_state (node)) {
88 throw failed_constructor();
94 use_destructive_playlist ();
97 DiskstreamCreated (this); /* EMIT SIGNAL */
101 AudioDiskstream::init_channel (ChannelInfo &chan)
103 chan.playback_wrap_buffer = 0;
104 chan.capture_wrap_buffer = 0;
105 chan.speed_buffer = 0;
106 chan.peak_power = 0.0f;
107 chan.write_source = 0;
109 chan.current_capture_buffer = 0;
110 chan.current_playback_buffer = 0;
111 chan.curr_capture_cnt = 0;
113 chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
114 chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
115 chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
118 /* touch the ringbuffer buffers, which will cause
119 them to be mapped into locked physical RAM if
120 we're running with mlockall(). this doesn't do
123 memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
124 memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
125 memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
130 AudioDiskstream::init (Diskstream::Flag f)
134 /* there are no channels at this point, so these
135 two calls just get speed_buffer_size and wrap_buffer
136 size setup without duplicating their code.
139 set_block_size (_session.get_block_size());
140 allocate_temporary_buffers ();
142 pending_overwrite = false;
144 overwrite_queued = false;
145 input_change_pending = NoChange;
152 AudioDiskstream::destroy_channel (ChannelInfo &chan)
154 if (chan.write_source) {
155 chan.write_source->release ();
156 chan.write_source = 0;
159 if (chan.speed_buffer) {
160 delete [] chan.speed_buffer;
163 if (chan.playback_wrap_buffer) {
164 delete [] chan.playback_wrap_buffer;
166 if (chan.capture_wrap_buffer) {
167 delete [] chan.capture_wrap_buffer;
170 delete chan.playback_buf;
171 delete chan.capture_buf;
172 delete chan.capture_transition_buf;
174 chan.playback_buf = 0;
175 chan.capture_buf = 0;
178 AudioDiskstream::~AudioDiskstream ()
180 Glib::Mutex::Lock lm (state_lock);
185 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
186 destroy_channel((*chan));
193 AudioDiskstream::handle_input_change (IOChange change, void *src)
195 Glib::Mutex::Lock lm (state_lock);
197 if (!(input_change_pending & change)) {
198 input_change_pending = IOChange (input_change_pending|change);
199 _session.request_input_change_handling ();
204 AudioDiskstream::non_realtime_input_change ()
207 Glib::Mutex::Lock lm (state_lock);
209 if (input_change_pending == NoChange) {
213 if (input_change_pending & ConfigurationChanged) {
215 if (_io->n_inputs() > _n_channels) {
217 // we need to add new channel infos
219 int diff = _io->n_inputs() - channels.size();
221 for (int i = 0; i < diff; ++i) {
225 } else if (_io->n_inputs() < _n_channels) {
227 // we need to get rid of channels
229 int diff = channels.size() - _io->n_inputs();
231 for (int i = 0; i < diff; ++i) {
237 get_input_sources ();
238 set_capture_offset ();
240 if (first_input_change) {
241 set_align_style (_persistent_alignment_style);
242 first_input_change = false;
244 set_align_style_from_io ();
247 input_change_pending = NoChange;
250 /* reset capture files */
252 reset_write_sources (false);
254 /* now refill channel buffers */
256 if (speed() != 1.0f || speed() != -1.0f) {
257 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()));
260 seek (_session.transport_frame());
265 AudioDiskstream::get_input_sources ()
267 uint32_t ni = _io->n_inputs();
269 for (uint32_t n = 0; n < ni; ++n) {
271 const char **connections = _io->input(n)->get_connections ();
272 ChannelInfo& chan = channels[n];
274 if (connections == 0 || connections[0] == 0) {
277 // _source->disable_metering ();
283 chan.source = _session.engine().get_port_by_name (connections[0]);
293 AudioDiskstream::find_and_use_playlist (const string& name)
296 AudioPlaylist* playlist;
298 if ((pl = _session.get_playlist (name)) == 0) {
299 error << string_compose(_("AudioDiskstream: Session doesn't know about a Playlist called \"%1\""), name) << endmsg;
303 if ((playlist = dynamic_cast<AudioPlaylist*> (pl)) == 0) {
304 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
308 return use_playlist (playlist);
312 AudioDiskstream::use_playlist (Playlist* playlist)
314 assert(dynamic_cast<AudioPlaylist*>(playlist));
317 Glib::Mutex::Lock lm (state_lock);
319 if (playlist == _playlist) {
323 plstate_connection.disconnect();
324 plmod_connection.disconnect ();
325 plgone_connection.disconnect ();
331 _playlist = dynamic_cast<AudioPlaylist*>(playlist);
334 if (!in_set_state && recordable()) {
335 reset_write_sources (false);
338 plstate_connection = _playlist->StateChanged.connect (mem_fun (*this, &AudioDiskstream::playlist_changed));
339 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &AudioDiskstream::playlist_modified));
340 plgone_connection = _playlist->GoingAway.connect (mem_fun (*this, &AudioDiskstream::playlist_deleted));
343 if (!overwrite_queued) {
344 _session.request_overwrite_buffer (this);
345 overwrite_queued = true;
348 PlaylistChanged (); /* EMIT SIGNAL */
349 _session.set_dirty ();
355 AudioDiskstream::use_new_playlist ()
358 AudioPlaylist* playlist;
360 if (!in_set_state && destructive()) {
365 newname = Playlist::bump_name (_playlist->name(), _session);
367 newname = Playlist::bump_name (_name, _session);
370 if ((playlist = new AudioPlaylist (_session, newname, hidden())) != 0) {
371 playlist->set_orig_diskstream_id (id());
372 return use_playlist (playlist);
379 AudioDiskstream::use_copy_playlist ()
385 if (_playlist == 0) {
386 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
391 AudioPlaylist* playlist;
393 newname = Playlist::bump_name (_playlist->name(), _session);
395 if ((playlist = new AudioPlaylist (*_playlist, newname)) != 0) {
396 playlist->set_orig_diskstream_id (id());
397 return use_playlist (playlist);
405 AudioDiskstream::playlist_deleted (Playlist* pl)
407 /* this catches an ordering issue with session destruction. playlists
408 are destroyed before diskstreams. we have to invalidate any handles
409 we have to the playlist.
417 AudioDiskstream::setup_destructive_playlist ()
419 AudioRegion::SourceList srcs;
421 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
422 srcs.push_back ((*chan).write_source);
425 /* a single full-sized region */
427 AudioRegion* region = new AudioRegion (srcs, 0, max_frames, _name);
428 _playlist->add_region (*region, 0);
432 AudioDiskstream::use_destructive_playlist ()
434 /* use the sources associated with the single full-extent region */
436 Playlist::RegionList* rl = _playlist->regions_at (0);
439 reset_write_sources (false, true);
443 AudioRegion* region = dynamic_cast<AudioRegion*> (rl->front());
446 throw failed_constructor();
452 ChannelList::iterator chan;
454 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
455 (*chan).write_source = dynamic_cast<AudioFileSource*>(®ion->source (n));
456 (*chan).write_source->set_allow_remove_if_empty (false);
459 /* the source list will never be reset for a destructive track */
463 AudioDiskstream::set_io (IO& io)
466 set_align_style_from_io ();
470 AudioDiskstream::non_realtime_set_speed ()
472 if (_buffer_reallocation_required)
474 Glib::Mutex::Lock lm (state_lock);
475 allocate_temporary_buffers ();
477 _buffer_reallocation_required = false;
480 if (_seek_required) {
481 if (speed() != 1.0f || speed() != -1.0f) {
482 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()), true);
485 seek (_session.transport_frame(), true);
488 _seek_required = false;
493 AudioDiskstream::check_record_status (jack_nframes_t transport_frame, jack_nframes_t nframes, bool can_record)
495 int possibly_recording;
498 const int transport_rolling = 0x4;
499 const int track_rec_enabled = 0x2;
500 const int global_rec_enabled = 0x1;
502 /* merge together the 3 factors that affect record status, and compute
506 rolling = _session.transport_speed() != 0.0f;
507 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
508 change = possibly_recording ^ last_possibly_recording;
510 if (possibly_recording == last_possibly_recording) {
516 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
518 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
519 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
521 /* starting to record: compute first+last frames */
523 first_recordable_frame = transport_frame + _capture_offset;
524 last_recordable_frame = max_frames;
525 capture_start_frame = transport_frame;
527 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
529 /* was stopped, now rolling (and recording) */
531 if (_alignment_style == ExistingMaterial) {
532 first_recordable_frame += _session.worst_output_latency();
534 first_recordable_frame += _roll_delay;
539 /* was rolling, but record state changed */
541 if (_alignment_style == ExistingMaterial) {
544 if (!_session.get_punch_in()) {
546 /* manual punch in happens at the correct transport frame
547 because the user hit a button. but to get alignment correct
548 we have to back up the position of the new region to the
549 appropriate spot given the roll delay.
552 capture_start_frame -= _roll_delay;
554 /* XXX paul notes (august 2005): i don't know why
558 first_recordable_frame += _capture_offset;
562 /* autopunch toggles recording at the precise
563 transport frame, and then the DS waits
564 to start recording for a time that depends
565 on the output latency.
568 first_recordable_frame += _session.worst_output_latency();
573 if (_session.get_punch_in()) {
574 first_recordable_frame += _roll_delay;
576 capture_start_frame -= _roll_delay;
582 if (_flags & Recordable) {
583 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
585 RingBufferNPT<CaptureTransition>::rw_vector transvec;
586 (*chan).capture_transition_buf->get_write_vector(&transvec);
588 if (transvec.len[0] > 0) {
589 transvec.buf[0]->type = CaptureStart;
590 transvec.buf[0]->capture_val = capture_start_frame;
591 (*chan).capture_transition_buf->increment_write_ptr(1);
595 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
601 } else if (!record_enabled() || !can_record) {
605 last_recordable_frame = transport_frame + _capture_offset;
607 if (_alignment_style == ExistingMaterial) {
608 last_recordable_frame += _session.worst_output_latency();
610 last_recordable_frame += _roll_delay;
614 last_possibly_recording = possibly_recording;
618 AudioDiskstream::process (jack_nframes_t transport_frame, jack_nframes_t nframes, jack_nframes_t offset, bool can_record, bool rec_monitors_input)
621 ChannelList::iterator c;
623 jack_nframes_t rec_offset = 0;
624 jack_nframes_t rec_nframes = 0;
625 bool nominally_recording;
626 bool re = record_enabled ();
627 bool collect_playback = false;
629 /* if we've already processed the frames corresponding to this call,
630 just return. this allows multiple routes that are taking input
631 from this diskstream to call our ::process() method, but have
632 this stuff only happen once. more commonly, it allows both
633 the AudioTrack that is using this AudioDiskstream *and* the Session
634 to call process() without problems.
641 check_record_status (transport_frame, nframes, can_record);
643 nominally_recording = (can_record && re);
650 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
651 must always be called as a pair. The only exception is if this function
652 returns a non-zero value, in which case, ::commit should not be called.
655 // If we can't take the state lock return.
656 if (!state_lock.trylock()) {
660 adjust_capture_position = 0;
662 for (c = channels.begin(); c != channels.end(); ++c) {
663 (*c).current_capture_buffer = 0;
664 (*c).current_playback_buffer = 0;
667 if (nominally_recording || (_session.get_record_enabled() && _session.get_punch_in())) {
670 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
677 case OverlapInternal:
678 /* ---------- recrange
681 rec_nframes = nframes;
686 /* |--------| recrange
689 rec_nframes = transport_frame + nframes - first_recordable_frame;
691 rec_offset = first_recordable_frame - transport_frame;
696 /* |--------| recrange
699 rec_nframes = last_recordable_frame - transport_frame;
703 case OverlapExternal:
704 /* |--------| recrange
705 -------------- transrange
707 rec_nframes = last_recordable_frame - last_recordable_frame;
708 rec_offset = first_recordable_frame - transport_frame;
712 if (rec_nframes && !was_recording) {
713 capture_captured = 0;
714 was_recording = true;
719 if (can_record && !_last_capture_regions.empty()) {
720 _last_capture_regions.clear ();
723 if (nominally_recording || rec_nframes) {
725 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
727 ChannelInfo& chan (*c);
729 chan.capture_buf->get_write_vector (&chan.capture_vector);
731 if (rec_nframes <= chan.capture_vector.len[0]) {
733 chan.current_capture_buffer = chan.capture_vector.buf[0];
735 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
739 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
743 jack_nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
745 if (rec_nframes > total) {
750 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
751 jack_nframes_t first = chan.capture_vector.len[0];
753 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
754 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
755 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
756 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
758 chan.current_capture_buffer = chan.capture_wrap_buffer;
765 finish_capture (rec_monitors_input);
772 /* data will be written to disk */
774 if (rec_nframes == nframes && rec_offset == 0) {
776 for (c = channels.begin(); c != channels.end(); ++c) {
777 (*c).current_playback_buffer = (*c).current_capture_buffer;
780 playback_distance = nframes;
785 /* we can't use the capture buffer as the playback buffer, because
786 we recorded only a part of the current process' cycle data
790 collect_playback = true;
793 adjust_capture_position = rec_nframes;
795 } else if (nominally_recording) {
797 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
799 for (c = channels.begin(); c != channels.end(); ++c) {
800 (*c).current_playback_buffer = (*c).current_capture_buffer;
803 playback_distance = nframes;
807 collect_playback = true;
810 if (collect_playback) {
812 /* we're doing playback */
814 jack_nframes_t necessary_samples;
816 /* no varispeed playback if we're recording, because the output .... TBD */
818 if (rec_nframes == 0 && _actual_speed != 1.0f) {
819 necessary_samples = (jack_nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
821 necessary_samples = nframes;
824 for (c = channels.begin(); c != channels.end(); ++c) {
825 (*c).playback_buf->get_read_vector (&(*c).playback_vector);
830 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
832 ChannelInfo& chan (*c);
834 if (necessary_samples <= chan.playback_vector.len[0]) {
836 chan.current_playback_buffer = chan.playback_vector.buf[0];
839 jack_nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
841 if (necessary_samples > total) {
847 memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
848 chan.playback_vector.len[0] * sizeof (Sample));
849 memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1],
850 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
852 chan.current_playback_buffer = chan.playback_wrap_buffer;
857 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
859 uint64_t phase = last_phase;
860 jack_nframes_t i = 0;
862 // Linearly interpolate into the alt buffer
863 // using 40.24 fixp maths (swh)
865 for (c = channels.begin(); c != channels.end(); ++c) {
868 ChannelInfo& chan (*c);
873 for (jack_nframes_t outsample = 0; outsample < nframes; ++outsample) {
875 fr = (phase & 0xFFFFFF) / 16777216.0f;
876 chan.speed_buffer[outsample] =
877 chan.current_playback_buffer[i] * (1.0f - fr) +
878 chan.current_playback_buffer[i+1] * fr;
882 chan.current_playback_buffer = chan.speed_buffer;
885 playback_distance = i + 1;
886 last_phase = (phase & 0xFFFFFF);
889 playback_distance = nframes;
901 /* we're exiting with failure, so ::commit will not
902 be called. unlock the state lock.
912 AudioDiskstream::commit (jack_nframes_t nframes)
914 bool need_butler = false;
916 if (_actual_speed < 0.0) {
917 playback_sample -= playback_distance;
919 playback_sample += playback_distance;
922 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
924 (*chan).playback_buf->increment_read_ptr (playback_distance);
926 if (adjust_capture_position) {
927 (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
931 if (adjust_capture_position != 0) {
932 capture_captured += adjust_capture_position;
933 adjust_capture_position = 0;
937 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
939 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
940 || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
951 AudioDiskstream::set_pending_overwrite (bool yn)
953 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
955 pending_overwrite = yn;
957 overwrite_frame = playback_sample;
958 overwrite_offset = channels.front().playback_buf->get_read_ptr();
962 AudioDiskstream::overwrite_existing_buffers ()
964 Sample* mixdown_buffer;
968 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
970 overwrite_queued = false;
972 /* assume all are the same size */
973 jack_nframes_t size = channels[0].playback_buf->bufsize();
975 mixdown_buffer = new Sample[size];
976 gain_buffer = new float[size];
977 workbuf = new char[size*4];
979 /* reduce size so that we can fill the buffer correctly. */
983 jack_nframes_t start;
985 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
987 start = overwrite_frame;
988 jack_nframes_t cnt = size;
990 /* to fill the buffer without resetting the playback sample, we need to
991 do it one or two chunks (normally two).
993 |----------------------------------------------------------------------|
997 |<- second chunk->||<----------------- first chunk ------------------>|
1001 jack_nframes_t to_read = size - overwrite_offset;
1003 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, workbuf,
1004 start, to_read, *chan, n, reversed)) {
1005 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1006 _id, size, playback_sample) << endmsg;
1010 if (cnt > to_read) {
1014 if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer, workbuf,
1015 start, cnt, *chan, n, reversed)) {
1016 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1017 _id, size, playback_sample) << endmsg;
1026 pending_overwrite = false;
1027 delete [] gain_buffer;
1028 delete [] mixdown_buffer;
1034 AudioDiskstream::seek (jack_nframes_t frame, bool complete_refill)
1036 Glib::Mutex::Lock lm (state_lock);
1039 ChannelList::iterator chan;
1041 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1042 (*chan).playback_buf->reset ();
1043 (*chan).capture_buf->reset ();
1046 playback_sample = frame;
1049 if (complete_refill) {
1050 while ((ret = non_realtime_do_refill ()) > 0);
1052 ret = non_realtime_do_refill ();
1059 AudioDiskstream::can_internal_playback_seek (jack_nframes_t distance)
1061 ChannelList::iterator chan;
1063 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1064 if ((*chan).playback_buf->read_space() < distance) {
1072 AudioDiskstream::internal_playback_seek (jack_nframes_t distance)
1074 ChannelList::iterator chan;
1076 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1077 (*chan).playback_buf->increment_read_ptr (distance);
1080 first_recordable_frame += distance;
1081 playback_sample += distance;
1087 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, char * workbuf, jack_nframes_t& start, jack_nframes_t cnt,
1088 ChannelInfo& channel_info, int channel, bool reversed)
1090 jack_nframes_t this_read = 0;
1091 bool reloop = false;
1092 jack_nframes_t loop_end = 0;
1093 jack_nframes_t loop_start = 0;
1094 jack_nframes_t loop_length = 0;
1095 jack_nframes_t offset = 0;
1099 /* Make the use of a Location atomic for this read operation.
1101 Note: Locations don't get deleted, so all we care about
1102 when I say "atomic" is that we are always pointing to
1103 the same one and using a start/length values obtained
1107 if ((loc = loop_location) != 0) {
1108 loop_start = loc->start();
1109 loop_end = loc->end();
1110 loop_length = loop_end - loop_start;
1113 /* if we are looping, ensure that the first frame we read is at the correct
1114 position within the loop.
1117 if (loc && start >= loop_end) {
1118 //cerr << "start adjusted from " << start;
1119 start = loop_start + ((start - loop_start) % loop_length);
1120 //cerr << "to " << start << endl;
1122 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1127 /* take any loop into account. we can't read past the end of the loop. */
1129 if (loc && (loop_end - start < cnt)) {
1130 this_read = loop_end - start;
1131 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1138 if (this_read == 0) {
1142 this_read = min(cnt,this_read);
1144 if (_playlist->read (buf+offset, mixdown_buffer, gain_buffer, workbuf, start, this_read, channel) != this_read) {
1145 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1150 _read_data_count = _playlist->read_data_count();
1154 /* don't adjust start, since caller has already done that
1157 swap_by_ptr (buf, buf + this_read - 1);
1161 /* if we read to the end of the loop, go back to the beginning */
1171 offset += this_read;
1178 AudioDiskstream::do_refill (Sample* mixdown_buffer, float* gain_buffer, char * workbuf)
1181 jack_nframes_t to_read;
1182 RingBufferNPT<Sample>::rw_vector vector;
1186 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1187 jack_nframes_t total_space;
1188 jack_nframes_t zero_fill;
1190 ChannelList::iterator i;
1193 channels.front().playback_buf->get_write_vector (&vector);
1195 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1199 /* if there are 2+ chunks of disk i/o possible for
1200 this track, let the caller know so that it can arrange
1201 for us to be called again, ASAP.
1204 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1208 /* if we're running close to normal speed and there isn't enough
1209 space to do disk_io_chunk_frames of I/O, then don't bother.
1211 at higher speeds, just do it because the sync between butler
1212 and audio thread may not be good enough.
1215 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1219 /* when slaved, don't try to get too close to the read pointer. this
1220 leaves space for the buffer reversal to have something useful to
1224 if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1228 total_space = min (disk_io_chunk_frames, total_space);
1232 if (file_frame == 0) {
1234 /* at start: nothing to do but fill with silence */
1236 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1238 ChannelInfo& chan (*i);
1239 chan.playback_buf->get_write_vector (&vector);
1240 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1241 if (vector.len[1]) {
1242 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1244 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1249 if (file_frame < total_space) {
1251 /* too close to the start: read what we can,
1252 and then zero fill the rest
1255 zero_fill = total_space - file_frame;
1256 total_space = file_frame;
1261 /* move read position backwards because we are going
1262 to reverse the data.
1265 file_frame -= total_space;
1271 if (file_frame == max_frames) {
1273 /* at end: nothing to do but fill with silence */
1275 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1277 ChannelInfo& chan (*i);
1278 chan.playback_buf->get_write_vector (&vector);
1279 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1280 if (vector.len[1]) {
1281 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1283 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1288 if (file_frame > max_frames - total_space) {
1290 /* to close to the end: read what we can, and zero fill the rest */
1292 zero_fill = total_space - (max_frames - file_frame);
1293 total_space = max_frames - file_frame;
1300 /* Please note: the code to allocate buffers isn't run
1301 during normal butler thread operation. Its there
1302 for other times when we need to call do_refill()
1303 from somewhere other than the butler thread.
1306 if (mixdown_buffer == 0) {
1307 mixdown_buffer = new Sample[disk_io_chunk_frames];
1308 free_mixdown = true;
1310 free_mixdown = false;
1313 if (gain_buffer == 0) {
1314 gain_buffer = new float[disk_io_chunk_frames];
1321 workbuf = new char[disk_io_chunk_frames * 4];
1322 free_workbuf = true;
1324 free_workbuf = false;
1327 jack_nframes_t file_frame_tmp = 0;
1329 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1331 ChannelInfo& chan (*i);
1334 jack_nframes_t len1, len2;
1336 chan.playback_buf->get_write_vector (&vector);
1339 file_frame_tmp = file_frame;
1342 buf1 = vector.buf[1];
1343 len1 = vector.len[1];
1344 buf2 = vector.buf[0];
1345 len2 = vector.len[0];
1347 buf1 = vector.buf[0];
1348 len1 = vector.len[0];
1349 buf2 = vector.buf[1];
1350 len2 = vector.len[1];
1354 to_read = min (ts, len1);
1355 to_read = min (to_read, disk_io_chunk_frames);
1359 if (read (buf1, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1364 chan.playback_buf->increment_write_ptr (to_read);
1368 to_read = min (ts, len2);
1373 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1374 so read some or all of vector.len[1] as well.
1377 if (read (buf2, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1382 chan.playback_buf->increment_write_ptr (to_read);
1391 file_frame = file_frame_tmp;
1395 delete [] mixdown_buffer;
1398 delete [] gain_buffer;
1408 AudioDiskstream::do_flush (char * workbuf, bool force_flush)
1412 RingBufferNPT<Sample>::rw_vector vector;
1413 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1414 jack_nframes_t total;
1416 /* important note: this function will write *AT MOST*
1417 disk_io_chunk_frames of data to disk. it will never
1418 write more than that. if its writes that much and there
1419 is more than that waiting to be written, it will return 1,
1420 otherwise 0 on success or -1 on failure.
1422 if there is less than disk_io_chunk_frames to be written,
1423 no data will be written at all unless `force_flush' is true.
1426 _write_data_count = 0;
1428 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1430 (*chan).capture_buf->get_read_vector (&vector);
1432 total = vector.len[0] + vector.len[1];
1435 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1440 /* if there are 2+ chunks of disk i/o possible for
1441 this track, let the caller know so that it can arrange
1442 for us to be called again, ASAP.
1444 if we are forcing a flush, then if there is* any* extra
1445 work, let the caller know.
1447 if we are no longer recording and there is any extra work,
1448 let the caller know too.
1451 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1455 to_write = min (disk_io_chunk_frames, (jack_nframes_t) vector.len[0]);
1458 // check the transition buffer when recording destructive
1459 // important that we get this after the capture buf
1461 if (destructive()) {
1462 (*chan).capture_transition_buf->get_read_vector(&transvec);
1463 size_t transcount = transvec.len[0] + transvec.len[1];
1464 bool have_start = false;
1467 for (ti=0; ti < transcount; ++ti) {
1468 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1470 if (captrans.type == CaptureStart) {
1471 // by definition, the first data we got above represents the given capture pos
1473 (*chan).write_source->mark_capture_start (captrans.capture_val);
1474 (*chan).curr_capture_cnt = 0;
1478 else if (captrans.type == CaptureEnd) {
1480 // capture end, the capture_val represents total frames in capture
1482 if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1484 // shorten to make the write a perfect fit
1485 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt);
1487 if (nto_write < to_write) {
1488 ret = 1; // should we?
1490 to_write = nto_write;
1492 (*chan).write_source->mark_capture_end ();
1494 // increment past this transition, but go no further
1499 // actually ends just beyond this chunk, so force more work
1507 (*chan).capture_transition_buf->increment_read_ptr(ti);
1511 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write, workbuf) != to_write) {
1512 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1516 (*chan).capture_buf->increment_read_ptr (to_write);
1517 (*chan).curr_capture_cnt += to_write;
1519 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1521 /* we wrote all of vector.len[0] but it wasn't an entire
1522 disk_io_chunk_frames of data, so arrange for some part
1523 of vector.len[1] to be flushed to disk as well.
1526 to_write = min ((jack_nframes_t)(disk_io_chunk_frames - to_write), (jack_nframes_t) vector.len[1]);
1528 if ((*chan).write_source->write (vector.buf[1], to_write, workbuf) != to_write) {
1529 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1533 _write_data_count += (*chan).write_source->write_data_count();
1535 (*chan).capture_buf->increment_read_ptr (to_write);
1536 (*chan).curr_capture_cnt += to_write;
1545 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1547 uint32_t buffer_position;
1548 bool more_work = true;
1550 AudioRegion* region = 0;
1551 jack_nframes_t total_capture;
1552 AudioRegion::SourceList srcs;
1553 AudioRegion::SourceList::iterator src;
1554 ChannelList::iterator chan;
1555 vector<CaptureInfo*>::iterator ci;
1557 list<AudioFileSource*>* deletion_list;
1558 bool mark_write_completed = false;
1560 finish_capture (true);
1562 /* butler is already stopped, but there may be work to do
1563 to flush remaining data to disk.
1566 while (more_work && !err) {
1567 switch (do_flush ( _session.conversion_buffer(Session::TransportContext), true)) {
1574 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1579 /* XXX is there anything we can do if err != 0 ? */
1580 Glib::Mutex::Lock lm (capture_info_lock);
1582 if (capture_info.empty()) {
1586 if (abort_capture) {
1588 ChannelList::iterator chan;
1590 deletion_list = new list<AudioFileSource*>;
1592 for ( chan = channels.begin(); chan != channels.end(); ++chan) {
1594 if ((*chan).write_source) {
1596 (*chan).write_source->mark_for_remove ();
1597 (*chan).write_source->release ();
1599 deletion_list->push_back ((*chan).write_source);
1601 (*chan).write_source = 0;
1604 /* new source set up in "out" below */
1607 if (!deletion_list->empty()) {
1608 DeleteSources (deletion_list);
1610 delete deletion_list;
1616 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1617 total_capture += (*ci)->frames;
1620 /* figure out the name for this take */
1622 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1624 AudioFileSource* s = (*chan).write_source;
1628 AudioFileSource* fsrc;
1632 if ((fsrc = dynamic_cast<AudioFileSource *>(s)) != 0) {
1633 fsrc->update_header (capture_info.front()->start, when, twhen);
1636 s->set_captured_for (_name);
1641 /* destructive tracks have a single, never changing region */
1643 if (destructive()) {
1645 /* send a signal that any UI can pick up to do the right thing. there is
1646 a small problem here in that a UI may need the peak data to be ready
1647 for the data that was recorded and this isn't interlocked with that
1648 process. this problem is deferred to the UI.
1651 _playlist->Modified();
1655 /* Register a new region with the Session that
1656 describes the entire source. Do this first
1657 so that any sub-regions will obviously be
1658 children of this one (later!)
1662 region = new AudioRegion (srcs, channels[0].write_source->last_capture_start_frame(), total_capture,
1663 region_name_from_path (channels[0].write_source->name()),
1664 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
1666 region->special_set_position (capture_info.front()->start);
1670 catch (failed_constructor& err) {
1671 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1675 _last_capture_regions.push_back (region);
1677 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1679 _session.add_undo (_playlist->get_memento());
1680 _playlist->freeze ();
1682 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1685 _session.region_name (region_name, channels[0].write_source->name(), false);
1687 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1690 region = new AudioRegion (srcs, buffer_position, (*ci)->frames, region_name);
1693 catch (failed_constructor& err) {
1694 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1695 continue; /* XXX is this OK? */
1698 _last_capture_regions.push_back (region);
1700 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1702 i_am_the_modifier++;
1703 _playlist->add_region (*region, (*ci)->start);
1704 i_am_the_modifier--;
1706 buffer_position += (*ci)->frames;
1710 _session.add_redo_no_execute (_playlist->get_memento());
1713 mark_write_completed = true;
1715 reset_write_sources (mark_write_completed);
1718 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1722 capture_info.clear ();
1723 capture_start_frame = 0;
1727 AudioDiskstream::finish_capture (bool rec_monitors_input)
1729 was_recording = false;
1731 if (capture_captured == 0) {
1735 if (recordable() && destructive()) {
1736 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1738 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1739 (*chan).capture_transition_buf->get_write_vector(&transvec);
1742 if (transvec.len[0] > 0) {
1743 transvec.buf[0]->type = CaptureEnd;
1744 transvec.buf[0]->capture_val = capture_captured;
1745 (*chan).capture_transition_buf->increment_write_ptr(1);
1749 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1755 CaptureInfo* ci = new CaptureInfo;
1757 ci->start = capture_start_frame;
1758 ci->frames = capture_captured;
1760 /* XXX theoretical race condition here. Need atomic exchange ?
1761 However, the circumstances when this is called right
1762 now (either on record-disable or transport_stopped)
1763 mean that no actual race exists. I think ...
1764 We now have a capture_info_lock, but it is only to be used
1765 to synchronize in the transport_stop and the capture info
1766 accessors, so that invalidation will not occur (both non-realtime).
1769 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1771 capture_info.push_back (ci);
1772 capture_captured = 0;
1776 AudioDiskstream::set_record_enabled (bool yn, void* src)
1778 bool rolling = _session.transport_speed() != 0.0f;
1780 if (!recordable() || !_session.record_enabling_legal()) {
1784 /* if we're turning on rec-enable, there needs to be an
1788 if (yn && channels[0].source == 0) {
1790 /* pick up connections not initiated *from* the IO object
1791 we're associated with.
1794 get_input_sources ();
1797 /* yes, i know that this not proof against race conditions, but its
1798 good enough. i think.
1801 if (record_enabled() != yn) {
1803 g_atomic_int_set (&_record_enabled, 1);
1804 capturing_sources.clear ();
1805 if (Config->get_use_hardware_monitoring()) {
1806 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1807 if ((*chan).source) {
1808 (*chan).source->request_monitor_input (!(_session.get_auto_input() && rolling));
1810 capturing_sources.push_back ((*chan).write_source);
1813 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1814 capturing_sources.push_back ((*chan).write_source);
1819 g_atomic_int_set (&_record_enabled, 0);
1820 if (Config->get_use_hardware_monitoring()) {
1821 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1822 if ((*chan).source) {
1823 (*chan).source->request_monitor_input (false);
1827 capturing_sources.clear ();
1830 record_enable_changed (src); /* EMIT SIGNAL */
1835 AudioDiskstream::get_state ()
1837 XMLNode* node = new XMLNode ("AudioDiskstream");
1839 LocaleGuard lg (X_("POSIX"));
1841 snprintf (buf, sizeof(buf), "0x%x", _flags);
1842 node->add_property ("flags", buf);
1844 snprintf (buf, sizeof(buf), "%zd", channels.size());
1845 node->add_property ("channels", buf);
1847 node->add_property ("playlist", _playlist->name());
1849 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1850 node->add_property ("speed", buf);
1852 node->add_property("name", _name);
1853 snprintf (buf, sizeof(buf), "%" PRIu64, id());
1854 node->add_property("id", buf);
1856 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1858 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1859 XMLNode* cs_grandchild;
1861 for (vector<AudioFileSource*>::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1862 cs_grandchild = new XMLNode (X_("file"));
1863 cs_grandchild->add_property (X_("path"), (*i)->path());
1864 cs_child->add_child_nocopy (*cs_grandchild);
1867 /* store the location where capture will start */
1871 if (_session.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1872 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1874 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1877 cs_child->add_property (X_("at"), buf);
1878 node->add_child_nocopy (*cs_child);
1882 node->add_child_copy (*_extra_xml);
1889 AudioDiskstream::set_state (const XMLNode& node)
1891 const XMLProperty* prop;
1892 XMLNodeList nlist = node.children();
1893 XMLNodeIterator niter;
1894 uint32_t nchans = 1;
1895 XMLNode* capture_pending_node = 0;
1896 LocaleGuard lg (X_("POSIX"));
1898 in_set_state = true;
1900 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1901 if ((*niter)->name() == IO::state_node_name) {
1902 deprecated_io_node = new XMLNode (**niter);
1905 if ((*niter)->name() == X_("CapturingSources")) {
1906 capture_pending_node = *niter;
1910 /* prevent write sources from being created */
1912 in_set_state = true;
1914 if ((prop = node.property ("name")) != 0) {
1915 _name = prop->value();
1918 if (deprecated_io_node) {
1919 if ((prop = deprecated_io_node->property ("id")) != 0) {
1920 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
1923 if ((prop = node.property ("id")) != 0) {
1924 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
1928 if ((prop = node.property ("flags")) != 0) {
1929 _flags = strtol (prop->value().c_str(), 0, 0);
1932 if ((prop = node.property ("channels")) != 0) {
1933 nchans = atoi (prop->value().c_str());
1936 // create necessary extra channels
1937 // we are always constructed with one
1938 // and we always need one
1940 if (nchans > _n_channels) {
1942 // we need to add new channel infos
1943 //LockMonitor lm (state_lock, __LINE__, __FILE__);
1945 int diff = nchans - channels.size();
1947 for (int i=0; i < diff; ++i) {
1951 } else if (nchans < _n_channels) {
1953 // we need to get rid of channels
1954 //LockMonitor lm (state_lock, __LINE__, __FILE__);
1956 int diff = channels.size() - nchans;
1958 for (int i = 0; i < diff; ++i) {
1963 if ((prop = node.property ("playlist")) == 0) {
1968 bool had_playlist = (_playlist != 0);
1970 if (find_and_use_playlist (prop->value())) {
1974 if (!had_playlist) {
1975 _playlist->set_orig_diskstream_id (_id);
1978 if (!destructive() && capture_pending_node) {
1979 /* destructive streams have one and only one source per channel,
1980 and so they never end up in pending capture in any useful
1983 use_pending_capture_data (*capture_pending_node);
1988 if ((prop = node.property ("speed")) != 0) {
1989 double sp = atof (prop->value().c_str());
1991 if (realtime_set_speed (sp, false)) {
1992 non_realtime_set_speed ();
1996 _n_channels = channels.size();
1998 in_set_state = false;
2000 /* make sure this is clear before we do anything else */
2002 capturing_sources.clear ();
2004 /* write sources are handled when we handle the input set
2005 up of the IO that owns this DS (::non_realtime_input_change())
2008 in_set_state = false;
2014 AudioDiskstream::use_new_write_source (uint32_t n)
2016 if (!recordable()) {
2020 if (n >= channels.size()) {
2021 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2025 ChannelInfo &chan = channels[n];
2027 if (chan.write_source) {
2029 if (AudioFileSource::is_empty (chan.write_source->path())) {
2030 chan.write_source->mark_for_remove ();
2031 chan.write_source->release();
2032 delete chan.write_source;
2034 chan.write_source->release();
2035 chan.write_source = 0;
2040 if ((chan.write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2041 throw failed_constructor();
2045 catch (failed_constructor &err) {
2046 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2047 chan.write_source = 0;
2051 chan.write_source->use ();
2053 /* do not remove destructive files even if they are empty */
2055 chan.write_source->set_allow_remove_if_empty (!destructive());
2061 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2063 ChannelList::iterator chan;
2066 if (!recordable()) {
2070 capturing_sources.clear ();
2072 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2073 if (!destructive()) {
2075 if ((*chan).write_source && mark_write_complete) {
2076 (*chan).write_source->mark_streaming_write_completed ();
2078 use_new_write_source (n);
2080 if (record_enabled()) {
2081 capturing_sources.push_back ((*chan).write_source);
2085 if ((*chan).write_source == 0) {
2086 use_new_write_source (n);
2091 if (destructive()) {
2093 /* we now have all our write sources set up, so create the
2094 playlist's single region.
2097 if (_playlist->empty()) {
2098 setup_destructive_playlist ();
2104 AudioDiskstream::rename_write_sources ()
2106 ChannelList::iterator chan;
2109 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2110 if ((*chan).write_source != 0) {
2111 (*chan).write_source->set_name (_name, destructive());
2112 /* XXX what to do if one of them fails ? */
2120 AudioDiskstream::set_block_size (jack_nframes_t nframes)
2122 if (_session.get_block_size() > speed_buffer_size) {
2123 speed_buffer_size = _session.get_block_size();
2125 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2126 if ((*chan).speed_buffer) delete [] (*chan).speed_buffer;
2127 (*chan).speed_buffer = new Sample[speed_buffer_size];
2130 allocate_temporary_buffers ();
2134 AudioDiskstream::allocate_temporary_buffers ()
2136 /* make sure the wrap buffer is at least large enough to deal
2137 with the speeds up to 1.2, to allow for micro-variation
2138 when slaving to MTC, SMPTE etc.
2141 double sp = max (fabsf (_actual_speed), 1.2f);
2142 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * sp) + 1;
2144 if (required_wrap_size > wrap_buffer_size) {
2146 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2147 if ((*chan).playback_wrap_buffer) delete [] (*chan).playback_wrap_buffer;
2148 (*chan).playback_wrap_buffer = new Sample[required_wrap_size];
2149 if ((*chan).capture_wrap_buffer) delete [] (*chan).capture_wrap_buffer;
2150 (*chan).capture_wrap_buffer = new Sample[required_wrap_size];
2153 wrap_buffer_size = required_wrap_size;
2158 AudioDiskstream::monitor_input (bool yn)
2160 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2162 if ((*chan).source) {
2163 (*chan).source->request_monitor_input (yn);
2169 AudioDiskstream::set_align_style_from_io ()
2171 bool have_physical = false;
2177 get_input_sources ();
2179 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2180 if ((*chan).source && (*chan).source->flags() & JackPortIsPhysical) {
2181 have_physical = true;
2186 if (have_physical) {
2187 set_align_style (ExistingMaterial);
2189 set_align_style (CaptureTime);
2194 AudioDiskstream::add_channel ()
2196 /* XXX need to take lock??? */
2200 init_channel (chan);
2202 chan.speed_buffer = new Sample[speed_buffer_size];
2203 chan.playback_wrap_buffer = new Sample[wrap_buffer_size];
2204 chan.capture_wrap_buffer = new Sample[wrap_buffer_size];
2206 channels.push_back (chan);
2208 _n_channels = channels.size();
2214 AudioDiskstream::remove_channel ()
2216 if (channels.size() > 1) {
2217 /* XXX need to take lock??? */
2218 ChannelInfo & chan = channels.back();
2219 destroy_channel (chan);
2220 channels.pop_back();
2222 _n_channels = channels.size();
2230 AudioDiskstream::playback_buffer_load () const
2232 return (float) ((double) channels.front().playback_buf->read_space()/
2233 (double) channels.front().playback_buf->bufsize());
2237 AudioDiskstream::capture_buffer_load () const
2239 return (float) ((double) channels.front().capture_buf->write_space()/
2240 (double) channels.front().capture_buf->bufsize());
2245 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2247 const XMLProperty* prop;
2248 XMLNodeList nlist = node.children();
2249 XMLNodeIterator niter;
2250 AudioFileSource* fs;
2251 AudioFileSource* first_fs = 0;
2252 AudioRegion::SourceList pending_sources;
2253 jack_nframes_t position;
2255 if ((prop = node.property (X_("at"))) == 0) {
2259 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2263 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2264 if ((*niter)->name() == X_("file")) {
2266 if ((prop = (*niter)->property (X_("path"))) == 0) {
2271 fs = new SndFileSource (prop->value(),
2272 Config->get_native_file_data_format(),
2273 Config->get_native_file_header_format(),
2274 _session.frame_rate());
2277 catch (failed_constructor& err) {
2278 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2279 _name, prop->value())
2284 pending_sources.push_back (fs);
2286 if (first_fs == 0) {
2290 fs->set_captured_for (_name);
2294 if (pending_sources.size() == 0) {
2295 /* nothing can be done */
2299 if (pending_sources.size() != _n_channels) {
2300 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2305 AudioRegion* region;
2308 region = new AudioRegion (pending_sources, 0, first_fs->length(),
2309 region_name_from_path (first_fs->name()),
2310 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
2312 region->special_set_position (0);
2315 catch (failed_constructor& err) {
2316 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2324 region = new AudioRegion (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name()));
2327 catch (failed_constructor& err) {
2328 error << string_compose (_("%1: cannot create region from pending capture sources"),
2335 _playlist->add_region (*region, position);