2 Copyright (C) 2009-2016 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.
21 #include "pbd/memento_command.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/audioplaylist.h"
25 #include "ardour/audio_buffer.h"
26 #include "ardour/butler.h"
27 #include "ardour/debug.h"
28 #include "ardour/disk_reader.h"
29 #include "ardour/midi_ring_buffer.h"
30 #include "ardour/midi_playlist.h"
31 #include "ardour/playlist.h"
32 #include "ardour/playlist_factory.h"
33 #include "ardour/session.h"
34 #include "ardour/session_playlists.h"
36 using namespace ARDOUR;
40 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
42 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
43 : DiskIOProcessor (s, str, f)
47 , overwrite_offset (0)
48 , _pending_overwrite (false)
49 , overwrite_queued (false)
52 , _monitoring_choice (MonitorDisk)
53 , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
54 , _frames_written_to_ringbuffer (0)
55 , _frames_read_from_ringbuffer (0)
59 DiskReader::~DiskReader ()
61 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 deleted\n", _name));
62 Glib::Threads::Mutex::Lock lm (state_lock);
64 for (uint32_t n = 0; n < DataType::num_types; ++n) {
66 _playlists[n]->release ();
71 RCUWriter<ChannelList> writer (channels);
72 boost::shared_ptr<ChannelList> c = writer.get_copy();
74 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
87 DiskReader::allocate_working_buffers()
89 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
90 for disk i/o bandwidth) and then convert back into samples. These buffers
91 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
94 _mixdown_buffer = new Sample[2*1048576];
95 _gain_buffer = new gain_t[2*1048576];
99 DiskReader::free_working_buffers()
101 delete [] _mixdown_buffer;
102 delete [] _gain_buffer;
108 DiskReader::default_chunk_frames()
114 DiskReader::set_name (string const & str)
117 for (uint32_t n = 0; n < DataType::num_types; ++n) {
119 _playlists[n]->set_name (str);
122 SessionObject::set_name(str);
129 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
131 _roll_delay = nframes;
135 DiskReader::set_state (const XMLNode& node, int version)
137 XMLProperty const * prop;
139 if (DiskIOProcessor::set_state (node, version)) {
143 if ((prop = node.property ("audio-playlist")) == 0) {
147 if (find_and_use_playlist (DataType::AUDIO, prop->value())) {
151 if ((prop = node.property ("midi-playlist")) == 0) {
155 if (find_and_use_playlist (DataType::MIDI, prop->value())) {
162 /* Processor interface */
165 DiskReader::configure_io (ChanCount in, ChanCount out)
167 Glib::Threads::Mutex::Lock lm (state_lock);
169 RCUWriter<ChannelList> writer (channels);
170 boost::shared_ptr<ChannelList> c = writer.get_copy();
172 uint32_t n_audio = in.n_audio();
174 if (n_audio > c->size()) {
175 add_channel_to (c, n_audio - c->size());
176 } else if (n_audio < c->size()) {
177 remove_channel_from (c, c->size() - n_audio);
180 if (in.n_midi() > 0 && !_midi_buf) {
181 const size_t size = _session.butler()->midi_diskstream_buffer_size();
182 _midi_buf = new MidiRingBuffer<framepos_t>(size);
183 midi_interpolation.add_channel_to (0,0);
186 Processor::configure_io (in, out);
192 DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
194 if (in.n_midi() != 0 && in.n_midi() != 1) {
195 /* we only support zero or 1 MIDI stream */
200 /* currently no way to deliver different channels that we receive */
208 DiskReader::realtime_handle_transport_stopped ()
213 DiskReader::realtime_locate ()
218 DiskReader::set_loop (Location *location)
221 if (location->start() >= location->end()) {
222 error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
227 loop_location = location;
229 LoopSet (location); /* EMIT SIGNAL */
234 DiskReader::buffer_load () const
236 /* Note: for MIDI it's not trivial to differentiate the following two cases:
238 1. The playback buffer is empty because the system has run out of time to fill it.
239 2. The playback buffer is empty because there is no more data on the playlist.
241 If we use a simple buffer load computation, we will report that the MIDI diskstream
242 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
243 are so low compared to audio, just use the audio value here.
246 boost::shared_ptr<ChannelList> c = channels.reader();
249 /* no channels, so no buffers, so completely full and ready to playback, sir! */
253 PBD::RingBufferNPT<Sample> * b = c->front()->buf;
254 return (float) ((double) b->read_space() / (double) b->bufsize());
258 DiskReader::adjust_buffering ()
260 boost::shared_ptr<ChannelList> c = channels.reader();
262 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
263 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
267 DiskReader::ChannelInfo::ChannelInfo (framecnt_t bufsize, framecnt_t speed_size, framecnt_t wrap_size)
271 speed_buffer = new Sample[speed_size];
272 wrap_buffer = new Sample[wrap_size];
274 buf = new RingBufferNPT<Sample> (bufsize);
276 /* touch the ringbuffer buffer, which will cause
277 them to be mapped into locked physical RAM if
278 we're running with mlockall(). this doesn't do
282 memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
286 DiskReader::ChannelInfo::resize (framecnt_t bufsize)
289 buf = new RingBufferNPT<Sample> (bufsize);
290 memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
293 DiskReader::ChannelInfo::~ChannelInfo ()
295 delete [] speed_buffer;
298 delete [] wrap_buffer;
306 DiskReader::set_block_size (pframes_t /*nframes*/)
308 if (_session.get_block_size() > speed_buffer_size) {
309 speed_buffer_size = _session.get_block_size();
310 boost::shared_ptr<ChannelList> c = channels.reader();
312 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
313 delete [] (*chan)->speed_buffer;
314 (*chan)->speed_buffer = new Sample[speed_buffer_size];
317 allocate_temporary_buffers ();
322 DiskReader::allocate_temporary_buffers ()
324 /* make sure the wrap buffer is at least large enough to deal
325 with the speeds up to 1.2, to allow for micro-variation
326 when slaving to MTC, Timecode etc.
329 double const sp = max (fabs (_actual_speed), 1.2);
330 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
332 if (required_wrap_size > wrap_buffer_size) {
334 boost::shared_ptr<ChannelList> c = channels.reader();
336 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
337 if ((*chan)->wrap_buffer) {
338 delete [] (*chan)->wrap_buffer;
340 (*chan)->wrap_buffer = new Sample[required_wrap_size];
343 wrap_buffer_size = required_wrap_size;
349 DiskReader::playlist_changed (const PropertyChange&)
351 playlist_modified ();
355 DiskReader::playlist_modified ()
357 if (!i_am_the_modifier && !overwrite_queued) {
358 // !!!! _session.request_overwrite_buffer (this);
359 overwrite_queued = true;
364 DiskReader::playlist_deleted (boost::weak_ptr<Playlist> wpl)
366 boost::shared_ptr<Playlist> pl (wpl.lock());
372 for (uint32_t n = 0; n < DataType::num_types; ++n) {
373 if (pl == _playlists[n]) {
375 /* this catches an ordering issue with session destruction. playlists
376 are destroyed before disk readers. we have to invalidate any handles
377 we have to the playlist.
379 _playlists[n].reset ();
385 boost::shared_ptr<AudioPlaylist>
386 DiskReader::audio_playlist () const
388 return boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
391 boost::shared_ptr<MidiPlaylist>
392 DiskReader::midi_playlist () const
394 return boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
398 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
404 bool prior_playlist = false;
407 Glib::Threads::Mutex::Lock lm (state_lock);
409 if (playlist == _playlists[dt]) {
413 playlist_connections.drop_connections ();
415 if (_playlists[dt]) {
416 _playlists[dt]->release();
417 prior_playlist = true;
420 _playlists[dt] = playlist;
423 playlist->ContentsChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
424 playlist->LayeringChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
425 playlist->DropReferences.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_deleted, this, boost::weak_ptr<Playlist>(playlist)));
426 playlist->RangesMoved.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_ranges_moved, this, _1, _2));
429 /* don't do this if we've already asked for it *or* if we are setting up
430 the diskstream for the very first time - the input changed handling will
431 take care of the buffer refill.
434 if (!overwrite_queued && prior_playlist) {
435 // !!! _session.request_overwrite_buffer (this);
436 overwrite_queued = true;
439 PlaylistChanged (dt); /* EMIT SIGNAL */
440 _session.set_dirty ();
446 DiskReader::find_and_use_playlist (DataType dt, const string& name)
448 boost::shared_ptr<Playlist> playlist;
450 if ((playlist = _session.playlists->by_name (name)) == 0) {
451 playlist = PlaylistFactory::create (dt, _session, name);
455 error << string_compose(_("DiskReader: \"%1\" isn't an playlist"), name) << endmsg;
459 return use_playlist (dt, playlist);
463 DiskReader::use_new_playlist (DataType dt)
466 boost::shared_ptr<Playlist> playlist = _playlists[dt];
469 newname = Playlist::bump_name (playlist->name(), _session);
471 newname = Playlist::bump_name (_name, _session);
474 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (dt, _session, newname, hidden()));
480 return use_playlist (dt, playlist);
484 DiskReader::use_copy_playlist (DataType dt)
486 assert (_playlists[dt]);
488 if (_playlists[dt] == 0) {
489 error << string_compose(_("DiskReader %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
494 boost::shared_ptr<Playlist> playlist;
496 newname = Playlist::bump_name (_playlists[dt]->name(), _session);
498 if ((playlist = PlaylistFactory::create (_playlists[dt], newname)) == 0) {
502 playlist->reset_shares();
504 return use_playlist (dt, playlist);
508 /** Do some record stuff [not described in this comment!]
511 * - Setup playback_distance with the nframes, or nframes adjusted
512 * for current varispeed, if appropriate.
513 * - Setup current_buffer in each ChannelInfo to point to data
514 * that someone can read playback_distance worth of data from.
517 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
518 double speed, pframes_t nframes, bool result_required)
521 boost::shared_ptr<ChannelList> c = channels.reader();
522 ChannelList::iterator chan;
523 framecnt_t playback_distance = 0;
525 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
531 for (chan = c->begin(); chan != c->end(); ++chan) {
532 (*chan)->current_buffer = 0;
535 const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
537 if (need_disk_signal) {
539 /* we're doing playback */
541 framecnt_t necessary_samples;
543 if (_actual_speed != 1.0) {
544 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
546 necessary_samples = nframes;
549 for (chan = c->begin(); chan != c->end(); ++chan) {
550 (*chan)->buf->get_read_vector (&(*chan)->read_vector);
555 /* Setup current_buffer in each ChannelInfo to point to data that someone
556 can read necessary_samples (== nframes at a transport speed of 1) worth of data
560 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
562 ChannelInfo* chaninfo (*chan);
564 if (necessary_samples <= (framecnt_t) chaninfo->read_vector.len[0]) {
565 /* There are enough samples in the first part of the ringbuffer */
566 chaninfo->current_buffer = chaninfo->read_vector.buf[0];
569 framecnt_t total = chaninfo->read_vector.len[0] + chaninfo->read_vector.len[1];
571 if (necessary_samples > total) {
572 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
573 cerr << "underrun for " << _name << endl;
574 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
575 DEBUG_THREAD_SELF, name(), total));
581 /* We have enough samples, but not in one lump. Coalesce the two parts
582 into one in wrap_buffer in our ChannelInfo, and specify that
583 as our current_buffer.
586 assert(wrap_buffer_size >= necessary_samples);
588 /* Copy buf[0] from buf */
589 memcpy ((char *) chaninfo->wrap_buffer,
590 chaninfo->read_vector.buf[0],
591 chaninfo->read_vector.len[0] * sizeof (Sample));
593 /* Copy buf[1] from buf */
594 memcpy (chaninfo->wrap_buffer + chaninfo->read_vector.len[0],
595 chaninfo->read_vector.buf[1],
596 (necessary_samples - chaninfo->read_vector.len[0])
599 chaninfo->current_buffer = chaninfo->wrap_buffer;
604 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
606 interpolation.set_speed (_target_speed);
609 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
610 ChannelInfo* chaninfo (*chan);
612 playback_distance = interpolation.interpolate (
613 channel, nframes, chaninfo->current_buffer, chaninfo->speed_buffer);
615 chaninfo->current_buffer = chaninfo->speed_buffer;
619 playback_distance = nframes;
622 _speed = _target_speed;
625 if (need_disk_signal) {
627 /* copy data over to buffer set */
629 size_t n_buffers = bufs.count().n_audio();
630 size_t n_chans = c->size();
631 gain_t scaling = 1.0f;
633 if (n_chans > n_buffers) {
634 scaling = ((float) n_buffers)/n_chans;
637 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
639 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
640 ChannelInfo* chaninfo (*chan);
643 if (scaling != 1.0f) {
644 buf.read_from_with_gain (chaninfo->current_buffer, nframes, scaling);
646 buf.read_from (chaninfo->current_buffer, nframes);
649 if (scaling != 1.0f) {
650 buf.accumulate_with_gain_from (chaninfo->current_buffer, nframes, scaling);
652 buf.accumulate_from (chaninfo->current_buffer, nframes);
657 /* extra buffers will already be silent, so leave them alone */
660 _need_butler = false;
662 if (_actual_speed < 0.0) {
663 playback_sample -= playback_distance;
665 playback_sample += playback_distance;
668 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
669 (*chan)->buf->increment_read_ptr (playback_distance);
674 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
678 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
684 /* MIDI data handling */
686 if (_actual_speed != 1.0f && _target_speed > 0) {
688 interpolation.set_speed (_target_speed);
690 playback_distance = midi_interpolation.distance (nframes);
693 playback_distance = nframes;
696 if (need_disk_signal && !_session.declick_out_pending()) {
698 /* copy the diskstream data to all output buffers */
700 MidiBuffer& mbuf (bufs.get_midi (0));
701 get_playback (mbuf, playback_distance);
703 /* leave the audio count alone */
704 ChanCount cnt (DataType::MIDI, 1);
705 cnt.set (DataType::AUDIO, bufs.count().n_audio());
706 bufs.set_count (cnt);
709 if (_target_speed > 0 && _actual_speed != 1.0f) {
710 MidiBuffer& mbuf (bufs.get_midi (0));
711 for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
712 MidiBuffer::TimeType *tme = i.timeptr();
713 *tme = (*tme) * nframes / playback_distance;
718 /* MIDI butler needed part */
720 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
721 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
724 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
725 " = " << frames_written - frames_read
726 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
729 /* frames_read will generally be less than frames_written, but
730 * immediately after an overwrite, we can end up having read some data
731 * before we've written any. we don't need to trip an assert() on this,
732 * but we do need to check so that the decision on whether or not we
733 * need the butler is done correctly.
738 * Doing heavy GUI operations[1] can stall also the butler.
739 * The RT-thread meanwhile will happily continue and
740 * ‘frames_read’ (from buffer to output) will become larger
741 * than ‘frames_written’ (from disk to buffer).
743 * The disk-stream is now behind..
745 * In those cases the butler needs to be summed to refill the buffer (done now)
746 * AND we need to skip (frames_read - frames_written). ie remove old events
747 * before playback_sample from the rinbuffer.
749 * [1] one way to do so is described at #6170.
750 * For me just popping up the context-menu on a MIDI-track header
751 * of a track with a large (think beethoven :) midi-region also did the
752 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
754 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
757 if (frames_read <= frames_written) {
758 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
765 /* make sure bufs shows whatever data we had available */
768 cnt.set (DataType::MIDI, 1);
769 cnt.set (DataType::AUDIO, bufs.count().n_audio());
770 bufs.set_count (cnt);
774 DiskReader::calculate_playback_distance (pframes_t nframes)
776 frameoffset_t playback_distance = nframes;
778 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
779 interpolation.set_speed (_target_speed);
780 boost::shared_ptr<ChannelList> c = channels.reader();
782 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
783 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
786 playback_distance = nframes;
789 if (_actual_speed < 0.0) {
790 return -playback_distance;
792 return playback_distance;
797 DiskReader::set_pending_overwrite (bool yn)
799 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
801 _pending_overwrite = yn;
803 overwrite_frame = playback_sample;
805 boost::shared_ptr<ChannelList> c = channels.reader ();
807 overwrite_offset = c->front()->buf->get_read_ptr();
812 DiskReader::overwrite_existing_buffers ()
816 boost::shared_ptr<ChannelList> c = channels.reader();
818 overwrite_queued = false;
824 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
826 /* assume all are the same size */
827 framecnt_t size = c->front()->buf->bufsize();
829 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
830 std::auto_ptr<float> gain_buffer (new float[size]);
832 /* reduce size so that we can fill the buffer correctly (ringbuffers
833 can only handle size-1, otherwise they appear to be empty)
840 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
842 start = overwrite_frame;
843 framecnt_t cnt = size;
845 /* to fill the buffer without resetting the playback sample, we need to
846 do it one or two chunks (normally two).
848 |----------------------------------------------------------------------|
852 |<- second chunk->||<----------------- first chunk ------------------>|
856 framecnt_t to_read = size - overwrite_offset;
858 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
859 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
860 id(), size, playback_sample) << endmsg;
868 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
869 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
870 id(), size, playback_sample) << endmsg;
882 if (_midi_buf && _playlists[DataType::MIDI]) {
884 /* Clear the playback buffer contents. This is safe as long as the butler
885 thread is suspended, which it should be.
888 _midi_buf->reset_tracker ();
890 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
891 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
893 /* Resolve all currently active notes in the playlist. This is more
894 aggressive than it needs to be: ideally we would only resolve what is
895 absolutely necessary, but this seems difficult and/or impossible without
896 having the old data or knowing what change caused the overwrite.
898 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
900 midi_read (overwrite_frame, _chunk_frames, false);
902 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
905 _pending_overwrite = false;
911 DiskReader::non_realtime_locate (framepos_t location)
913 /* now refill channel buffers */
915 if (speed() != 1.0f || speed() != -1.0f) {
916 seek ((framepos_t) (location * (double) speed()), true);
918 seek (location, true);
923 DiskReader::seek (framepos_t frame, bool complete_refill)
927 ChannelList::iterator chan;
928 boost::shared_ptr<ChannelList> c = channels.reader();
930 Glib::Threads::Mutex::Lock lm (state_lock);
932 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
933 (*chan)->buf->reset ();
936 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
937 /* we haven't read anything since the last seek,
938 so flush all note trackers to prevent
945 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
946 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
948 playback_sample = frame;
951 if (complete_refill) {
952 /* call _do_refill() to refill the entire buffer, using
953 the largest reads possible.
955 while ((ret = do_refill_with_alloc (false)) > 0) ;
957 /* call _do_refill() to refill just one chunk, and then
960 ret = do_refill_with_alloc (true);
968 DiskReader::can_internal_playback_seek (framecnt_t distance)
972 ChannelList::iterator chan;
973 boost::shared_ptr<ChannelList> c = channels.reader();
975 for (chan = c->begin(); chan != c->end(); ++chan) {
976 if ((*chan)->buf->read_space() < (size_t) distance) {
983 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
984 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
986 return ((frames_written - frames_read) < distance);
990 DiskReader::internal_playback_seek (framecnt_t distance)
992 ChannelList::iterator chan;
993 boost::shared_ptr<ChannelList> c = channels.reader();
995 for (chan = c->begin(); chan != c->end(); ++chan) {
996 (*chan)->buf->increment_read_ptr (::llabs(distance));
999 playback_sample += distance;
1005 void swap_by_ptr (Sample *first, Sample *last)
1007 while (first < last) {
1008 Sample tmp = *first;
1014 /** Read some data for 1 channel from our playlist into a buffer.
1015 * @param buf Buffer to write to.
1016 * @param start Session frame to start reading from; updated to where we end up
1018 * @param cnt Count of samples to read.
1019 * @param reversed true if we are running backwards, otherwise false.
1022 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
1023 framepos_t& start, framecnt_t cnt,
1024 int channel, bool reversed)
1026 framecnt_t this_read = 0;
1027 bool reloop = false;
1028 framepos_t loop_end = 0;
1029 framepos_t loop_start = 0;
1030 framecnt_t offset = 0;
1033 /* XXX we don't currently play loops in reverse. not sure why */
1037 framecnt_t loop_length = 0;
1039 /* Make the use of a Location atomic for this read operation.
1041 Note: Locations don't get deleted, so all we care about
1042 when I say "atomic" is that we are always pointing to
1043 the same one and using a start/length values obtained
1047 if ((loc = loop_location) != 0) {
1048 loop_start = loc->start();
1049 loop_end = loc->end();
1050 loop_length = loop_end - loop_start;
1053 /* if we are looping, ensure that the first frame we read is at the correct
1054 position within the loop.
1057 if (loc && start >= loop_end) {
1058 start = loop_start + ((start - loop_start) % loop_length);
1067 /* We need this while loop in case we hit a loop boundary, in which case our read from
1068 the playlist must be split into more than one section.
1073 /* take any loop into account. we can't read past the end of the loop. */
1075 if (loc && (loop_end - start < cnt)) {
1076 this_read = loop_end - start;
1083 if (this_read == 0) {
1087 this_read = min(cnt,this_read);
1089 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1090 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1097 swap_by_ptr (buf, buf + this_read - 1);
1101 /* if we read to the end of the loop, go back to the beginning */
1111 offset += this_read;
1118 DiskReader::_do_refill_with_alloc (bool partial_fill)
1120 /* We limit disk reads to at most 4MB chunks, which with floating point
1121 samples would be 1M samples. But we might use 16 or 14 bit samples,
1122 in which case 4MB is more samples than that. Therefore size this for
1123 the smallest sample value .. 4MB = 2M samples (16 bit).
1127 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
1128 std::auto_ptr<float> gain_buf (new float[2*1048576]);
1130 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
1137 return refill_midi ();
1141 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1143 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
1149 return refill_midi ();
1153 /** Get some more data from disk and put it in our channels' bufs,
1154 * if there is suitable space in them.
1156 * If fill_level is non-zero, then we will refill the buffer so that there is
1157 * still at least fill_level samples of space left to be filled. This is used
1158 * after locates so that we do not need to wait to fill the entire buffer.
1163 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1165 if (_session.state_of_the_state() & Session::Loading) {
1171 RingBufferNPT<Sample>::rw_vector vector;
1172 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1173 framecnt_t total_space;
1174 framecnt_t zero_fill;
1176 ChannelList::iterator i;
1177 boost::shared_ptr<ChannelList> c = channels.reader();
1180 /* do not read from disk while session is marked as Loading, to avoid
1181 useless redundant I/O.
1188 assert(mixdown_buffer);
1189 assert(gain_buffer);
1196 c->front()->buf->get_write_vector (&vector);
1198 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1199 /* nowhere to write to */
1204 if (fill_level < total_space) {
1205 total_space -= fill_level;
1207 /* we can't do anything with it */
1212 /* if we're running close to normal speed and there isn't enough
1213 space to do disk_read_chunk_frames of I/O, then don't bother.
1215 at higher speeds, just do it because the sync between butler
1216 and audio thread may not be good enough.
1218 Note: it is a design assumption that disk_read_chunk_frames is smaller
1219 than the playback buffer size, so this check should never trip when
1220 the playback buffer is empty.
1223 if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
1227 /* when slaved, don't try to get too close to the read pointer. this
1228 leaves space for the buffer reversal to have something useful to
1232 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
1238 if (file_frame == 0) {
1240 /* at start: nothing to do but fill with silence */
1242 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1244 ChannelInfo* chan (*i);
1245 chan->buf->get_write_vector (&vector);
1246 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1247 if (vector.len[1]) {
1248 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1250 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1255 if (file_frame < total_space) {
1257 /* too close to the start: read what we can,
1258 and then zero fill the rest
1261 zero_fill = total_space - file_frame;
1262 total_space = file_frame;
1271 if (file_frame == max_framepos) {
1273 /* at end: nothing to do but fill with silence */
1275 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1277 ChannelInfo* chan (*i);
1278 chan->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->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1288 if (file_frame > max_framepos - total_space) {
1290 /* to close to the end: read what we can, and zero fill the rest */
1292 zero_fill = total_space - (max_framepos - file_frame);
1293 total_space = max_framepos - file_frame;
1300 framepos_t file_frame_tmp = 0;
1302 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1304 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1305 size_t total_bytes = total_space * bits_per_sample / 8;
1307 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1309 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1311 /* find nearest (lower) multiple of 16384 */
1313 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1315 /* now back to samples */
1317 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1319 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1320 // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1321 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
1323 // uint64_t before = g_get_monotonic_time ();
1324 // uint64_t elapsed;
1326 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1328 ChannelInfo* chan (*i);
1331 framecnt_t len1, len2;
1333 chan->buf->get_write_vector (&vector);
1335 if ((framecnt_t) vector.len[0] > samples_to_read) {
1337 /* we're not going to fill the first chunk, so certainly do not bother with the
1338 other part. it won't be connected with the part we do fill, as in:
1340 .... => writable space
1341 ++++ => readable space
1342 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1344 |......|+++++++++++++|...............................|
1349 So, just pretend that the buf1 part isn't there.
1359 file_frame_tmp = file_frame;
1361 buf1 = vector.buf[0];
1362 len1 = vector.len[0];
1363 buf2 = vector.buf[1];
1364 len2 = vector.len[1];
1366 to_read = min (ts, len1);
1367 to_read = min (to_read, (framecnt_t) samples_to_read);
1369 assert (to_read >= 0);
1373 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1378 chan->buf->increment_write_ptr (to_read);
1382 to_read = min (ts, len2);
1386 /* we read all of vector.len[0], but it wasn't the
1387 entire samples_to_read of data, so read some or
1388 all of vector.len[1] as well.
1391 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1396 chan->buf->increment_write_ptr (to_read);
1400 /* XXX: do something */
1405 // elapsed = g_get_monotonic_time () - before;
1406 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1408 file_frame = file_frame_tmp;
1409 assert (file_frame >= 0);
1411 ret = ((total_space - samples_to_read) > _chunk_frames);
1413 c->front()->buf->get_write_vector (&vector);
1420 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1422 /* If we're coming from an undo, it will have handled
1423 automation undo (it must, since automation-follows-regions
1424 can lose automation data). Hence we can do nothing here.
1432 if (!_track || Config->get_automation_follows_regions () == false) {
1436 list< Evoral::RangeMove<double> > movements;
1438 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1439 i != movements_frames.end();
1442 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1445 /* move panner automation */
1446 boost::shared_ptr<Pannable> pannable = _track->pannable();
1447 Evoral::ControlSet::Controls& c (pannable->controls());
1449 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1450 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1454 boost::shared_ptr<AutomationList> alist = ac->alist();
1455 if (!alist->size()) {
1458 XMLNode & before = alist->get_state ();
1459 bool const things_moved = alist->move_ranges (movements);
1461 _session.add_command (new MementoCommand<AutomationList> (
1462 *alist.get(), &before, &alist->get_state ()));
1465 /* move processor automation */
1466 _track->foreach_processor (boost::bind (&Diskstream::move_processor_automation, this, _1, movements_frames));
1471 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1473 boost::shared_ptr<Processor> processor (p.lock ());
1478 list< Evoral::RangeMove<double> > movements;
1479 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1480 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1483 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1485 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1486 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1490 XMLNode & before = al->get_state ();
1491 bool const things_moved = al->move_ranges (movements);
1493 _session.add_command (
1494 new MementoCommand<AutomationList> (
1495 *al.get(), &before, &al->get_state ()
1502 boost::shared_ptr<MidiBuffer>
1503 DiskReader::get_gui_feed_buffer () const
1505 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1507 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1508 b->copy (_gui_feed_buffer);
1513 DiskReader::reset_tracker ()
1515 _midi_buf->reset_tracker ();
1517 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1520 mp->reset_note_trackers ();
1525 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1527 _midi_buf->resolve_tracker(buffer, time);
1529 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1532 mp->reset_note_trackers ();
1537 DiskReader::flush_playback (framepos_t start, framepos_t end)
1539 _midi_buf->flush (start, end);
1540 g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
1543 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1544 * so that an event at playback_sample has time = 0
1547 DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
1551 Location* loc = loop_location;
1553 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1554 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1555 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1556 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1558 //cerr << "======== PRE ========\n";
1559 //_midi_buf->dump (cerr);
1560 //cerr << "----------------\n";
1562 size_t events_read = 0;
1565 framepos_t effective_start;
1567 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1568 effective_start = loop_range.squish (playback_sample);
1570 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1572 if (effective_start == loc->start()) {
1573 /* We need to turn off notes that may extend
1574 beyond the loop end.
1577 _midi_buf->resolve_tracker (dst, 0);
1580 /* for split-cycles we need to offset the events */
1582 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1584 /* end of loop is within the range we are reading, so
1585 split the read in two, and lie about the location
1589 framecnt_t first, second;
1591 first = loc->end() - effective_start;
1592 second = nframes - first;
1594 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1595 effective_start, loc->end(), first, second));
1598 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1599 effective_start, first));
1600 events_read = _midi_buf->read (dst, effective_start, first);
1604 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1605 loc->start(), second));
1606 events_read += _midi_buf->read (dst, loc->start(), second);
1610 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1611 effective_start, nframes));
1612 events_read = _midi_buf->read (dst, effective_start, effective_start + nframes);
1615 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1616 if (n_skipped > 0) {
1617 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1619 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1620 events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
1623 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1624 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1625 _name, events_read, playback_sample, playback_sample + nframes,
1626 _midi_buf->read_space(), _midi_buf->write_space(),
1627 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1629 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1631 //cerr << "======== POST ========\n";
1632 //_midi_buf->dump (cerr);
1633 //cerr << "----------------\n";
1636 /** Get the start, end, and length of a location "atomically".
1638 * Note: Locations don't get deleted, so all we care about when I say "atomic"
1639 * is that we are always pointing to the same one and using start/length values
1640 * obtained just once. Use this function to achieve this since location being
1641 * a parameter achieves this.
1644 get_location_times(const Location* location,
1650 *start = location->start();
1651 *end = location->end();
1652 *length = *end - *start;
1656 /** @a start is set to the new frame position (TIME) read up to */
1658 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1660 framecnt_t this_read = 0;
1661 framepos_t loop_end = 0;
1662 framepos_t loop_start = 0;
1663 framecnt_t loop_length = 0;
1664 Location* loc = loop_location;
1665 framepos_t effective_start = start;
1666 Evoral::Range<framepos_t>* loop_range (0);
1668 // MidiTrack* mt = dynamic_cast<MidiTrack*>(_track);
1669 // MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1670 MidiChannelFilter* filter = 0;
1672 frameoffset_t loop_offset = 0;
1674 if (!reversed && loc) {
1675 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1680 /* take any loop into account. we can't read past the end of the loop. */
1682 if (loc && !reversed) {
1685 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1688 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1689 position within the loop.
1692 effective_start = loop_range->squish (effective_start);
1694 if ((loop_end - effective_start) <= dur) {
1695 /* too close to end of loop to read "dur", so
1698 this_read = loop_end - effective_start;
1707 if (this_read == 0) {
1711 this_read = min (dur,this_read);
1713 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1715 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1716 error << string_compose(
1717 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1718 id(), this_read, start) << endmsg;
1722 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1726 // Swap note ons with note offs here. etc?
1727 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1728 // CC values etc. hard.
1732 /* adjust passed-by-reference argument (note: this is
1733 monotonic and does not reflect looping.
1737 /* similarly adjust effective_start, but this may be
1738 readjusted for seamless looping as we continue around
1741 effective_start += this_read;
1745 //offset += this_read;
1752 DiskReader::refill_midi ()
1755 size_t write_space = _midi_buf->write_space();
1756 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1758 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
1759 write_space, file_frame));
1761 /* no space to write */
1762 if (write_space == 0) {
1770 /* at end: nothing to do */
1771 if (file_frame == max_framepos) {
1775 uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1776 uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1778 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1782 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1784 to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1785 to_read = min (to_read, (framecnt_t) write_space);
1787 if (midi_read (file_frame, to_read, reversed)) {