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>
38 #include <pbd/memento_command.h>
40 #include <ardour/ardour.h>
41 #include <ardour/audioengine.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/utils.h>
44 #include <ardour/configuration.h>
45 #include <ardour/audiofilesource.h>
46 #include <ardour/destructive_filesource.h>
47 #include <ardour/send.h>
48 #include <ardour/audioplaylist.h>
49 #include <ardour/cycle_timer.h>
50 #include <ardour/audioregion.h>
56 using namespace ARDOUR;
59 jack_nframes_t AudioDiskstream::disk_io_chunk_frames;
61 sigc::signal<void,AudioDiskstream*> AudioDiskstream::AudioDiskstreamCreated;
62 sigc::signal<void,list<AudioFileSource*>*> AudioDiskstream::DeleteSources;
63 sigc::signal<void> AudioDiskstream::DiskOverrun;
64 sigc::signal<void> AudioDiskstream::DiskUnderrun;
66 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Flag flag)
70 /* prevent any write sources from being created */
79 AudioDiskstreamCreated (this); /* EMIT SIGNAL */
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
89 if (set_state (node)) {
91 throw failed_constructor();
97 use_destructive_playlist ();
100 AudioDiskstreamCreated (this); /* EMIT SIGNAL */
104 AudioDiskstream::init_channel (ChannelInfo &chan)
106 chan.playback_wrap_buffer = 0;
107 chan.capture_wrap_buffer = 0;
108 chan.speed_buffer = 0;
109 chan.peak_power = 0.0f;
110 chan.write_source = 0;
112 chan.current_capture_buffer = 0;
113 chan.current_playback_buffer = 0;
114 chan.curr_capture_cnt = 0;
116 chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
117 chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
118 chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
121 /* touch the ringbuffer buffers, which will cause
122 them to be mapped into locked physical RAM if
123 we're running with mlockall(). this doesn't do
126 memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
127 memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
128 memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
133 AudioDiskstream::init (Flag f)
139 _alignment_style = ExistingMaterial;
140 _persistent_alignment_style = ExistingMaterial;
141 first_input_change = true;
143 i_am_the_modifier = 0;
144 g_atomic_int_set (&_record_enabled, 0);
145 was_recording = false;
146 capture_start_frame = 0;
147 capture_captured = 0;
148 _visible_speed = 1.0f;
149 _actual_speed = 1.0f;
150 _buffer_reallocation_required = false;
151 _seek_required = false;
152 first_recordable_frame = max_frames;
153 last_recordable_frame = max_frames;
158 adjust_capture_position = 0;
159 last_possibly_recording = 0;
161 wrap_buffer_size = 0;
162 speed_buffer_size = 0;
164 phi = (uint64_t) (0x1000000);
167 playback_distance = 0;
168 _read_data_count = 0;
169 _write_data_count = 0;
170 deprecated_io_node = 0;
172 /* there are no channels at this point, so these
173 two calls just get speed_buffer_size and wrap_buffer
174 size setup without duplicating their code.
177 set_block_size (_session.get_block_size());
178 allocate_temporary_buffers ();
180 pending_overwrite = false;
182 overwrite_queued = false;
183 input_change_pending = NoChange;
190 AudioDiskstream::destroy_channel (ChannelInfo &chan)
192 if (chan.write_source) {
193 chan.write_source->release ();
194 chan.write_source = 0;
197 if (chan.speed_buffer) {
198 delete [] chan.speed_buffer;
201 if (chan.playback_wrap_buffer) {
202 delete [] chan.playback_wrap_buffer;
204 if (chan.capture_wrap_buffer) {
205 delete [] chan.capture_wrap_buffer;
208 delete chan.playback_buf;
209 delete chan.capture_buf;
210 delete chan.capture_transition_buf;
212 chan.playback_buf = 0;
213 chan.capture_buf = 0;
216 AudioDiskstream::~AudioDiskstream ()
218 Glib::Mutex::Lock lm (state_lock);
224 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
225 destroy_channel((*chan));
232 AudioDiskstream::handle_input_change (IOChange change, void *src)
234 Glib::Mutex::Lock lm (state_lock);
236 if (!(input_change_pending & change)) {
237 input_change_pending = IOChange (input_change_pending|change);
238 _session.request_input_change_handling ();
243 AudioDiskstream::non_realtime_input_change ()
246 Glib::Mutex::Lock lm (state_lock);
248 if (input_change_pending == NoChange) {
252 if (input_change_pending & ConfigurationChanged) {
254 if (_io->n_inputs() > _n_channels) {
256 // we need to add new channel infos
258 int diff = _io->n_inputs() - channels.size();
260 for (int i = 0; i < diff; ++i) {
264 } else if (_io->n_inputs() < _n_channels) {
266 // we need to get rid of channels
268 int diff = channels.size() - _io->n_inputs();
270 for (int i = 0; i < diff; ++i) {
276 get_input_sources ();
277 set_capture_offset ();
279 if (first_input_change) {
280 set_align_style (_persistent_alignment_style);
281 first_input_change = false;
283 set_align_style_from_io ();
286 input_change_pending = NoChange;
289 /* reset capture files */
291 reset_write_sources (false);
293 /* now refill channel buffers */
295 if (speed() != 1.0f || speed() != -1.0f) {
296 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()));
299 seek (_session.transport_frame());
304 AudioDiskstream::get_input_sources ()
306 uint32_t ni = _io->n_inputs();
308 for (uint32_t n = 0; n < ni; ++n) {
310 const char **connections = _io->input(n)->get_connections ();
311 ChannelInfo& chan = channels[n];
313 if (connections == 0 || connections[0] == 0) {
316 // _source->disable_metering ();
322 chan.source = _session.engine().get_port_by_name (connections[0]);
332 AudioDiskstream::find_and_use_playlist (const string& name)
335 AudioPlaylist* playlist;
337 if ((pl = _session.get_playlist (name)) == 0) {
338 error << string_compose(_("AudioDiskstream: Session doesn't know about a Playlist called \"%1\""), name) << endmsg;
342 if ((playlist = dynamic_cast<AudioPlaylist*> (pl)) == 0) {
343 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
347 return use_playlist (playlist);
351 AudioDiskstream::use_playlist (AudioPlaylist* playlist)
354 Glib::Mutex::Lock lm (state_lock);
356 if (playlist == _playlist) {
360 plstate_connection.disconnect();
361 plmod_connection.disconnect ();
362 plgone_connection.disconnect ();
368 _playlist = playlist;
371 if (!in_set_state && recordable()) {
372 reset_write_sources (false);
375 plstate_connection = _playlist->StateChanged.connect (mem_fun (*this, &AudioDiskstream::playlist_changed));
376 plmod_connection = _playlist->Modified.connect (mem_fun (*this, &AudioDiskstream::playlist_modified));
377 plgone_connection = _playlist->GoingAway.connect (mem_fun (*this, &AudioDiskstream::playlist_deleted));
380 if (!overwrite_queued) {
381 _session.request_overwrite_buffer (this);
382 overwrite_queued = true;
385 PlaylistChanged (); /* EMIT SIGNAL */
386 _session.set_dirty ();
392 AudioDiskstream::playlist_deleted (Playlist* pl)
394 /* this catches an ordering issue with session destruction. playlists
395 are destroyed before diskstreams. we have to invalidate any handles
396 we have to the playlist.
403 AudioDiskstream::use_new_playlist ()
406 AudioPlaylist* playlist;
408 if (!in_set_state && destructive()) {
413 newname = Playlist::bump_name (_playlist->name(), _session);
415 newname = Playlist::bump_name (_name, _session);
418 if ((playlist = new AudioPlaylist (_session, newname, hidden())) != 0) {
419 playlist->set_orig_diskstream_id (id());
420 return use_playlist (playlist);
427 AudioDiskstream::use_copy_playlist ()
433 if (_playlist == 0) {
434 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
439 AudioPlaylist* playlist;
441 newname = Playlist::bump_name (_playlist->name(), _session);
443 if ((playlist = new AudioPlaylist (*_playlist, newname)) != 0) {
444 playlist->set_orig_diskstream_id (id());
445 return use_playlist (playlist);
452 AudioDiskstream::setup_destructive_playlist ()
454 AudioRegion::SourceList srcs;
456 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
457 srcs.push_back ((*chan).write_source);
460 /* a single full-sized region */
462 AudioRegion* region = new AudioRegion (srcs, 0, max_frames, _name);
463 _playlist->add_region (*region, 0);
467 AudioDiskstream::use_destructive_playlist ()
469 /* use the sources associated with the single full-extent region */
471 Playlist::RegionList* rl = _playlist->regions_at (0);
474 reset_write_sources (false, true);
478 AudioRegion* region = dynamic_cast<AudioRegion*> (rl->front());
481 throw failed_constructor();
487 ChannelList::iterator chan;
489 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
490 (*chan).write_source = dynamic_cast<AudioFileSource*>(®ion->source (n));
491 (*chan).write_source->set_allow_remove_if_empty (false);
494 /* the source list will never be reset for a destructive track */
498 AudioDiskstream::set_io (IO& io)
501 set_align_style_from_io ();
505 AudioDiskstream::set_name (string str, void *src)
508 _playlist->set_name (str);
511 if (!in_set_state && recordable()) {
512 /* rename existing capture files so that they have the correct name */
513 return rename_write_sources ();
523 AudioDiskstream::set_speed (double sp)
525 _session.request_diskstream_speed (*this, sp);
527 /* to force a rebuffering at the right place */
532 AudioDiskstream::realtime_set_speed (double sp, bool global)
534 bool changed = false;
535 double new_speed = sp * _session.transport_speed();
537 if (_visible_speed != sp) {
542 if (new_speed != _actual_speed) {
544 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() *
545 fabs (new_speed)) + 1;
547 if (required_wrap_size > wrap_buffer_size) {
548 _buffer_reallocation_required = true;
551 _actual_speed = new_speed;
552 phi = (uint64_t) (0x1000000 * fabs(_actual_speed));
557 _seek_required = true;
559 speed_changed (); /* EMIT SIGNAL */
562 return _buffer_reallocation_required || _seek_required;
566 AudioDiskstream::non_realtime_set_speed ()
568 if (_buffer_reallocation_required)
570 Glib::Mutex::Lock lm (state_lock);
571 allocate_temporary_buffers ();
573 _buffer_reallocation_required = false;
576 if (_seek_required) {
577 if (speed() != 1.0f || speed() != -1.0f) {
578 seek ((jack_nframes_t) (_session.transport_frame() * (double) speed()), true);
581 seek (_session.transport_frame(), true);
584 _seek_required = false;
589 AudioDiskstream::prepare ()
592 playback_distance = 0;
596 AudioDiskstream::check_record_status (jack_nframes_t transport_frame, jack_nframes_t nframes, bool can_record)
598 int possibly_recording;
601 const int transport_rolling = 0x4;
602 const int track_rec_enabled = 0x2;
603 const int global_rec_enabled = 0x1;
605 /* merge together the 3 factors that affect record status, and compute
609 rolling = _session.transport_speed() != 0.0f;
610 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
611 change = possibly_recording ^ last_possibly_recording;
613 if (possibly_recording == last_possibly_recording) {
619 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
621 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
622 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
624 /* starting to record: compute first+last frames */
626 first_recordable_frame = transport_frame + _capture_offset;
627 last_recordable_frame = max_frames;
628 capture_start_frame = transport_frame;
630 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
632 /* was stopped, now rolling (and recording) */
634 if (_alignment_style == ExistingMaterial) {
635 first_recordable_frame += _session.worst_output_latency();
637 first_recordable_frame += _roll_delay;
642 /* was rolling, but record state changed */
644 if (_alignment_style == ExistingMaterial) {
647 if (!_session.get_punch_in()) {
649 /* manual punch in happens at the correct transport frame
650 because the user hit a button. but to get alignment correct
651 we have to back up the position of the new region to the
652 appropriate spot given the roll delay.
655 capture_start_frame -= _roll_delay;
657 /* XXX paul notes (august 2005): i don't know why
661 first_recordable_frame += _capture_offset;
665 /* autopunch toggles recording at the precise
666 transport frame, and then the DS waits
667 to start recording for a time that depends
668 on the output latency.
671 first_recordable_frame += _session.worst_output_latency();
676 if (_session.get_punch_in()) {
677 first_recordable_frame += _roll_delay;
679 capture_start_frame -= _roll_delay;
685 if (_flags & Recordable) {
686 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
688 RingBufferNPT<CaptureTransition>::rw_vector transvec;
689 (*chan).capture_transition_buf->get_write_vector(&transvec);
691 if (transvec.len[0] > 0) {
692 transvec.buf[0]->type = CaptureStart;
693 transvec.buf[0]->capture_val = capture_start_frame;
694 (*chan).capture_transition_buf->increment_write_ptr(1);
698 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
704 } else if (!record_enabled() || !can_record) {
708 last_recordable_frame = transport_frame + _capture_offset;
710 if (_alignment_style == ExistingMaterial) {
711 last_recordable_frame += _session.worst_output_latency();
713 last_recordable_frame += _roll_delay;
717 last_possibly_recording = possibly_recording;
721 AudioDiskstream::process (jack_nframes_t transport_frame, jack_nframes_t nframes, jack_nframes_t offset, bool can_record, bool rec_monitors_input)
724 ChannelList::iterator c;
726 jack_nframes_t rec_offset = 0;
727 jack_nframes_t rec_nframes = 0;
728 bool nominally_recording;
729 bool re = record_enabled ();
730 bool collect_playback = false;
732 /* if we've already processed the frames corresponding to this call,
733 just return. this allows multiple routes that are taking input
734 from this diskstream to call our ::process() method, but have
735 this stuff only happen once. more commonly, it allows both
736 the AudioTrack that is using this AudioDiskstream *and* the Session
737 to call process() without problems.
744 check_record_status (transport_frame, nframes, can_record);
746 nominally_recording = (can_record && re);
753 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
754 must always be called as a pair. The only exception is if this function
755 returns a non-zero value, in which case, ::commit should not be called.
758 // If we can't take the state lock return.
759 if (!state_lock.trylock()) {
763 adjust_capture_position = 0;
765 for (c = channels.begin(); c != channels.end(); ++c) {
766 (*c).current_capture_buffer = 0;
767 (*c).current_playback_buffer = 0;
770 if (nominally_recording || (_session.get_record_enabled() && _session.get_punch_in())) {
773 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
780 case OverlapInternal:
781 /* ---------- recrange
784 rec_nframes = nframes;
789 /* |--------| recrange
792 rec_nframes = transport_frame + nframes - first_recordable_frame;
794 rec_offset = first_recordable_frame - transport_frame;
799 /* |--------| recrange
802 rec_nframes = last_recordable_frame - transport_frame;
806 case OverlapExternal:
807 /* |--------| recrange
808 -------------- transrange
810 rec_nframes = last_recordable_frame - last_recordable_frame;
811 rec_offset = first_recordable_frame - transport_frame;
815 if (rec_nframes && !was_recording) {
816 capture_captured = 0;
817 was_recording = true;
822 if (can_record && !_last_capture_regions.empty()) {
823 _last_capture_regions.clear ();
826 if (nominally_recording || rec_nframes) {
828 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
830 ChannelInfo& chan (*c);
832 chan.capture_buf->get_write_vector (&chan.capture_vector);
834 if (rec_nframes <= chan.capture_vector.len[0]) {
836 chan.current_capture_buffer = chan.capture_vector.buf[0];
838 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
842 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
846 jack_nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
848 if (rec_nframes > total) {
853 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
854 jack_nframes_t first = chan.capture_vector.len[0];
856 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
857 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
858 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
859 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
861 chan.current_capture_buffer = chan.capture_wrap_buffer;
868 finish_capture (rec_monitors_input);
875 /* data will be written to disk */
877 if (rec_nframes == nframes && rec_offset == 0) {
879 for (c = channels.begin(); c != channels.end(); ++c) {
880 (*c).current_playback_buffer = (*c).current_capture_buffer;
883 playback_distance = nframes;
888 /* we can't use the capture buffer as the playback buffer, because
889 we recorded only a part of the current process' cycle data
893 collect_playback = true;
896 adjust_capture_position = rec_nframes;
898 } else if (nominally_recording) {
900 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
902 for (c = channels.begin(); c != channels.end(); ++c) {
903 (*c).current_playback_buffer = (*c).current_capture_buffer;
906 playback_distance = nframes;
910 collect_playback = true;
913 if (collect_playback) {
915 /* we're doing playback */
917 jack_nframes_t necessary_samples;
919 /* no varispeed playback if we're recording, because the output .... TBD */
921 if (rec_nframes == 0 && _actual_speed != 1.0f) {
922 necessary_samples = (jack_nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
924 necessary_samples = nframes;
927 for (c = channels.begin(); c != channels.end(); ++c) {
928 (*c).playback_buf->get_read_vector (&(*c).playback_vector);
933 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
935 ChannelInfo& chan (*c);
937 if (necessary_samples <= chan.playback_vector.len[0]) {
939 chan.current_playback_buffer = chan.playback_vector.buf[0];
942 jack_nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
944 if (necessary_samples > total) {
950 memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
951 chan.playback_vector.len[0] * sizeof (Sample));
952 memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1],
953 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
955 chan.current_playback_buffer = chan.playback_wrap_buffer;
960 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
962 uint64_t phase = last_phase;
963 jack_nframes_t i = 0;
965 // Linearly interpolate into the alt buffer
966 // using 40.24 fixp maths (swh)
968 for (c = channels.begin(); c != channels.end(); ++c) {
971 ChannelInfo& chan (*c);
976 for (jack_nframes_t outsample = 0; outsample < nframes; ++outsample) {
978 fr = (phase & 0xFFFFFF) / 16777216.0f;
979 chan.speed_buffer[outsample] =
980 chan.current_playback_buffer[i] * (1.0f - fr) +
981 chan.current_playback_buffer[i+1] * fr;
985 chan.current_playback_buffer = chan.speed_buffer;
988 playback_distance = i + 1;
989 last_phase = (phase & 0xFFFFFF);
992 playback_distance = nframes;
1004 /* we're exiting with failure, so ::commit will not
1005 be called. unlock the state lock.
1008 state_lock.unlock();
1015 AudioDiskstream::recover ()
1017 state_lock.unlock();
1022 AudioDiskstream::commit (jack_nframes_t nframes)
1024 bool need_butler = false;
1026 if (_actual_speed < 0.0) {
1027 playback_sample -= playback_distance;
1029 playback_sample += playback_distance;
1032 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1034 (*chan).playback_buf->increment_read_ptr (playback_distance);
1036 if (adjust_capture_position) {
1037 (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
1041 if (adjust_capture_position != 0) {
1042 capture_captured += adjust_capture_position;
1043 adjust_capture_position = 0;
1047 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
1049 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
1050 || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
1053 state_lock.unlock();
1061 AudioDiskstream::set_pending_overwrite (bool yn)
1063 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
1065 pending_overwrite = yn;
1067 overwrite_frame = playback_sample;
1068 overwrite_offset = channels.front().playback_buf->get_read_ptr();
1072 AudioDiskstream::overwrite_existing_buffers ()
1074 Sample* mixdown_buffer;
1078 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1080 overwrite_queued = false;
1082 /* assume all are the same size */
1083 jack_nframes_t size = channels[0].playback_buf->bufsize();
1085 mixdown_buffer = new Sample[size];
1086 gain_buffer = new float[size];
1087 workbuf = new char[size*4];
1089 /* reduce size so that we can fill the buffer correctly. */
1093 jack_nframes_t start;
1095 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1097 start = overwrite_frame;
1098 jack_nframes_t cnt = size;
1100 /* to fill the buffer without resetting the playback sample, we need to
1101 do it one or two chunks (normally two).
1103 |----------------------------------------------------------------------|
1107 |<- second chunk->||<----------------- first chunk ------------------>|
1111 jack_nframes_t to_read = size - overwrite_offset;
1113 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, workbuf,
1114 start, to_read, *chan, n, reversed)) {
1115 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1116 _id, size, playback_sample) << endmsg;
1120 if (cnt > to_read) {
1124 if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer, workbuf,
1125 start, cnt, *chan, n, reversed)) {
1126 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
1127 _id, size, playback_sample) << endmsg;
1136 pending_overwrite = false;
1137 delete [] gain_buffer;
1138 delete [] mixdown_buffer;
1144 AudioDiskstream::seek (jack_nframes_t frame, bool complete_refill)
1146 Glib::Mutex::Lock lm (state_lock);
1149 ChannelList::iterator chan;
1151 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1152 (*chan).playback_buf->reset ();
1153 (*chan).capture_buf->reset ();
1156 playback_sample = frame;
1159 if (complete_refill) {
1160 while ((ret = do_refill (0, 0, 0)) > 0);
1162 ret = do_refill (0, 0, 0);
1169 AudioDiskstream::can_internal_playback_seek (jack_nframes_t distance)
1171 ChannelList::iterator chan;
1173 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1174 if ((*chan).playback_buf->read_space() < distance) {
1182 AudioDiskstream::internal_playback_seek (jack_nframes_t distance)
1184 ChannelList::iterator chan;
1186 for (chan = channels.begin(); chan != channels.end(); ++chan) {
1187 (*chan).playback_buf->increment_read_ptr (distance);
1190 first_recordable_frame += distance;
1191 playback_sample += distance;
1197 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, char * workbuf, jack_nframes_t& start, jack_nframes_t cnt,
1198 ChannelInfo& channel_info, int channel, bool reversed)
1200 jack_nframes_t this_read = 0;
1201 bool reloop = false;
1202 jack_nframes_t loop_end = 0;
1203 jack_nframes_t loop_start = 0;
1204 jack_nframes_t loop_length = 0;
1205 jack_nframes_t offset = 0;
1209 /* Make the use of a Location atomic for this read operation.
1211 Note: Locations don't get deleted, so all we care about
1212 when I say "atomic" is that we are always pointing to
1213 the same one and using a start/length values obtained
1217 if ((loc = loop_location) != 0) {
1218 loop_start = loc->start();
1219 loop_end = loc->end();
1220 loop_length = loop_end - loop_start;
1223 /* if we are looping, ensure that the first frame we read is at the correct
1224 position within the loop.
1227 if (loc && start >= loop_end) {
1228 //cerr << "start adjusted from " << start;
1229 start = loop_start + ((start - loop_start) % loop_length);
1230 //cerr << "to " << start << endl;
1232 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1237 /* take any loop into account. we can't read past the end of the loop. */
1239 if (loc && (loop_end - start < cnt)) {
1240 this_read = loop_end - start;
1241 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1248 if (this_read == 0) {
1252 this_read = min(cnt,this_read);
1254 if (_playlist->read (buf+offset, mixdown_buffer, gain_buffer, workbuf, start, this_read, channel) != this_read) {
1255 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1260 _read_data_count = _playlist->read_data_count();
1264 /* don't adjust start, since caller has already done that
1267 swap_by_ptr (buf, buf + this_read - 1);
1271 /* if we read to the end of the loop, go back to the beginning */
1281 offset += this_read;
1288 AudioDiskstream::do_refill (Sample* mixdown_buffer, float* gain_buffer, char * workbuf)
1291 jack_nframes_t to_read;
1292 RingBufferNPT<Sample>::rw_vector vector;
1296 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1297 jack_nframes_t total_space;
1298 jack_nframes_t zero_fill;
1300 ChannelList::iterator i;
1303 channels.front().playback_buf->get_write_vector (&vector);
1305 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1309 /* if there are 2+ chunks of disk i/o possible for
1310 this track, let the caller know so that it can arrange
1311 for us to be called again, ASAP.
1314 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1318 /* if we're running close to normal speed and there isn't enough
1319 space to do disk_io_chunk_frames of I/O, then don't bother.
1321 at higher speeds, just do it because the sync between butler
1322 and audio thread may not be good enough.
1325 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1329 /* when slaved, don't try to get too close to the read pointer. this
1330 leaves space for the buffer reversal to have something useful to
1334 if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1338 total_space = min (disk_io_chunk_frames, total_space);
1342 if (file_frame == 0) {
1344 /* at start: nothing to do but fill with silence */
1346 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1348 ChannelInfo& chan (*i);
1349 chan.playback_buf->get_write_vector (&vector);
1350 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1351 if (vector.len[1]) {
1352 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1354 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1359 if (file_frame < total_space) {
1361 /* too close to the start: read what we can,
1362 and then zero fill the rest
1365 zero_fill = total_space - file_frame;
1366 total_space = file_frame;
1371 /* move read position backwards because we are going
1372 to reverse the data.
1375 file_frame -= total_space;
1381 if (file_frame == max_frames) {
1383 /* at end: nothing to do but fill with silence */
1385 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1387 ChannelInfo& chan (*i);
1388 chan.playback_buf->get_write_vector (&vector);
1389 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1390 if (vector.len[1]) {
1391 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1393 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1398 if (file_frame > max_frames - total_space) {
1400 /* to close to the end: read what we can, and zero fill the rest */
1402 zero_fill = total_space - (max_frames - file_frame);
1403 total_space = max_frames - file_frame;
1410 /* Please note: the code to allocate buffers isn't run
1411 during normal butler thread operation. Its there
1412 for other times when we need to call do_refill()
1413 from somewhere other than the butler thread.
1416 if (mixdown_buffer == 0) {
1417 mixdown_buffer = new Sample[disk_io_chunk_frames];
1418 free_mixdown = true;
1420 free_mixdown = false;
1423 if (gain_buffer == 0) {
1424 gain_buffer = new float[disk_io_chunk_frames];
1431 workbuf = new char[disk_io_chunk_frames * 4];
1432 free_workbuf = true;
1434 free_workbuf = false;
1437 jack_nframes_t file_frame_tmp = 0;
1439 for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1441 ChannelInfo& chan (*i);
1444 jack_nframes_t len1, len2;
1446 chan.playback_buf->get_write_vector (&vector);
1449 file_frame_tmp = file_frame;
1452 buf1 = vector.buf[1];
1453 len1 = vector.len[1];
1454 buf2 = vector.buf[0];
1455 len2 = vector.len[0];
1457 buf1 = vector.buf[0];
1458 len1 = vector.len[0];
1459 buf2 = vector.buf[1];
1460 len2 = vector.len[1];
1464 to_read = min (ts, len1);
1465 to_read = min (to_read, disk_io_chunk_frames);
1469 if (read (buf1, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1474 chan.playback_buf->increment_write_ptr (to_read);
1478 to_read = min (ts, len2);
1483 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1484 so read some or all of vector.len[1] as well.
1487 if (read (buf2, mixdown_buffer, gain_buffer, workbuf, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1492 chan.playback_buf->increment_write_ptr (to_read);
1501 file_frame = file_frame_tmp;
1505 delete [] mixdown_buffer;
1508 delete [] gain_buffer;
1518 AudioDiskstream::do_flush (char * workbuf, bool force_flush)
1522 RingBufferNPT<Sample>::rw_vector vector;
1523 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1524 jack_nframes_t total;
1526 /* important note: this function will write *AT MOST*
1527 disk_io_chunk_frames of data to disk. it will never
1528 write more than that. if its writes that much and there
1529 is more than that waiting to be written, it will return 1,
1530 otherwise 0 on success or -1 on failure.
1532 if there is less than disk_io_chunk_frames to be written,
1533 no data will be written at all unless `force_flush' is true.
1536 _write_data_count = 0;
1538 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1540 (*chan).capture_buf->get_read_vector (&vector);
1542 total = vector.len[0] + vector.len[1];
1545 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1550 /* if there are 2+ chunks of disk i/o possible for
1551 this track, let the caller know so that it can arrange
1552 for us to be called again, ASAP.
1554 if we are forcing a flush, then if there is* any* extra
1555 work, let the caller know.
1557 if we are no longer recording and there is any extra work,
1558 let the caller know too.
1561 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1565 to_write = min (disk_io_chunk_frames, (jack_nframes_t) vector.len[0]);
1568 // check the transition buffer when recording destructive
1569 // important that we get this after the capture buf
1571 if (destructive()) {
1572 (*chan).capture_transition_buf->get_read_vector(&transvec);
1573 size_t transcount = transvec.len[0] + transvec.len[1];
1574 bool have_start = false;
1577 for (ti=0; ti < transcount; ++ti) {
1578 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1580 if (captrans.type == CaptureStart) {
1581 // by definition, the first data we got above represents the given capture pos
1583 (*chan).write_source->mark_capture_start (captrans.capture_val);
1584 (*chan).curr_capture_cnt = 0;
1588 else if (captrans.type == CaptureEnd) {
1590 // capture end, the capture_val represents total frames in capture
1592 if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1594 // shorten to make the write a perfect fit
1595 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt);
1597 if (nto_write < to_write) {
1598 ret = 1; // should we?
1600 to_write = nto_write;
1602 (*chan).write_source->mark_capture_end ();
1604 // increment past this transition, but go no further
1609 // actually ends just beyond this chunk, so force more work
1617 (*chan).capture_transition_buf->increment_read_ptr(ti);
1621 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write, workbuf) != to_write) {
1622 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1626 (*chan).capture_buf->increment_read_ptr (to_write);
1627 (*chan).curr_capture_cnt += to_write;
1629 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1631 /* we wrote all of vector.len[0] but it wasn't an entire
1632 disk_io_chunk_frames of data, so arrange for some part
1633 of vector.len[1] to be flushed to disk as well.
1636 to_write = min ((jack_nframes_t)(disk_io_chunk_frames - to_write), (jack_nframes_t) vector.len[1]);
1638 if ((*chan).write_source->write (vector.buf[1], to_write, workbuf) != to_write) {
1639 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1643 _write_data_count += (*chan).write_source->write_data_count();
1645 (*chan).capture_buf->increment_read_ptr (to_write);
1646 (*chan).curr_capture_cnt += to_write;
1655 AudioDiskstream::playlist_changed (Change ignored)
1657 playlist_modified ();
1661 AudioDiskstream::playlist_modified ()
1663 if (!i_am_the_modifier && !overwrite_queued) {
1664 _session.request_overwrite_buffer (this);
1665 overwrite_queued = true;
1670 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1672 uint32_t buffer_position;
1673 bool more_work = true;
1675 AudioRegion* region = 0;
1676 jack_nframes_t total_capture;
1677 AudioRegion::SourceList srcs;
1678 AudioRegion::SourceList::iterator src;
1679 ChannelList::iterator chan;
1680 vector<CaptureInfo*>::iterator ci;
1682 list<AudioFileSource*>* deletion_list;
1683 bool mark_write_completed = false;
1685 finish_capture (true);
1687 /* butler is already stopped, but there may be work to do
1688 to flush remaining data to disk.
1691 while (more_work && !err) {
1692 switch (do_flush ( _session.conversion_buffer(Session::TransportContext), true)) {
1699 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1704 /* XXX is there anything we can do if err != 0 ? */
1705 Glib::Mutex::Lock lm (capture_info_lock);
1707 if (capture_info.empty()) {
1711 if (abort_capture) {
1713 ChannelList::iterator chan;
1715 deletion_list = new list<AudioFileSource*>;
1717 for ( chan = channels.begin(); chan != channels.end(); ++chan) {
1719 if ((*chan).write_source) {
1721 (*chan).write_source->mark_for_remove ();
1722 (*chan).write_source->release ();
1724 deletion_list->push_back ((*chan).write_source);
1726 (*chan).write_source = 0;
1729 /* new source set up in "out" below */
1732 if (!deletion_list->empty()) {
1733 DeleteSources (deletion_list);
1735 delete deletion_list;
1741 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1742 total_capture += (*ci)->frames;
1745 /* figure out the name for this take */
1747 for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1749 AudioFileSource* s = (*chan).write_source;
1753 AudioFileSource* fsrc;
1757 if ((fsrc = dynamic_cast<AudioFileSource *>(s)) != 0) {
1758 cerr << "updating source after capture\n";
1759 fsrc->update_header (capture_info.front()->start, when, twhen);
1762 s->set_captured_for (_name);
1767 /* destructive tracks have a single, never changing region */
1769 if (destructive()) {
1771 /* send a signal that any UI can pick up to do the right thing. there is
1772 a small problem here in that a UI may need the peak data to be ready
1773 for the data that was recorded and this isn't interlocked with that
1774 process. this problem is deferred to the UI.
1777 _playlist->Modified();
1781 /* Register a new region with the Session that
1782 describes the entire source. Do this first
1783 so that any sub-regions will obviously be
1784 children of this one (later!)
1788 region = new AudioRegion (srcs, channels[0].write_source->last_capture_start_frame(), total_capture,
1789 region_name_from_path (channels[0].write_source->name()),
1790 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
1792 region->special_set_position (capture_info.front()->start);
1796 catch (failed_constructor& err) {
1797 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1801 _last_capture_regions.push_back (region);
1803 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1805 XMLNode &before = _playlist->get_state();
1806 _playlist->freeze ();
1808 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1811 _session.region_name (region_name, channels[0].write_source->name(), false);
1813 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1816 region = new AudioRegion (srcs, buffer_position, (*ci)->frames, region_name);
1819 catch (failed_constructor& err) {
1820 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1821 continue; /* XXX is this OK? */
1824 _last_capture_regions.push_back (region);
1826 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1828 i_am_the_modifier++;
1829 _playlist->add_region (*region, (*ci)->start);
1830 i_am_the_modifier--;
1832 buffer_position += (*ci)->frames;
1836 XMLNode &after = _playlist->get_state();
1837 _session.add_command (new MementoCommand<Playlist>(*_playlist, before, after));
1840 mark_write_completed = true;
1842 reset_write_sources (mark_write_completed);
1845 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1849 capture_info.clear ();
1850 capture_start_frame = 0;
1854 AudioDiskstream::finish_capture (bool rec_monitors_input)
1856 was_recording = false;
1858 if (capture_captured == 0) {
1862 if (recordable() && destructive()) {
1863 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1865 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1866 (*chan).capture_transition_buf->get_write_vector(&transvec);
1869 if (transvec.len[0] > 0) {
1870 transvec.buf[0]->type = CaptureEnd;
1871 transvec.buf[0]->capture_val = capture_captured;
1872 (*chan).capture_transition_buf->increment_write_ptr(1);
1876 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1882 CaptureInfo* ci = new CaptureInfo;
1884 ci->start = capture_start_frame;
1885 ci->frames = capture_captured;
1887 /* XXX theoretical race condition here. Need atomic exchange ?
1888 However, the circumstances when this is called right
1889 now (either on record-disable or transport_stopped)
1890 mean that no actual race exists. I think ...
1891 We now have a capture_info_lock, but it is only to be used
1892 to synchronize in the transport_stop and the capture info
1893 accessors, so that invalidation will not occur (both non-realtime).
1896 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1898 capture_info.push_back (ci);
1899 capture_captured = 0;
1903 AudioDiskstream::set_record_enabled (bool yn, void* src)
1905 bool rolling = _session.transport_speed() != 0.0f;
1907 if (!recordable() || !_session.record_enabling_legal()) {
1911 /* if we're turning on rec-enable, there needs to be an
1915 if (yn && channels[0].source == 0) {
1917 /* pick up connections not initiated *from* the IO object
1918 we're associated with.
1921 get_input_sources ();
1924 /* yes, i know that this not proof against race conditions, but its
1925 good enough. i think.
1928 if (record_enabled() != yn) {
1930 g_atomic_int_set (&_record_enabled, 1);
1931 capturing_sources.clear ();
1932 if (Config->get_use_hardware_monitoring()) {
1933 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1934 if ((*chan).source) {
1935 (*chan).source->request_monitor_input (!(_session.get_auto_input() && rolling));
1937 capturing_sources.push_back ((*chan).write_source);
1940 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1941 capturing_sources.push_back ((*chan).write_source);
1946 g_atomic_int_set (&_record_enabled, 0);
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 (false);
1954 capturing_sources.clear ();
1957 record_enable_changed (src); /* EMIT SIGNAL */
1962 AudioDiskstream::get_state ()
1964 XMLNode* node = new XMLNode ("AudioDiskstream");
1966 LocaleGuard lg (X_("POSIX"));
1968 snprintf (buf, sizeof(buf), "0x%x", _flags);
1969 node->add_property ("flags", buf);
1971 snprintf (buf, sizeof(buf), "%zd", channels.size());
1972 node->add_property ("channels", buf);
1974 node->add_property ("playlist", _playlist->name());
1976 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1977 node->add_property ("speed", buf);
1979 node->add_property("name", _name);
1980 snprintf (buf, sizeof(buf), "%" PRIu64, id());
1981 node->add_property("id", buf);
1983 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1985 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1986 XMLNode* cs_grandchild;
1988 for (vector<AudioFileSource*>::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1989 cs_grandchild = new XMLNode (X_("file"));
1990 cs_grandchild->add_property (X_("path"), (*i)->path());
1991 cs_child->add_child_nocopy (*cs_grandchild);
1994 /* store the location where capture will start */
1998 if (_session.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1999 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
2001 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
2004 cs_child->add_property (X_("at"), buf);
2005 node->add_child_nocopy (*cs_child);
2009 node->add_child_copy (*_extra_xml);
2016 AudioDiskstream::set_state (const XMLNode& node)
2018 const XMLProperty* prop;
2019 XMLNodeList nlist = node.children();
2020 XMLNodeIterator niter;
2021 uint32_t nchans = 1;
2022 XMLNode* capture_pending_node = 0;
2023 LocaleGuard lg (X_("POSIX"));
2025 in_set_state = true;
2027 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2028 if ((*niter)->name() == IO::state_node_name) {
2029 deprecated_io_node = new XMLNode (**niter);
2032 if ((*niter)->name() == X_("CapturingSources")) {
2033 capture_pending_node = *niter;
2037 /* prevent write sources from being created */
2039 in_set_state = true;
2041 if ((prop = node.property ("name")) != 0) {
2042 _name = prop->value();
2045 if (deprecated_io_node) {
2046 if ((prop = deprecated_io_node->property ("id")) != 0) {
2047 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2050 if ((prop = node.property ("id")) != 0) {
2051 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
2055 if ((prop = node.property ("flags")) != 0) {
2056 _flags = strtol (prop->value().c_str(), 0, 0);
2059 if ((prop = node.property ("channels")) != 0) {
2060 nchans = atoi (prop->value().c_str());
2063 // create necessary extra channels
2064 // we are always constructed with one
2065 // and we always need one
2067 if (nchans > _n_channels) {
2069 // we need to add new channel infos
2070 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2072 int diff = nchans - channels.size();
2074 for (int i=0; i < diff; ++i) {
2078 } else if (nchans < _n_channels) {
2080 // we need to get rid of channels
2081 //LockMonitor lm (state_lock, __LINE__, __FILE__);
2083 int diff = channels.size() - nchans;
2085 for (int i = 0; i < diff; ++i) {
2090 if ((prop = node.property ("playlist")) == 0) {
2095 bool had_playlist = (_playlist != 0);
2097 if (find_and_use_playlist (prop->value())) {
2101 if (!had_playlist) {
2102 _playlist->set_orig_diskstream_id (_id);
2105 if (!destructive() && capture_pending_node) {
2106 /* destructive streams have one and only one source per channel,
2107 and so they never end up in pending capture in any useful
2110 use_pending_capture_data (*capture_pending_node);
2115 if ((prop = node.property ("speed")) != 0) {
2116 double sp = atof (prop->value().c_str());
2118 if (realtime_set_speed (sp, false)) {
2119 non_realtime_set_speed ();
2123 _n_channels = channels.size();
2125 in_set_state = false;
2127 /* make sure this is clear before we do anything else */
2129 capturing_sources.clear ();
2131 /* write sources are handled when we handle the input set
2132 up of the IO that owns this DS (::non_realtime_input_change())
2135 in_set_state = false;
2141 AudioDiskstream::use_new_write_source (uint32_t n)
2143 if (!recordable()) {
2147 if (n >= channels.size()) {
2148 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2152 ChannelInfo &chan = channels[n];
2154 if (chan.write_source) {
2156 if (AudioFileSource::is_empty (chan.write_source->path())) {
2157 chan.write_source->mark_for_remove ();
2158 chan.write_source->release();
2159 delete chan.write_source;
2161 chan.write_source->release();
2162 chan.write_source = 0;
2167 if ((chan.write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2168 throw failed_constructor();
2172 catch (failed_constructor &err) {
2173 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2174 chan.write_source = 0;
2178 chan.write_source->use ();
2180 /* do not remove destructive files even if they are empty */
2182 chan.write_source->set_allow_remove_if_empty (!destructive());
2188 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2190 ChannelList::iterator chan;
2193 if (!recordable()) {
2197 capturing_sources.clear ();
2199 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2200 if (!destructive()) {
2202 if ((*chan).write_source && mark_write_complete) {
2203 (*chan).write_source->mark_streaming_write_completed ();
2205 use_new_write_source (n);
2207 if (record_enabled()) {
2208 capturing_sources.push_back ((*chan).write_source);
2212 if ((*chan).write_source == 0) {
2213 use_new_write_source (n);
2218 if (destructive()) {
2220 /* we now have all our write sources set up, so create the
2221 playlist's single region.
2224 if (_playlist->empty()) {
2225 setup_destructive_playlist ();
2231 AudioDiskstream::rename_write_sources ()
2233 ChannelList::iterator chan;
2236 for (chan = channels.begin(), n = 0; chan != channels.end(); ++chan, ++n) {
2237 if ((*chan).write_source != 0) {
2238 (*chan).write_source->set_name (_name, destructive());
2239 /* XXX what to do if one of them fails ? */
2247 AudioDiskstream::set_block_size (jack_nframes_t nframes)
2249 if (_session.get_block_size() > speed_buffer_size) {
2250 speed_buffer_size = _session.get_block_size();
2252 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2253 if ((*chan).speed_buffer) delete [] (*chan).speed_buffer;
2254 (*chan).speed_buffer = new Sample[speed_buffer_size];
2257 allocate_temporary_buffers ();
2261 AudioDiskstream::allocate_temporary_buffers ()
2263 /* make sure the wrap buffer is at least large enough to deal
2264 with the speeds up to 1.2, to allow for micro-variation
2265 when slaving to MTC, SMPTE etc.
2268 double sp = max (fabsf (_actual_speed), 1.2f);
2269 jack_nframes_t required_wrap_size = (jack_nframes_t) floor (_session.get_block_size() * sp) + 1;
2271 if (required_wrap_size > wrap_buffer_size) {
2273 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2274 if ((*chan).playback_wrap_buffer) delete [] (*chan).playback_wrap_buffer;
2275 (*chan).playback_wrap_buffer = new Sample[required_wrap_size];
2276 if ((*chan).capture_wrap_buffer) delete [] (*chan).capture_wrap_buffer;
2277 (*chan).capture_wrap_buffer = new Sample[required_wrap_size];
2280 wrap_buffer_size = required_wrap_size;
2285 AudioDiskstream::monitor_input (bool yn)
2287 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2289 if ((*chan).source) {
2290 (*chan).source->request_monitor_input (yn);
2296 AudioDiskstream::set_capture_offset ()
2299 /* can't capture, so forget it */
2303 _capture_offset = _io->input_latency();
2307 AudioDiskstream::set_persistent_align_style (AlignStyle a)
2309 _persistent_alignment_style = a;
2313 AudioDiskstream::set_align_style_from_io ()
2315 bool have_physical = false;
2321 get_input_sources ();
2323 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
2324 if ((*chan).source && (*chan).source->flags() & JackPortIsPhysical) {
2325 have_physical = true;
2330 if (have_physical) {
2331 set_align_style (ExistingMaterial);
2333 set_align_style (CaptureTime);
2338 AudioDiskstream::set_align_style (AlignStyle a)
2340 if (record_enabled() && _session.actively_recording()) {
2345 if (a != _alignment_style) {
2346 _alignment_style = a;
2347 AlignmentStyleChanged ();
2352 AudioDiskstream::add_channel ()
2354 /* XXX need to take lock??? */
2358 init_channel (chan);
2360 chan.speed_buffer = new Sample[speed_buffer_size];
2361 chan.playback_wrap_buffer = new Sample[wrap_buffer_size];
2362 chan.capture_wrap_buffer = new Sample[wrap_buffer_size];
2364 channels.push_back (chan);
2366 _n_channels = channels.size();
2372 AudioDiskstream::remove_channel ()
2374 if (channels.size() > 1) {
2375 /* XXX need to take lock??? */
2376 ChannelInfo & chan = channels.back();
2377 destroy_channel (chan);
2378 channels.pop_back();
2380 _n_channels = channels.size();
2388 AudioDiskstream::playback_buffer_load () const
2390 return (float) ((double) channels.front().playback_buf->read_space()/
2391 (double) channels.front().playback_buf->bufsize());
2395 AudioDiskstream::capture_buffer_load () const
2397 return (float) ((double) channels.front().capture_buf->write_space()/
2398 (double) channels.front().capture_buf->bufsize());
2402 AudioDiskstream::set_loop (Location *location)
2405 if (location->start() >= location->end()) {
2406 error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
2411 loop_location = location;
2413 LoopSet (location); /* EMIT SIGNAL */
2418 AudioDiskstream::get_capture_start_frame (uint32_t n)
2420 Glib::Mutex::Lock lm (capture_info_lock);
2422 if (capture_info.size() > n) {
2423 return capture_info[n]->start;
2426 return capture_start_frame;
2431 AudioDiskstream::get_captured_frames (uint32_t n)
2433 Glib::Mutex::Lock lm (capture_info_lock);
2435 if (capture_info.size() > n) {
2436 return capture_info[n]->frames;
2439 return capture_captured;
2444 AudioDiskstream::punch_in ()
2449 AudioDiskstream::punch_out ()
2454 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2456 const XMLProperty* prop;
2457 XMLNodeList nlist = node.children();
2458 XMLNodeIterator niter;
2459 AudioFileSource* fs;
2460 AudioFileSource* first_fs = 0;
2461 AudioRegion::SourceList pending_sources;
2462 jack_nframes_t position;
2464 if ((prop = node.property (X_("at"))) == 0) {
2468 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2472 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2473 if ((*niter)->name() == X_("file")) {
2475 if ((prop = (*niter)->property (X_("path"))) == 0) {
2480 fs = new SndFileSource (prop->value(),
2481 Config->get_native_file_data_format(),
2482 Config->get_native_file_header_format(),
2483 _session.frame_rate());
2486 catch (failed_constructor& err) {
2487 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2488 _name, prop->value())
2493 pending_sources.push_back (fs);
2495 if (first_fs == 0) {
2499 fs->set_captured_for (_name);
2503 if (pending_sources.size() == 0) {
2504 /* nothing can be done */
2508 if (pending_sources.size() != _n_channels) {
2509 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2514 AudioRegion* region;
2517 region = new AudioRegion (pending_sources, 0, first_fs->length(),
2518 region_name_from_path (first_fs->name()),
2519 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile));
2521 region->special_set_position (0);
2524 catch (failed_constructor& err) {
2525 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2533 region = new AudioRegion (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name()));
2536 catch (failed_constructor& err) {
2537 error << string_compose (_("%1: cannot create region from pending capture sources"),
2544 _playlist->add_region (*region, position);
2550 AudioDiskstream::set_roll_delay (jack_nframes_t nframes)
2552 _roll_delay = nframes;
2556 AudioDiskstream::set_destructive (bool yn)
2558 if (yn != destructive()) {
2559 reset_write_sources (true, true);
2561 _flags |= Destructive;
2563 _flags &= ~Destructive;